I am making a maze game with enumerated types to hold the values of walls, open spaces (etc) and i am not sure why this code does not work, i am trying to create a new board and set everything to open, then go through and randomly set values to the spots in the array.
maze = new Cell[row][col];
for (int r = 0; r < maze.length; r++) {
for (int c = 0; c < maze.length; c++)
maze[r][c].setType(CellType.OPEN);
}
Random randomMaze = new Random();
for (int ran = 0; ran <= numWalls ; ran++){
maze[randomMaze.nextInt(maze.length)][randomMaze.nextInt(maze.length)].setType(CellType.WALL);
}
this will do what you said. not sure you will get the kind of maze you want:
import java.util.Random;
class Maze {
enum CellType {
open,wall;
}
Maze(int n) {
this.n=n;
maze=new CellType[n][n];
init();
}
private void init() {
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
maze[i][j]=CellType.open;
}
void randomize(int walls) {
init();
Random random=new Random();
for(int i=0;i<=walls;i++)
maze[random.nextInt(n)][random.nextInt(n)]=CellType.wall;
}
public String toString() {
StringBuffer sb=new StringBuffer();
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++)
switch(maze[i][j]) {
case open:
sb.append(' ');
break;
case wall:
sb.append('|');
break;
}
sb.append('\n');
}
return sb.toString();
}
final int n;
CellType[][] maze;
}
public class Main {
public static void main(String[] args) {
Maze maze=new Maze(5);
System.out.println(maze);
maze.randomize(4);
System.out.println(maze);
}
}
I think, your inner loop should be something like
for (int c = 0; c < maze[r].length; c++)
... with the [r].
I have not tried it though.
I think that your maze would be a good candidate for a class. Something like this should work:
import java.util.Random;
public class Maze {
private int[][] mMaze;
private int mRows;
private int mCols;
//enums here:
public static int CELL_TYPE_OPEN = 0;
public static int CELL_TYPE_WALL = 1;
public Maze(int rows, int cols){
mRows = rows;
mCols = cols;
mMaze = new int[mRows][mCols];
for (int r = 0; r < mRows; r++) {
for (int c = 0; c < mCols; c++) {
mMaze[r][c] = Maze.CELL_TYPE_OPEN;
}
}
}
public void RandomizeMaze(int numWalls){
Random randomMaze = new Random();
for (int ran = 0; ran <= numWalls ; ran++){
mMaze[randomMaze.nextInt(mRows)][randomMaze.nextInt(mCols)]=(Maze.CELL_TYPE_WALL);
}
}
}
Related
I'm working on a Tower of Hanoi project for school which needs to ask the user how many disks there are and then it needs to create and then solve the tower with a visual included. How I decided to do it is by using 2D arrays and for the most part its working, my only problem is that I don't know how to move the disks while keeping it modular. Here is my code.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of disks");
int num = scan.nextInt();
int temp = num-(num-1);
int measure = num;
//initializing the towers
int[][] towers = new int[num][num];
for(int i = 0 ; i < num; i++)
{
for(int j=0; j <3; j++)
{
}
}
createRings(towers, num, temp);
moveDisk(towers,num);
}
// creating the rings
private static void createRings (int[][]towers, int num, int temp)
{
for(int i = 0; i<num; i++)
{
for(int j=0; j<3;j++)
{
towers[i][0] = temp;
}
temp = temp+1;
}
displayTower(towers, num);
}
// prints the array for display purposes
private static void displayTower (int[][] towers, int num)
{
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(towers[i][j]+"\t");
}
System.out.println();
}
}
//moves the numbers in the array that represents disks
private static void moveDisk(int[][]towers, int num)
{
System.out.println();
displayTower(towers, num);
}
Does anyone have any suggestions on what I could do?
I've changed your code a bit to make it more readable for me.
I changed the towers array. Now each tower is its own array inside the towers array (makes more sense IMHO).
Arrays in Java know their size. So you don't have to pass the length of the array as a parameter to every method.
I added a method getHighestIdx() which returns the index before the first 0 value in the array
I don't know, how the function moveDisk() was intended to work. I changed the declaration so that it makes sense to me. It now moves a disk from tower i to tower j
This should help you to implement the algorithm from the linked question.
Here is the changed code:
public static void main(String[] args) {
int numberOfRings = 6;
int[][] towers = new int[3][numberOfRings];
createRings(towers);
displayTowers(towers);
moveDisk(towers, 0, 2);
displayTowers(towers);
}
private static void createRings(int[][] towers) {
for (int j = 0; j < towers[0].length; j++) {
towers[0][j] = j + 1;
}
}
private static void displayTowers(int[][] towers) {
for (int i = 0; i < towers[0].length; i++) {
for (int j = 0; j < towers.length; j++) {
System.out.print(towers[j][i] + " ");
}
System.out.println("");
}
}
private static void moveDisk(int[][] towers, int fromIdx, int toIdx) {
int valToMove = towers[fromIdx][getHighestIdx(towers[fromIdx])];
towers[fromIdx][getHighestIdx(towers[fromIdx])] = 0;
towers[toIdx][getHighestIdx(towers[toIdx]) + 1] = valToMove;
}
private static int getHighestIdx(int[] tower) {
int i = 0;
while (i < tower.length && tower[i] != 0) {
i++;
}
return i - 1;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Having trouble understanding compile error. Main should be left unchanged. I believe MakeandFillMatix method is the problem and I can't figure it out. I think it's how I created the method.
import java.util.*;
/*
*/
public class TesterProject
{
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);
printMatrix(m);
}
public static int getMatrixSize()
{
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextint();
return n;
}
public static void makeAndFillMatrix(int [][] r)
{
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j]= rand;
}
}
return r;
}
public static void printMatrix(int [][] matrix)
{
for(int r = 0; r < matrix.length; r++)
{
for(int c = 0; c < matrix[r].length; c++)
{
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Hint
You have many problems in your code :
int n = S.nextint(); it should be int n = S.nextInt(); with Upper I
You can't compare an int with an array for (int j = 0; j < r; j++) { i think you need this for (int j = 0; j < i; j++) {
void makeAndFillMatrix(int[][] r) it not return any thing, and your return an array in the end.
makeAndFillMatrix(int[][] r) take an array of 2D and not an int int[][] m = makeAndFillMatrix(n);
Fix this problem and your problem is solve :)
EDIT
Then you have to change your code to be like this :
public static void main(String[] args) {
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);//<<<----Problem 4
printMatrix(m);
}
public static int getMatrixSize() {
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextInt();//<<--------------Problem 1
return n;
}
public static int[][] makeAndFillMatrix(int n) {//<<<---Problem 3
Random generator = new Random(5);
int[][] r = new int[n][n];
int rand = generator.nextInt(10);
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < i; j++) {//<<<-----------Problem 2
r[i][j] = rand;
}
}
return r;
}
public static void printMatrix(int[][] matrix) {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
Change makeAndFillMatrix(int[][] r) to makeAndFillMatrix(int r)
You want the matrix size, which is an integer, so take integer instead of a multidimensional array.
And in the for loop after that, change r.length to just r
Change void to int [][] in the method declaration.
In the method add a line int[][] q; and change r[i][j] = rand to q[i][j] = rand
And change return r to return q
The error you are receiving is due to you calling
int[][] m = makeAndFillMatrix(n);
in your main method.
You set n as an int in the line above, meaning n is a number, BUT, makeAndFillMatrix(int[][]) takes in a 2d array of ints. (A 2d array is a matrix, by the way.)
If you want to make a matrix of the size entered in by the user, then instead of passing n into your makeAndFillMatrix method, you would need to pass in a matrix of size n. You can do this in two ways. Option 1 is to pass in the matrix to your makeAndFillMatrix method like so:
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(new int[n][n]); // new int matrix of size n
printMatrix(m);
}
Or (the more conventional way, in my opinion), you can give makeAndFillMatrix the size of the matrix (like you are doing), and you can have makeAndFillMatrix make the array:
public static void makeAndFillMatrix(int matrixSize)
{
int[][] r = new int[matrixSize][matrixSize];
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r[i].length; j++) //~~~I modified this line as well~~~
{
r[i][j]= rand;
}
}
return r;
}
Anyways, you can take your pick at which approach you want to take to this problem, but regardless, I noticed that your makeAndFillMatrix method had an error. I fixed it and wrote //~~~I modified this line as well~~~
Your inner for loop originally said for(int j = 0; j < r; j++), but r is a matrix. For the inner loop, you would want to increase j until it has reached the size of the current row you are on in the matrix, so I changed that line as well. (Your inner loop was correct in your printMatrix method.) Whichever approach you take for your first issue, the inner loop in your makeAndFillMatrix method will need to be modified as well.
I hope this helps!
You are trying to cast 'int' (in the main function) to an 'int[][]' (the parameter of 'makeAndFillMatrix'. Also, makeAndFillMatrix returns 'void'.
I believe you want to rewrite your function to something like this:
public static int[][] makeAndFillMatrix(int r)
{
// Create a new matrix
int[][] matrix = new int[r][r];
// Get a random value
Random generator = new Random(5);
int rand = generator.nextInt(10);
// Assign random value to each cell of the matrix
for(int i = 0; i < r; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j] = rand;
}
}
// Return the matrix
return matrix;
}
public class lab {
public static void main (String args[]){
double[][] g = {RandomArray(3)};
printArray(g);
}
private static void printArray(double[][] g) {
System.out.println(Arrays.deepToString(g));
}
public static double[][] RandomArray(int n) {
double[] [] RandomArray = new double[n] [n];
Random randomNumberCreator = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
}
}
return RandomArray;
}
}
I am not sure what is wrong with my RandomArray method, i want it to work for 2-dimensional arrays but i have clearly made a mistake as the line below is receiving an error and I am unsure as to why this is happening. If you could explain to me the error that I have made i would be grateful.
double[][] g = {RandomArray(3)};
remove the curly brace around the function Call of "RandomArray"
public static void main (String args[]){
double[][] g = RandomArray(3);
printArray(g);
}
private static void printArray(double[][] g) {
System.out.println(Arrays.deepToString(g));
}
public static double[][] RandomArray(int n) {
double[] [] RandomArray = new double[n] [n];
Random randomNumberCreator = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
}
}
return RandomArray;
}
You are initializing the array incorrectly....
you dont need the { } when calling the method RandomArray
just doing double[][] g = RandomArray(3); will do the job
I am trying to solve this exercise but I am facing some problems while trying to do so. In logical terms, I think that I am thinking right. Could you take a look at my code please and try to help me?
import java.util.Arrays;
import java.util.Random;
public class exercicio_4_alapata {
public static void main(String[] args) {
int [] Array_numal;
Array_numal = new int [100];
int [] ArrayOrdenado;
ArrayOrdenado = new int [100];
int posicao_array;
int posicao_array2 = 0;
for (posicao_array = 0; posicao_array < Array_numal.length; posicao_array ++) {
Random rand = new Random();
Array_numal [posicao_array] = rand.nextInt(101);
}
int maior = Array_numal [0];
while (maior != ArrayOrdenado[99]) {
for (posicao_array2 = 0; posicao_array2 == 99; posicao_array2 ++) {
for (posicao_array = 0; posicao_array < Array_numal.length; posicao_array ++) {
if ((Array_numal[posicao_array] > maior) && (maior < ArrayOrdenado [posicao_array2 - 1])) {
maior = ArrayOrdenado [posicao_array2];
}
}
}
}
for (posicao_array2 = 0; posicao_array2 < ArrayOrdenado.length; posicao_array2 ++) {
System.out.println(ArrayOrdenado[posicao_array2]);
}
}
}
You could try to use Arrays.sort(T[] a, Comparator c)):
Arrays.sort(a, Collections.reverseOrder());
I'm writing a Java program that uses threads to multiply two matrices. I have the following code:
public class MatrixMultiplication {
//Declare matrices
public static int[][] matrix1 = new int[][]{
{1,2,3,4},{3,2,1,4}
};
public static int[][] matrix2 = new int[][]{
{2,1,3,4},{4,2,5,3}
};
public static int[][] result = new int[4][4];
//Threads
public static Thread[][] threads = new Thread[4][4];
public static void main(String[] args){
//create worker threads with M and N hard-coded
for(int i = 0; i < threads.length; i++) {
for (int l = 0; l < threads[i].length; l++) {
threads[i][l] = new Thread(new Worker(matrix1, matrix2, result, i, l));
}
}
for(int i = 0; i < threads.length; i++){
for(int l = 0; l < threads[i].length; i++){
try {
threads[i][l].start();
threads[i][l].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("Contents of result matrix");
for(int i = 0; i < 4; i++)
for(int l = 0; l < 4; l++){
System.out.println("["+i+","+l+"] = "+result[i][l]);
}
}
}
class Worker implements Runnable{
int[][] m1;
int[][] m2;
int[][] result;
int row;
int col;
public Worker(int[][]m1, int[][] m2, int[][] result, int row, int col){
this.m1 = m1;
this.m2 = m2;
this.result = result;
this.row = row;
this.col = col;
}
public void run(){result[row][col] = (m1[row][col] * m2[col][col]) + (m1[row][col+1] * m2[col+1][col]);}
}
The programming is throwing an ArrayIndexOutOfBoundsException on multiple lines, notable lines 21 and in the run method of the Worker thread class. I have tried several variations to no avail and am looking for guidance on this. Thank you very much.
There is several points of problem. On line 21 you use I+1 instead of L+1. Also, matrix are two-dimensional arrays with only two lines, not four.