Last active
April 12, 2017 01:02
-
-
Save bjhaid/3e41e60f387e5387d6040456ba0109e3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
class DirReduc { | |
static String inverse(String direction) { | |
String inv = ""; | |
switch (direction) { | |
case "NORTH": inv = "SOUTH"; | |
break; | |
case "SOUTH": inv = "NORTH"; | |
break; | |
case "EAST" : inv = "WEST"; | |
break; | |
case "WEST" : inv = "EAST"; | |
break; | |
} | |
return inv; | |
} | |
static String[] dirReduc(String[] arr) { | |
int size = arr.length; | |
int idx = 0; | |
Stack<String> stack = new Stack<String>(); | |
while (idx < size) { | |
if (!stack.empty() && stack.peek() == inverse(arr[idx])) { | |
stack.pop(); | |
} else { | |
stack.push(arr[idx]); | |
} | |
idx++; | |
} | |
return stack.toArray(new String[stack.size()]); | |
} | |
static void p(String [] arr) { | |
System.out.print("["); | |
for (int i = 0; i < arr.length; i++) { | |
if (i == arr.length - 1) { | |
System.out.print(arr[i]); | |
} else System.out.print(arr[i] + ", "); | |
} | |
System.out.print("]\n"); | |
} | |
public static void main(String [] argc) { | |
String[] arr = {"NORTH", "SOUTH", "EAST", "WEST"}; | |
p(dirReduc(arr)); | |
String[] arr1 = {"NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"}; | |
p(dirReduc(arr1)); | |
String[] arr2 = {"NORTH", "WEST", "SOUTH", "EAST"}; | |
p(dirReduc(arr2)); | |
String[] arr3 = {"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"}; | |
p(dirReduc(arr3)); | |
String[] arr4 = {"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"}; | |
p(dirReduc(arr4)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ javac DirReduc.java | |
$ java DirReduc | |
[] | |
[WEST, WEST] | |
[NORTH, WEST, SOUTH, EAST] | |
[WEST] | |
[] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment