Skip to content

Instantly share code, notes, and snippets.

@JankDev
Created April 19, 2020 16:15
Show Gist options
  • Save JankDev/deadcde8e0e9c184de365d3adf654d5e to your computer and use it in GitHub Desktop.
Save JankDev/deadcde8e0e9c184de365d3adf654d5e to your computer and use it in GitHub Desktop.
Reverse Polish Notation
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Scratch {
static double rnp(String pattern) {
return Pattern.compile(" ").splitAsStream(pattern)
.reduce(new LinkedList<>(), Scratch::accumulate, (doubles, acc) -> acc)
.get(0);
}
static LinkedList<Double> accumulate(LinkedList<Double> acc, String next) {
return switch (next) {
case "+" -> Stream.concat(List.of(acc.poll() + acc.poll()).stream(), acc.stream())
.collect(Collectors.toCollection(LinkedList::new));
case "-" -> {
var first = acc.poll();
var second = acc.poll();
yield Stream.concat(List.of(second - first).stream(), acc.stream())
.collect(Collectors.toCollection(LinkedList::new));
}
case "*" -> Stream.concat(List.of(acc.poll() * acc.poll()).stream(), acc.stream())
.collect(Collectors.toCollection(LinkedList::new));
default -> Stream.concat(List.of(Double.parseDouble(next)).stream(), acc.stream())
.collect(Collectors.toCollection(LinkedList::new));
};
}
public static void main(String[] args) {
System.out.println(rnp("90 34 12 33 55 66 + * - + -"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment