/blog-java-shunting-yard

An academic implenentation for the Shunting Yard Algorithm in Java

Primary LanguageJavaMIT LicenseMIT

"Academic" implementation for the Shunting Yard Algorithm in Java.

Usage:

import java.util.Arrays;
import java.util.List;

import static net.andreinc.shunting.yard.ShuntingYard.shuntingYard;
import static org.assertj.core.api.Assertions.assertThat;

// *****

List<String> given = Arrays.asList("( 1 + 2 ) * ( 3 / 4 ) ^ ( 5 + 6 )".split(" "));
List<String> expected = List.of("1", "2", "+", "3", "4", "/", "5", "6", "+", "^", "*");
List<String> computed = shuntingYard(given);

System.out.println("infix:" + given);
System.out.println("rpn (expected):" + expected);
System.out.println("rpn (computed):" + computed);

assertThat(computed).isEqualTo(expected);

Output:

infix:[(, 1, +, 2, ), *, (, 3, /, 4, ), ^, (, 5, +, 6, )]
rpn (expected):[1, 2, +, 3, 4, /, 5, 6, +, ^, *]
rpn (computed):[1, 2, +, 3, 4, /, 5, 6, +, ^, *]