This is a simple maze solver program.
.0........ .......... .0...0.0.0 ...0...0.. .......... .0.0...... .........0 ...F....0. .......... S.0...0...
this is the simple maze i’m working on. I implemented a solution to output cordinates of the path as follow.(cordinates aquired from a BFS algorithm)
Start - x = 9 y = 0 Move up to - x = 8 y = 0 Move up to - x = 7 y = 0 Move Right to - x = 7 y = 1 Move Right to - x = 7 y = 2 Move Right to - x = 7 y = 3 Finish
but I want to output like below(omit same direction and only output direction and last coordinate to same direction),
Start - x = 9 y = 0 Move up to - x = 7 y = 0 Move Right to- x = 7 y = 3 Finish
this all coordinates are allocated to a stack.below is my code,
System.out.println("Start - " + curr); curr = stack.pop(); while (!stack.isEmpty()) { System.out.println(curr); curr = stack.pop(); } System.out.println(curr); }
Advertisement
Answer
The simplest way is to define a function that takes two coordinates, and returns the direction, then iterate through the coordinates and check if there is a change compared to the next one.
public static String getDirection(int x1, int y1, int x2, int y2) { if(x1 == x2 && y1 > y2) return "up"; if(x1 == x2 && y1 < y2) return "down"; if(y1 == y2 && x1 < x2) return "right"; if(y1 == y2 && x1 > x2) return "left"; return "undecidable"; } // It is written so just for simplicity. // Use an array of Coord structs or something like that. public static void printDirections(int[] x, int[] y) { System.out.printf("Start - x = %d y = %dn", x[0], y[0]); String lastDirection = getDirection(x[0], y[0], x[1], y[1]); for(int i = 1; i < x.length - 1; i++) { String direction = getDirection(x[i], y[i], x[i + 1], y[i + 1]); if(!lastDirection.equals(direction)) { System.out.printf("Move %s to x = %d y = %d", lastDirection, x[i], y[i]); } lastDirection = direction; } System.out.printf("Move %s to x = %d y = %d", lastDirection, x[x.length - 1], y[y.length - 1]); }