# How do I populate a three-dimensional array with randomly placed predefined integers?

Solution for How do I populate a three-dimensional array with randomly placed predefined integers?
is Given Below:

I am new to programming and I have an assignment in Java that asks the user to navigate a 10X10X10 cubic maze, where there must be 500 monsters randomly generated, 499 open cells, and 1 treasure chest. The treasure chest must also be randomly generated, but it cannot occur within the same spot as a monster. The program I have to write asks for user input to check a cell in the array to see if its the treasure chest. If the cell is empty, I have to give a hint as to where the treasure chest is (how many cells away and if you’re in the same row, column, or page). The user gets three tries to find the treasure chest. At the end of the three tries, or if they hit a monster, the user loses and is told in what cell the chest was placed. For the purposes of the assignment, an empty cell = 0, the only cell with the treasure chest = 1, and the monster cell = 2.

I am having trouble populating the cells with only 500 monsters and one chest. My code below populates all the cells with a random amount of 0’s, 1’s and 2’s. I need to limit the 2’s to five-hundred instances, the 1’s to one instance (and check beforehand to make sure a monster isn’t in the cell), and keep the rest 0. I also need to make sure I’m not populating the same cell with more than one monster. This is as far as I’ve got:

``````import java.util.Random;

public class FindTheCheese
{

public static void main(String args[ ])
{

int size = 10;
int[][][] maze = new int[10][10][10];
Random gen = new Random();

for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++) {
for(int k = 0; k <10; k++) {
maze[i][j][k] = gen.nextInt(3);
System.out.print(maze[i][j][k] + ", "); // this won't be part of the final code, just used to check if I'm populating correctly
}
System.out.println();
}
}

}//closing main

}//closing class FindTheCheese
``````

1. Create a one-dimensional array of length 1000 to hold all the values to go into the maze. Set 500 elements to 2 (the monsters), one element to 1 (the treasure chest) and 499 elements to 0 (the free cells).
2. Shuffle the array using `Collections.shuffle(Arrays.asList(yourOneDimArray))`.
3. Now fill the values from the shuffled array into your 3-dimensional matrix in turn. Underway when you encounter the chest, record its coordinates in the maze. You will need this for reporting back to the user.

Happy coding.