SlideShare a Scribd company logo
1 of 9
Download to read offline
Write a program that randomly generates a maze in java
Solution
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
// initialize with x and y the same
public MyMaze(int aDimension) {
// Initialize
this(aDimension, aDimension);
}
// constructor
public MyMaze(int xDimension, int yDimension) {
dimensionX = xDimension;
dimensionY = yDimension;
gridDimensionX = xDimension * 4 + 1;
gridDimensionY = yDimension * 2 + 1;
grid = new char[gridDimensionX][gridDimensionY];
init();
generateMaze();
}
private void init() {
// create cells
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)
}
}
}
// inner class to represent a cell
private class Cell {
int x, y; // coordinates
// cells this cell is connected to
ArrayList neighbors = new ArrayList<>();
// solver: if already used
boolean visited = false;
// solver: the Cell before this one in the path
Cell parent = null;
// solver: if used in last attempt to solve path
boolean inPath = false;
// solver: distance travelled this far
double travelled;
// solver: projected distance to end
double projectedDist;
// impassable cell
boolean wall = true;
// if true, has yet to be used in generation
boolean open = true;
// construct Cell at x, y
Cell(int x, int y) {
this(x, y, true);
}
// construct Cell at x, y and with whether it isWall
Cell(int x, int y, boolean isWall) {
this.x = x;
this.y = y;
this.wall = isWall;
}
// add a neighbor to this cell, and this cell as a neighbor to the other
void addNeighbor(Cell other) {
if (!this.neighbors.contains(other)) { // avoid duplicates
this.neighbors.add(other);
}
if (!other.neighbors.contains(this)) { // avoid duplicates
other.neighbors.add(this);
}
}
// used in updateGrid()
boolean isCellBelowNeighbor() {
return this.neighbors.contains(new Cell(this.x, this.y + 1));
}
// used in updateGrid()
boolean isCellRightNeighbor() {
return this.neighbors.contains(new Cell(this.x + 1, this.y));
}
// useful Cell representation
@Override
public String toString() {
return String.format("Cell(%s, %s)", x, y);
}
// useful Cell equivalence
@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);
}
// should be overridden with equals
@Override
public int hashCode() {
// random hash code method designed to be usually unique
return this.x + this.y * 256;
}
}
// generate from upper left (In computing the y increases down often)
private void generateMaze() {
generateMaze(0, 0);
}
// generate the maze from coordinates x, y
private void generateMaze(int x, int y) {
generateMaze(getCell(x, y)); // generate from Cell
}
private void generateMaze(Cell startAt) {
// don't generate from cell not there
if (startAt == null) return;
startAt.open = false; // indicate cell closed for generation
ArrayList cells = new ArrayList<>();
cells.add(startAt);
while (!cells.isEmpty()) {
Cell cell;
// this is to reduce but not completely eliminate the number
// of long twisting halls with short easy to detect branches
// which results in easy mazes
if (random.nextInt(10)==0)
cell = cells.remove(random.nextInt(cells.size()));
else cell = cells.remove(cells.size() - 1);
// for collection
ArrayList neighbors = new ArrayList<>();
// cells that could potentially be neighbors
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) {
// skip if outside, is a wall or is not opened
if (other==null || other.wall || !other.open) continue;
neighbors.add(other);
}
if (neighbors.isEmpty()) continue;
// get random cell
Cell selected = neighbors.get(random.nextInt(neighbors.size()));
// add as neighbor
selected.open = false; // indicate cell closed for generation
cell.addNeighbor(selected);
cells.add(cell);
cells.add(selected);
}
}
// used to get a Cell at x, y; returns null out of bounds
public Cell getCell(int x, int y) {
try {
return cells[x][y];
} catch (ArrayIndexOutOfBoundsException e) { // catch out of bounds
return null;
}
}
public void solve() {
// default solve top left to bottom right
this.solve(0, 0, dimensionX - 1, dimensionY -1);
}
// solve the maze starting from the start state (A-star algorithm)
public void solve(int startX, int startY, int endX, int endY) {
// re initialize cells for path finding
for (Cell[] cellrow : this.cells) {
for (Cell cell : cellrow) {
cell.parent = null;
cell.visited = false;
cell.inPath = false;
cell.travelled = 0;
cell.projectedDist = -1;
}
}
// cells still being considered
ArrayList openCells = new ArrayList<>();
// cell being considered
Cell endCell = getCell(endX, endY);
if (endCell == null) return; // quit if end out of bounds
{ // anonymous block to delete start, because not used later
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
// sort openCells according to least projected distance
Collections.sort(openCells, new Comparator(){
@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); // pop cell least projectedDist
if (current == endCell) break; // at end
for (Cell neighbor : current.neighbors) {
double projDist = getProjectedDistance(neighbor,
current.travelled + 1, endCell);
if (!neighbor.visited || // not visited yet
projDist < neighbor.projectedDist) { // better path
neighbor.parent = current;
neighbor.visited = true;
neighbor.projectedDist = projDist;
neighbor.travelled = current.travelled + 1;
if (!openCells.contains(neighbor))
openCells.add(neighbor);
}
}
}
// create path from end to beginning
Cell backtracking = endCell;
backtracking.inPath = true;
while (backtracking.parent != null) {
backtracking = backtracking.parent;
backtracking.inPath = true;
}
}
// get the projected distance
// (A star algorithm consistent)
public double getProjectedDistance(Cell current, double travelled, Cell end) {
return travelled + Math.abs(current.x - end.x) +
Math.abs(current.y - current.x);
}
// draw the maze
public void updateGrid() {
char backChar = ' ', wallChar = 'X', cellChar = ' ', pathChar = '*';
// fill background
for (int x = 0; x < gridDimensionX; x ++) {
for (int y = 0; y < gridDimensionY; y ++) {
grid[x][y] = backChar;
}
}
// build walls
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;
}
}
// make meaningful representation
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;
}
}
}
}
}
// simply prints the map
public void draw() {
System.out.print(this);
}
// forms a meaningful representation
@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 += " ";
}
return output;
}
// run it
public static void main(String[] args) {
MyMaze maze = new MyMaze(20);
maze.solve();
System.out.print(maze);
}
}

More Related Content

Similar to Write a program that randomly generates a maze in javaSolution.pdf

java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
 
need help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfneed help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfarcotstarsports
 
Create a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdfCreate a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdfarihantsherwani
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
Bài tập và bài tập nâng cao của cây AVL.docx
Bài tập và bài tập nâng cao của cây  AVL.docxBài tập và bài tập nâng cao của cây  AVL.docx
Bài tập và bài tập nâng cao của cây AVL.docxLNhi89
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfjyothimuppasani1
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdfinfo750646
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Find the shortest route through a maze using linking and linked list.pdf
Find the shortest route through a maze using linking and linked list.pdfFind the shortest route through a maze using linking and linked list.pdf
Find the shortest route through a maze using linking and linked list.pdfsanuoptical
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyondFrancis Johny
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
I am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdfI am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdffortmdu
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdfasarudheen07
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdffootstatus
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdffms12345
 

Similar to Write a program that randomly generates a maze in javaSolution.pdf (20)

java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
 
need help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfneed help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdf
 
Create a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdfCreate a C program that implements The Game of Life cellular auto.pdf
Create a C program that implements The Game of Life cellular auto.pdf
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Bài tập và bài tập nâng cao của cây AVL.docx
Bài tập và bài tập nâng cao của cây  AVL.docxBài tập và bài tập nâng cao của cây  AVL.docx
Bài tập và bài tập nâng cao của cây AVL.docx
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Find the shortest route through a maze using linking and linked list.pdf
Find the shortest route through a maze using linking and linked list.pdfFind the shortest route through a maze using linking and linked list.pdf
Find the shortest route through a maze using linking and linked list.pdf
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Js objects
Js objectsJs objects
Js objects
 
I am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdfI am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdf
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdf
 

More from bermanbeancolungak45

why is the idea of a standard network protocol such as the OSI refer.pdf
why is the idea of a standard network protocol such as the OSI refer.pdfwhy is the idea of a standard network protocol such as the OSI refer.pdf
why is the idea of a standard network protocol such as the OSI refer.pdfbermanbeancolungak45
 
Which of the following potential problems need not be considered whe.pdf
Which of the following potential problems need not be considered whe.pdfWhich of the following potential problems need not be considered whe.pdf
Which of the following potential problems need not be considered whe.pdfbermanbeancolungak45
 
Which of the following is true of mutations They are very common T.pdf
Which of the following is true of mutations  They are very common  T.pdfWhich of the following is true of mutations  They are very common  T.pdf
Which of the following is true of mutations They are very common T.pdfbermanbeancolungak45
 
What type of security vulnerability are developers most likely to in.pdf
What type of security vulnerability are developers most likely to in.pdfWhat type of security vulnerability are developers most likely to in.pdf
What type of security vulnerability are developers most likely to in.pdfbermanbeancolungak45
 
What is the purpose of database administration2. What is the purp.pdf
What is the purpose of database administration2. What is the purp.pdfWhat is the purpose of database administration2. What is the purp.pdf
What is the purpose of database administration2. What is the purp.pdfbermanbeancolungak45
 
what is code to draw sun and earth and the moon in java OpenGLS.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdfwhat is code to draw sun and earth and the moon in java OpenGLS.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdfbermanbeancolungak45
 
What factors do you think make them excellent project reports write.pdf
What factors do you think make them excellent project reports write.pdfWhat factors do you think make them excellent project reports write.pdf
What factors do you think make them excellent project reports write.pdfbermanbeancolungak45
 
What aspects of todays information economy have influenced the imp.pdf
What aspects of todays information economy have influenced the imp.pdfWhat aspects of todays information economy have influenced the imp.pdf
What aspects of todays information economy have influenced the imp.pdfbermanbeancolungak45
 
This week, we are going to work together as a class to assist the Lon.pdf
This week, we are going to work together as a class to assist the Lon.pdfThis week, we are going to work together as a class to assist the Lon.pdf
This week, we are going to work together as a class to assist the Lon.pdfbermanbeancolungak45
 
The phylogenetic species concept looks at environmental adaptations a.pdf
The phylogenetic species concept looks at environmental adaptations a.pdfThe phylogenetic species concept looks at environmental adaptations a.pdf
The phylogenetic species concept looks at environmental adaptations a.pdfbermanbeancolungak45
 
The percentage of high school students who drink and drive was 17.5.pdf
The percentage of high school students who drink and drive was 17.5.pdfThe percentage of high school students who drink and drive was 17.5.pdf
The percentage of high school students who drink and drive was 17.5.pdfbermanbeancolungak45
 
Take a position on this statement The media represent realistic ima.pdf
Take a position on this statement The media represent realistic ima.pdfTake a position on this statement The media represent realistic ima.pdf
Take a position on this statement The media represent realistic ima.pdfbermanbeancolungak45
 
Suppose 60 different survey organizations visit eastern Tennessee to.pdf
Suppose 60 different survey organizations visit eastern Tennessee to.pdfSuppose 60 different survey organizations visit eastern Tennessee to.pdf
Suppose 60 different survey organizations visit eastern Tennessee to.pdfbermanbeancolungak45
 
Relate selected early morphological developments in the ancestors of.pdf
Relate selected early morphological developments in the ancestors of.pdfRelate selected early morphological developments in the ancestors of.pdf
Relate selected early morphological developments in the ancestors of.pdfbermanbeancolungak45
 
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdfQuestion VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdfbermanbeancolungak45
 
question - Jurassic Park (book and movie) proposed the concept of.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdfquestion - Jurassic Park (book and movie) proposed the concept of.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdfbermanbeancolungak45
 
Python programming question Assume that a file containing a serie.pdf
Python programming question Assume that a file containing a serie.pdfPython programming question Assume that a file containing a serie.pdf
Python programming question Assume that a file containing a serie.pdfbermanbeancolungak45
 
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdfPrior to the development of anti-retroviral drugs, HIV infected pati.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdfbermanbeancolungak45
 
Please this is my second time posting. I really need the right answe.pdf
Please this is my second time posting. I really need the right answe.pdfPlease this is my second time posting. I really need the right answe.pdf
Please this is my second time posting. I really need the right answe.pdfbermanbeancolungak45
 
Please by using Computer!Each of you were assigned a count.pdf
Please by using Computer!Each of you were assigned a count.pdfPlease by using Computer!Each of you were assigned a count.pdf
Please by using Computer!Each of you were assigned a count.pdfbermanbeancolungak45
 

More from bermanbeancolungak45 (20)

why is the idea of a standard network protocol such as the OSI refer.pdf
why is the idea of a standard network protocol such as the OSI refer.pdfwhy is the idea of a standard network protocol such as the OSI refer.pdf
why is the idea of a standard network protocol such as the OSI refer.pdf
 
Which of the following potential problems need not be considered whe.pdf
Which of the following potential problems need not be considered whe.pdfWhich of the following potential problems need not be considered whe.pdf
Which of the following potential problems need not be considered whe.pdf
 
Which of the following is true of mutations They are very common T.pdf
Which of the following is true of mutations  They are very common  T.pdfWhich of the following is true of mutations  They are very common  T.pdf
Which of the following is true of mutations They are very common T.pdf
 
What type of security vulnerability are developers most likely to in.pdf
What type of security vulnerability are developers most likely to in.pdfWhat type of security vulnerability are developers most likely to in.pdf
What type of security vulnerability are developers most likely to in.pdf
 
What is the purpose of database administration2. What is the purp.pdf
What is the purpose of database administration2. What is the purp.pdfWhat is the purpose of database administration2. What is the purp.pdf
What is the purpose of database administration2. What is the purp.pdf
 
what is code to draw sun and earth and the moon in java OpenGLS.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdfwhat is code to draw sun and earth and the moon in java OpenGLS.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdf
 
What factors do you think make them excellent project reports write.pdf
What factors do you think make them excellent project reports write.pdfWhat factors do you think make them excellent project reports write.pdf
What factors do you think make them excellent project reports write.pdf
 
What aspects of todays information economy have influenced the imp.pdf
What aspects of todays information economy have influenced the imp.pdfWhat aspects of todays information economy have influenced the imp.pdf
What aspects of todays information economy have influenced the imp.pdf
 
This week, we are going to work together as a class to assist the Lon.pdf
This week, we are going to work together as a class to assist the Lon.pdfThis week, we are going to work together as a class to assist the Lon.pdf
This week, we are going to work together as a class to assist the Lon.pdf
 
The phylogenetic species concept looks at environmental adaptations a.pdf
The phylogenetic species concept looks at environmental adaptations a.pdfThe phylogenetic species concept looks at environmental adaptations a.pdf
The phylogenetic species concept looks at environmental adaptations a.pdf
 
The percentage of high school students who drink and drive was 17.5.pdf
The percentage of high school students who drink and drive was 17.5.pdfThe percentage of high school students who drink and drive was 17.5.pdf
The percentage of high school students who drink and drive was 17.5.pdf
 
Take a position on this statement The media represent realistic ima.pdf
Take a position on this statement The media represent realistic ima.pdfTake a position on this statement The media represent realistic ima.pdf
Take a position on this statement The media represent realistic ima.pdf
 
Suppose 60 different survey organizations visit eastern Tennessee to.pdf
Suppose 60 different survey organizations visit eastern Tennessee to.pdfSuppose 60 different survey organizations visit eastern Tennessee to.pdf
Suppose 60 different survey organizations visit eastern Tennessee to.pdf
 
Relate selected early morphological developments in the ancestors of.pdf
Relate selected early morphological developments in the ancestors of.pdfRelate selected early morphological developments in the ancestors of.pdf
Relate selected early morphological developments in the ancestors of.pdf
 
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdfQuestion VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
 
question - Jurassic Park (book and movie) proposed the concept of.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdfquestion - Jurassic Park (book and movie) proposed the concept of.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdf
 
Python programming question Assume that a file containing a serie.pdf
Python programming question Assume that a file containing a serie.pdfPython programming question Assume that a file containing a serie.pdf
Python programming question Assume that a file containing a serie.pdf
 
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdfPrior to the development of anti-retroviral drugs, HIV infected pati.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
 
Please this is my second time posting. I really need the right answe.pdf
Please this is my second time posting. I really need the right answe.pdfPlease this is my second time posting. I really need the right answe.pdf
Please this is my second time posting. I really need the right answe.pdf
 
Please by using Computer!Each of you were assigned a count.pdf
Please by using Computer!Each of you were assigned a count.pdfPlease by using Computer!Each of you were assigned a count.pdf
Please by using Computer!Each of you were assigned a count.pdf
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

Write a program that randomly generates a maze in javaSolution.pdf

  • 1. Write a program that randomly generates a maze in java Solution 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 // initialize with x and y the same public MyMaze(int aDimension) { // Initialize this(aDimension, aDimension); } // constructor public MyMaze(int xDimension, int yDimension) { dimensionX = xDimension; dimensionY = yDimension; gridDimensionX = xDimension * 4 + 1; gridDimensionY = yDimension * 2 + 1; grid = new char[gridDimensionX][gridDimensionY]; init(); generateMaze(); } private void init() { // create cells 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)
  • 2. } } } // inner class to represent a cell private class Cell { int x, y; // coordinates // cells this cell is connected to ArrayList neighbors = new ArrayList<>(); // solver: if already used boolean visited = false; // solver: the Cell before this one in the path Cell parent = null; // solver: if used in last attempt to solve path boolean inPath = false; // solver: distance travelled this far double travelled; // solver: projected distance to end double projectedDist; // impassable cell boolean wall = true; // if true, has yet to be used in generation boolean open = true; // construct Cell at x, y Cell(int x, int y) { this(x, y, true); } // construct Cell at x, y and with whether it isWall Cell(int x, int y, boolean isWall) { this.x = x; this.y = y; this.wall = isWall; } // add a neighbor to this cell, and this cell as a neighbor to the other void addNeighbor(Cell other) { if (!this.neighbors.contains(other)) { // avoid duplicates this.neighbors.add(other);
  • 3. } if (!other.neighbors.contains(this)) { // avoid duplicates other.neighbors.add(this); } } // used in updateGrid() boolean isCellBelowNeighbor() { return this.neighbors.contains(new Cell(this.x, this.y + 1)); } // used in updateGrid() boolean isCellRightNeighbor() { return this.neighbors.contains(new Cell(this.x + 1, this.y)); } // useful Cell representation @Override public String toString() { return String.format("Cell(%s, %s)", x, y); } // useful Cell equivalence @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); } // should be overridden with equals @Override public int hashCode() { // random hash code method designed to be usually unique return this.x + this.y * 256; } } // generate from upper left (In computing the y increases down often) private void generateMaze() { generateMaze(0, 0); }
  • 4. // generate the maze from coordinates x, y private void generateMaze(int x, int y) { generateMaze(getCell(x, y)); // generate from Cell } private void generateMaze(Cell startAt) { // don't generate from cell not there if (startAt == null) return; startAt.open = false; // indicate cell closed for generation ArrayList cells = new ArrayList<>(); cells.add(startAt); while (!cells.isEmpty()) { Cell cell; // this is to reduce but not completely eliminate the number // of long twisting halls with short easy to detect branches // which results in easy mazes if (random.nextInt(10)==0) cell = cells.remove(random.nextInt(cells.size())); else cell = cells.remove(cells.size() - 1); // for collection ArrayList neighbors = new ArrayList<>(); // cells that could potentially be neighbors 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) { // skip if outside, is a wall or is not opened if (other==null || other.wall || !other.open) continue; neighbors.add(other); } if (neighbors.isEmpty()) continue; // get random cell Cell selected = neighbors.get(random.nextInt(neighbors.size())); // add as neighbor
  • 5. selected.open = false; // indicate cell closed for generation cell.addNeighbor(selected); cells.add(cell); cells.add(selected); } } // used to get a Cell at x, y; returns null out of bounds public Cell getCell(int x, int y) { try { return cells[x][y]; } catch (ArrayIndexOutOfBoundsException e) { // catch out of bounds return null; } } public void solve() { // default solve top left to bottom right this.solve(0, 0, dimensionX - 1, dimensionY -1); } // solve the maze starting from the start state (A-star algorithm) public void solve(int startX, int startY, int endX, int endY) { // re initialize cells for path finding for (Cell[] cellrow : this.cells) { for (Cell cell : cellrow) { cell.parent = null; cell.visited = false; cell.inPath = false; cell.travelled = 0; cell.projectedDist = -1; } } // cells still being considered ArrayList openCells = new ArrayList<>(); // cell being considered Cell endCell = getCell(endX, endY); if (endCell == null) return; // quit if end out of bounds { // anonymous block to delete start, because not used later
  • 6. 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 // sort openCells according to least projected distance Collections.sort(openCells, new Comparator(){ @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); // pop cell least projectedDist if (current == endCell) break; // at end for (Cell neighbor : current.neighbors) { double projDist = getProjectedDistance(neighbor, current.travelled + 1, endCell); if (!neighbor.visited || // not visited yet projDist < neighbor.projectedDist) { // better path neighbor.parent = current; neighbor.visited = true; neighbor.projectedDist = projDist; neighbor.travelled = current.travelled + 1; if (!openCells.contains(neighbor)) openCells.add(neighbor); } } } // create path from end to beginning
  • 7. Cell backtracking = endCell; backtracking.inPath = true; while (backtracking.parent != null) { backtracking = backtracking.parent; backtracking.inPath = true; } } // get the projected distance // (A star algorithm consistent) public double getProjectedDistance(Cell current, double travelled, Cell end) { return travelled + Math.abs(current.x - end.x) + Math.abs(current.y - current.x); } // draw the maze public void updateGrid() { char backChar = ' ', wallChar = 'X', cellChar = ' ', pathChar = '*'; // fill background for (int x = 0; x < gridDimensionX; x ++) { for (int y = 0; y < gridDimensionY; y ++) { grid[x][y] = backChar; } } // build walls 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; } } // make meaningful representation 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;
  • 8. 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; } } } } }
  • 9. // simply prints the map public void draw() { System.out.print(this); } // forms a meaningful representation @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 += " "; } return output; } // run it public static void main(String[] args) { MyMaze maze = new MyMaze(20); maze.solve(); System.out.print(maze); } }