Question

Please make this code workable and straight. this code does produce a proper output but just...

Please make this code workable and straight. this code does produce a proper output but just not in proper format. please solve this. thank you.

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; public class MyMaze { private int dimensionX, dimensionY; // dimension of maze private int gridDimensionX, gridDimensionY; // dimension of output grid private char[][] grid; // output grid private Cell[][] cells; // 2d array of Cells private Random random = new Random(); // The random object public MyMaze(int aDimension) { this(aDimension, aDimension); } public MyMaze(int xDimension, int yDimension) { dimensionX = 21; dimensionY = 70; gridDimensionX = 21 * 4 + 1; gridDimensionY = 70* 2 + 1; grid = new char[gridDimensionX][gridDimensionY]; init(); generateMaze(); } private void init() { cells = new Cell[dimensionX][dimensionY]; for (int x = 0; x < dimensionX; x++) { for (int y = 0; y < dimensionY; y++) { cells[x][y] = new Cell(x, y, false); // create cell (see Cell constructor) } } } private class Cell { int x, y; // coordinates ArrayList<Cell> neighbors = new ArrayList<>(); boolean visited = false;   Cell parent = null;   boolean inPath = false;    double travelled; double projectedDist; boolean wall = true; boolean open = true; Cell(int x, int y) { this(x, y, true); }    Cell(int x, int y, boolean isWall) { this.x = x; this.y = y; this.wall = isWall; } void addNeighbor(Cell other) { if (!this.neighbors.contains(other)) { this.neighbors.add(other); }         if (!other.neighbors.contains(this)) {             other.neighbors.add(this);         }     }         boolean isCellBelowNeighbor() {         return this.neighbors.contains(new Cell(this.x, this.y + 1));     }         boolean isCellRightNeighbor() {         return this.neighbors.contains(new Cell(this.x + 1, this.y));     }         @Override     public String toString() {         return String.format("Cell(%s, %s)", x, y);     }     @Override     public boolean equals(Object other) {         if (!(other instanceof Cell)) return false;         Cell otherCell = (Cell) other;         return (this.x == otherCell.x && this.y == otherCell.y);     }         @Override     public int hashCode() {         // random hash code method designed to be usually unique         return this.x + this.y * 256;     }   }   private void generateMaze() {       generateMaze(0, 0);   }   private void generateMaze(int x, int y) {       generateMaze(getCell(x, y)); // generate from Cell   }   private void generateMaze(Cell startAt) {       if (startAt == null) return;       startAt.open = false; // indicate cell closed for generation       ArrayList<Cell> cells = new ArrayList<>();       cells.add(startAt);       while (!cells.isEmpty()) {           Cell cell;                   if (random.nextInt(10)==0)               cell = cells.remove(random.nextInt(cells.size()));           else cell = cells.remove(cells.size() - 1);                     ArrayList<Cell> neighbors = new ArrayList<>();                     Cell[] potentialNeighbors = new Cell[]{               getCell(cell.x + 1, cell.y),               getCell(cell.x, cell.y + 1),               getCell(cell.x - 1, cell.y),               getCell(cell.x, cell.y - 1)           };           for (Cell other : potentialNeighbors) {                             if (other==null || other.wall || !other.open) continue;               neighbors.add(other);           }           if (neighbors.isEmpty()) continue;                     Cell selected = neighbors.get(random.nextInt(neighbors.size()));                     selected.open = false; // indicate cell closed for generation           cell.addNeighbor(selected);           cells.add(cell);           cells.add(selected);       }   }     public Cell getCell(int x, int y) {       try {           return cells[x][y];       } catch (ArrayIndexOutOfBoundsException e) {           return null;       }   }   public void solve() {             this.solve(0, 0, dimensionX - 1, dimensionY -1);   }     public void solve(int startX, int startY, int endX, int endY) {             for (Cell[] cellrow : this.cells) {           for (Cell cell : cellrow) {               cell.parent = null;               cell.visited = false;               cell.inPath = false;               cell.travelled = 0;               cell.projectedDist = -1;           }       }             ArrayList<Cell> openCells = new ArrayList<>();           Cell endCell = getCell(endX, endY);       if (endCell == null) return; // quit if end out of bounds       {           Cell start = getCell(startX, startY);           if (start == null) return; // quit if start out of bounds           start.projectedDist = getProjectedDistance(start, 0, endCell);           start.visited = true;           openCells.add(start);       }       boolean solving = true;       while (solving) {           if (openCells.isEmpty()) return; // quit, no path           Collections.sort(openCells, new Comparator<Cell>(){               @Override               public int compare(Cell cell1, Cell cell2) {                   double diff = cell1.projectedDist - cell2.projectedDist;                   if (diff > 0) return 1;                   else if (diff < 0) return -1;                   else return 0;               }           }); Cell current = openCells.remove(0); if (current == endCell) break; for (Cell neighbor : current.neighbors) { double projDist = getProjectedDistance(neighbor, current.travelled + 1, endCell); if (!neighbor.visited || projDist < neighbor.projectedDist) { neighbor.parent = current; neighbor.visited = true; neighbor.projectedDist = projDist; neighbor.travelled = current.travelled + 1; if (!openCells.contains(neighbor)) openCells.add(neighbor); } } } Cell backtracking = endCell; backtracking.inPath = true; while (backtracking.parent != null) { backtracking = backtracking.parent; backtracking.inPath = true; } } public double getProjectedDistance(Cell current, double travelled, Cell end) { return travelled + Math.abs(current.x - end.x) +  Math.abs(current.y - current.x); } public void updateGrid() { char backChar = ' ', wallChar = 'X', cellChar = ' ', pathChar = '*'; for (int x = 0; x < gridDimensionX; x ++) { for (int y = 0; y < gridDimensionY; y ++) { grid[x][y] = backChar; } } for (int x = 0; x < gridDimensionX; x ++) { for (int y = 0; y < gridDimensionY; y ++) { if (x % 4 == 0 || y % 2 == 0) grid[x][y] = wallChar; } } for (int x = 0; x < dimensionX; x++) { for (int y = 0; y < dimensionY; y++) { Cell current = getCell(x, y); int gridX = x * 4 + 2, gridY = y * 2 + 1; if (current.inPath) { grid[gridX][gridY] = pathChar; if (current.isCellBelowNeighbor()) if (getCell(x, y + 1).inPath) { grid[gridX][gridY + 1] = pathChar; grid[gridX + 1][gridY + 1] = backChar; grid[gridX - 1][gridY + 1] = backChar; } else { grid[gridX][gridY + 1] = cellChar; grid[gridX + 1][gridY + 1] = backChar; grid[gridX - 1][gridY + 1] = backChar; } if (current.isCellRightNeighbor()) if (getCell(x + 1, y).inPath) { grid[gridX + 2][gridY] = pathChar; grid[gridX + 1][gridY] = pathChar; grid[gridX + 3][gridY] = pathChar; } else { grid[gridX + 2][gridY] = cellChar; grid[gridX + 1][gridY] = cellChar; grid[gridX + 3][gridY] = cellChar; } } else { grid[gridX][gridY] = cellChar; if (current.isCellBelowNeighbor()) { grid[gridX][gridY + 1] = cellChar; grid[gridX + 1][gridY + 1] = backChar; grid[gridX - 1][gridY + 1] = backChar; } if (current.isCellRightNeighbor()) { grid[gridX + 2][gridY] = cellChar; grid[gridX + 1][gridY] = cellChar; grid[gridX + 3][gridY] = cellChar; } } } } } public void draw() { System.out.print(this); } @Override public String toString() { updateGrid(); String output = ""; for (int y = 0; y < gridDimensionY; y++) { for (int x = 0; x < gridDimensionX; x++) { output += grid[x][y]; } output += "\n"; } return output; } public static void main(String[] args) { MyMaze maze = new MyMaze(20); maze.solve(); maze.draw();   }} 
0 0
Add a comment Improve this question Transcribed image text
Answer #1

The code has been refactored in accordance with Java's coding conventions to a proper format. Hope it helps!

Code :

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Random;

public class MyMaze {

private int dimensionX, dimensionY; // dimension of maze

private int gridDimensionX, gridDimensionY; // dimension of output grid

private char[][] grid; // output grid

private Cell[][] cells; // 2d array of Cells

private Random random = new Random(); // The random object

public MyMaze(int aDimension) {

this(aDimension, aDimension);

}

public MyMaze(int xDimension, int yDimension) {

dimensionX = 21;

dimensionY = 70;

gridDimensionX = 21 * 4 + 1;

gridDimensionY = 70 * 2 + 1;

grid = new char[gridDimensionX][gridDimensionY];

init();

generateMaze();

}

private void init() {

cells = new Cell[dimensionX][dimensionY];

for (int x = 0; x < dimensionX; x++) {

for (int y = 0; y < dimensionY; y++) {

cells[x][y] = new Cell(x, y, false); // create cell (see Cell constructor)

}

}

}

private class Cell {

int x, y; // coordinates ArrayList<Cell>

neighbors=new ArrayList<>();

boolean visited = false;

Cell parent = null;

boolean inPath = false;

double travelled;

double projectedDist;

boolean wall = true;

boolean open = true;

Cell(int x, int y) {

this(x, y, true);

}

Cell(int x, int y, boolean isWall) {

this.x = x;

this.y = y;

this.wall = isWall;

}

void addNeighbor(Cell other) {

if (!this.neighbors.contains(other)) {

this.neighbors.add(other);

}

if (!other.neighbors.contains(this)) {

other.neighbors.add(this);

}

}

boolean isCellBelowNeighbor() {

return this.neighbors.contains(new Cell(this.x, this.y + 1));

}

boolean isCellRightNeighbor() {

return this.neighbors.contains(new Cell(this.x + 1, this.y));

}

@Override

public String toString() {

return String.format("Cell(%s, %s)", x, y);

}

@Override

public boolean equals(Object other) {

if (!(other instanceof Cell))

return false;

Cell otherCell = (Cell) other;

return (this.x == otherCell.x && this.y == otherCell.y);

}

@Override

public int hashCode() {

// random hash code method designed to be usually unique

return this.x + this.y * 256;

}

}

private void generateMaze() {

generateMaze(0, 0);

}

private void generateMaze(int x, int y) {

generateMaze(getCell(x, y)); // generate from Cell

}

private void generateMaze(Cell startAt) {

if (startAt == null)

return;

startAt.open = false; // indicate cell closed for generation

ArrayList<Cell> cells = new ArrayList<>();

cells.add(startAt);

while (!cells.isEmpty()) {

Cell cell;

if (random.nextInt(10) == 0)

cell = cells.remove(random.nextInt(cells.size()));

else

cell = cells.remove(cells.size() - 1);

ArrayList<Cell> neighbors = new ArrayList<>();

Cell[] potentialNeighbors = new Cell[] { getCell(cell.x + 1, cell.y), getCell(cell.x, cell.y + 1),

getCell(cell.x - 1, cell.y), getCell(cell.x, cell.y - 1)

};

for (Cell other : potentialNeighbors) {

if (other == null || other.wall || !other.open)

continue;

neighbors.add(other);

}

if (neighbors.isEmpty())

continue;

Cell selected = neighbors.get(random.nextInt(neighbors.size()));

selected.open = false; // indicate cell closed for generation

cell.addNeighbor(selected);

cells.add(cell);

cells.add(selected);

}

}

public Cell getCell(int x, int y) {

try {

return cells[x][y];

} catch (ArrayIndexOutOfBoundsException e) {

return null;

}

}

public void solve() {

this.solve(0, 0, dimensionX - 1, dimensionY - 1);

}

public void solve(int startX, int startY, int endX, int endY) {

for (Cell[] cellrow : this.cells) {

for (Cell cell : cellrow) {

cell.parent = null;

cell.visited = false;

cell.inPath = false;

cell.travelled = 0;

cell.projectedDist = -1;

}

}

ArrayList<Cell> openCells = new ArrayList<>();

Cell endCell = getCell(endX, endY);

if (endCell == null)

return; // quit if end out of bounds

{

Cell start = getCell(startX, startY);

if (start == null)

return; // quit if start out of bounds

start.projectedDist = getProjectedDistance(start, 0, endCell);

start.visited = true;

openCells.add(start);

}

boolean solving = true;

while (solving) {

if (openCells.isEmpty())

return; // quit, no path

Collections.sort(openCells, new Comparator<Cell>() {

@Override

public int compare(Cell cell1, Cell cell2) {

double diff = cell1.projectedDist - cell2.projectedDist;

if (diff > 0)

return 1;

else if (diff < 0)

return -1;

else

return 0;

}

});

Cell current = openCells.remove(0);

if (current == endCell)

break;

for (Cell neighbor : current.neighbors) {

double projDist = getProjectedDistance(neighbor, current.travelled + 1, endCell);

if (!neighbor.visited || projDist < neighbor.projectedDist) {

neighbor.parent = current;

neighbor.visited = true;

neighbor.projectedDist = projDist;

neighbor.travelled = current.travelled + 1;

if (!openCells.contains(neighbor))

openCells.add(neighbor);

}

}

}

Cell backtracking = endCell;

backtracking.inPath = true;

while (backtracking.parent != null) {

backtracking = backtracking.parent;

backtracking.inPath = true;

}

}

public double getProjectedDistance(Cell current, double travelled, Cell end) {

return travelled + Math.abs(current.x - end.x) + Math.abs(current.y - current.x);

}

public void updateGrid() {

char backChar = ' ', wallChar = 'X', cellChar = ' ', pathChar = '*';

for (int x = 0; x < gridDimensionX; x++) {

for (int y = 0; y < gridDimensionY; y++) {

grid[x][y] = backChar;

}

}

for (int x = 0; x < gridDimensionX; x++) {

for (int y = 0; y < gridDimensionY; y++) {

if (x % 4 == 0 || y % 2 == 0)

grid[x][y] = wallChar;

}

}

for (int x = 0; x < dimensionX; x++) {

for (int y = 0; y < dimensionY; y++) {

Cell current = getCell(x, y);

int gridX = x * 4 + 2, gridY = y * 2 + 1;

if (current.inPath) {

grid[gridX][gridY] = pathChar;

if (current.isCellBelowNeighbor())

if (getCell(x, y + 1).inPath) {

grid[gridX][gridY + 1] = pathChar;

grid[gridX + 1][gridY + 1] = backChar;

grid[gridX - 1][gridY + 1] = backChar;

} else {

grid[gridX][gridY + 1] = cellChar;

grid[gridX + 1][gridY + 1] = backChar;

grid[gridX - 1][gridY + 1] = backChar;

}

if (current.isCellRightNeighbor())

if (getCell(x + 1, y).inPath) {

grid[gridX + 2][gridY] = pathChar;

grid[gridX + 1][gridY] = pathChar;

grid[gridX + 3][gridY] = pathChar;

} else {

grid[gridX + 2][gridY] = cellChar;

grid[gridX + 1][gridY] = cellChar;

grid[gridX + 3][gridY] = cellChar;

}

} else {

grid[gridX][gridY] = cellChar;

if (current.isCellBelowNeighbor()) {

grid[gridX][gridY + 1] = cellChar;

grid[gridX + 1][gridY + 1] = backChar;

grid[gridX - 1][gridY + 1] = backChar;

}

if (current.isCellRightNeighbor()) {

grid[gridX + 2][gridY] = cellChar;

grid[gridX + 1][gridY] = cellChar;

grid[gridX + 3][gridY] = cellChar;

}

}

}

}

}

public void draw() {

System.out.print(this);

}

@Override

public String toString() {

updateGrid();

String output = "";

for (int y = 0; y < gridDimensionY; y++) {

for (int x = 0; x < gridDimensionX; x++) {

output += grid[x][y];

}

output += "\n";

}

return output;

}

public static void main(String[] args) {

MyMaze maze = new MyMaze(20);

maze.solve();

maze.draw();

}

}

Add a comment
Know the answer?
Add Answer to:
Please make this code workable and straight. this code does produce a proper output but just...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show...

    In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show when my acceptbutton1 is pressed. One message is if the mouse HAS been dragged. One is if the mouse HAS NOT been dragged. /// I tried to make the Points class or the Mouse Dragged function return a boolean of true, so that I could construct an IF/THEN statement for the showDialog messages, but my boolean value was never accepted by ButtonHandler. *************************ButtonHandler class************************************...

  • Please help to make the program working. Can not compile. import java.io.*; import java .util.*; public...

    Please help to make the program working. Can not compile. import java.io.*; import java .util.*; public class Puzzlee {                 static int NN = 9; // Grid Size // sample input static int myGrid[][] = {                                                                                                                                                                                                                                                                                {0,0,0,1,0,5,0,6,8},                                                                                                                 {0,0,0,0,0,0,7,0,1},                                                                                                                 {9,0,1,0,0,0,0,3,0},                                                                                                                 {0,0,7,0,2,6,0,0,0},                                                                                                                 {5,0,0,0,0,0,0,0,3},                                                                                                                 {0,0,0,8,7,0,4,0,0},                                                                                                                 {0,3,0,0,0,0,8,0,5},                                                                                                                 {1,0,5,0,0,0,0,0,0},                                                                                                                 {7,9,0,4,0,1,0,0,0}                                                                                                 };    static class myCell {                 int myRow, myColumn;                 public myCell(int myRow, int myColumn)                 {                                 super();                                ...

  • PLEASE HELP! The assignment details are in the *noted part of the code. I REALLY need...

    PLEASE HELP! The assignment details are in the *noted part of the code. I REALLY need help. import java.util.LinkedList; public class TwoDTree { private TwoDTreeNode root; private int size; public TwoDTree() {    clear(); } /** * Returns true if a point is already in the tree. * Returns false otherwise. * * The traversal remains the same. Start at the root, if the tree * is not empty, and compare the x-coordinates of the point passed * in and...

  • Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections;...

    Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections; class Grid { private boolean bombGrid[][]; private int countGrid[][]; private int numRows; private int numColumns; private int numBombs; public Grid() { this(10, 10, 25); }    public Grid(int rows, int columns) { this(rows, columns, 25); }    public Grid(int rows, int columns, int numBombs) { this.numRows = rows; this.numColumns = columns; this.numBombs = numBombs; createBombGrid(); createCountGrid(); }    public int getNumRows() { return numRows;...

  • Please help with the codes for the implementation of java.util.List, specifically for the 3 below overridden...

    Please help with the codes for the implementation of java.util.List, specifically for the 3 below overridden methods @Override        public int lastIndexOf(Object arg0) { required code }        @Override        public ListIterator<R> listIterator() { required code }        @Override        public ListIterator<R> listIterator(int arg0) { required code } PLEASE NOTE: Below are some of other overridden methods that are already implemented, they are meant to be examples of what the answers to the above questions for the 3 methods should...

  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • PLEASE HURRY Software Testing Don't make any changes to the provided code. Please write a test...

    PLEASE HURRY Software Testing Don't make any changes to the provided code. Please write a test case for the below prompt using the provided java programs Use the setString() function in MyCustomStringInterface to set the value to “Peter Piper picked a peck of pickled peppers.”. Then test to see if reverseNCharacters() function returns the reversed string when the characters are reversed in groups of 4 and padding is disabled (in this case, “etePiP r repkcipa decep fo kcip delkpep srep.”)....

  • output What is the output of the following: class Access public int x; private int y...

    output What is the output of the following: class Access public int x; private int y public void cal(int x, int y) { this.x = x + 1; this.y = y; } public void print() { System.out.print(""+y); } } class AccessSpecifier { public static void main(String args[]) { Access obj = new Access(); obj.cal(2, 3); System.out.print(obj.x); obj.print(); } } 33 Compilation error 23 None of the available choices Runtime error

  • Practically dying here with this, need help ASAP, just need to do hide(), hideBoth(), and matchFound(),...

    Practically dying here with this, need help ASAP, just need to do hide(), hideBoth(), and matchFound(), then implement them, so far in my version i tentatively made them, but I don't know ho to implement them so i posted the original code before i made my version of the three methods listed above. Need help fast, this is ridiculous. Implement just one requirement at a time. For example, try implementing the case where after the user clicks 2 squares, both...

  • Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a...

    Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import    java.time.temporal.ChronoUnit; public class LibraryCard {    private String id;    private String cardholderName;   ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT