Three Dimensional Boolean Arrays In Java - java

I have the following code:
public class Map {
private Random rand = new Random();
private int x, y, z;
private boolean[][][] blocks;
/**
* Creates a map object. Map objects include a 3 dimensional
* boolean array. Declared through <code>new boolean[z][y][x]</code>.
* #param x
* #param y
* #param z
*/
public Map(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
this.blocks = new boolean[this.z][this.y][this.x];
for (boolean[][] i : this.blocks) {
for (boolean[] j : i) {
for(int k = 0; k < j.length; k++) {
j[k] = (rand.nextInt(1) == 1);
}
}
System.out.println(Arrays.toString(this.blocks));
}
}
/**
* Returns the map array.
* #return
*/
public String getMap() {
return Arrays.toString(blocks);
}
}
I want to create a three-dimensional boolean array of random true/false values. However, whenever I call new Map(10, 10, 10) I get a "java.lang.NullPointerException", which means that the array is either full of null values, or is null itself.
What I want to know is how can I create this array, so I do not get this exception (nor any other exception).
EDIT: I fixed an error with setting a value for rand, but the loops still do not fill the array with booleans. I get this:
[[[Z#6d06d69c, [[Z#7852e922, [[Z#4e25154f, [[Z#70dea4e, [[Z#5c647e05, [[Z#33909752, [[Z#55f96302, [[Z#3d4eac69, [[Z#42a57993, [[Z#75b84c92]

That is because your array is not really 3D, it is an array of array of arrays. So your line
this.blocks = new boolean[this.z][this.y][this.x];
creates an array of z instances of boolean[][], all of which are null. So we need to create them explicitely:
this.blocks = new boolean[z][y][x];
for (int i = 0; i < z; i++) {
this.blocks[i] = new boolean[y][x];
for (int j = 0; j < y; j++) {
this.blocks[i][j] = new boolean[x];
for(int k = 0; k < x; k++) {
this.blocks[i][j][k] = (rand.nextInt(1) == 1);
}
}
}
System.out.println(Arrays.toString(this.blocks));

Related

What exactly should I be returning in this code?

We are creating a program that will return a topographic map and show the user the best way to navigate the terrain without making steep climbs or descents. For the files that I am working with, I am not sure what maximum and minimum values need to be returned. The assignment is mostly complete except for 3 errors regarding an expected return value. I've submitted the primary code that we are working with and included a link to the other files the professor has given us for the assignment.
I've tried return maxValue, return minValue, return max, return min, and a few other combinations but the issue is I'm not sure if I am supposed to be returning a value from this MapDataDrawer.java file or from one of the other two files that we have to use for the assignment from the professor.
//MapDataDrawer.java
//This is the code that is returning the error
import java.util.*;
import java.io.*;
import java.awt.*;
public class MapDataDrawer
{
private int[][] grid;
public MapDataDrawer(String filename, int rows, int cols){
// initialize grid
grid = new int[rows][cols];
//read the data from the file into the grid
File dataFile = new File(filename);
try {
Scanner dataInput = new Scanner(dataFile);
for (int i=0; i<rows; i++) {
for (int j=0; j<cols;j++) {
grid[i][j] = dataInput.nextInt();
}
}
} catch (Exception e) { e.printStackTrace();}
}
/**
* #return the min value in the entire grid
*/
public int findMin() {
// Implement this method
}
/**
* #return the max value in the entire grid
*/
public int findMax(){
// Implement this method
}
/**
* #param col the column of the grid to check
* #return the index of the row with the lowest value in the given col for the grid
*/
public int indexOfMinRow(int col){
//Implement this method
}
/**
* Draws the grid using the given Graphics object.
* Colors should be grayscale values 0-255, scaled based on min/max values in grid
*/
public void drawMap(Graphics g){
int min = findMin();
int max = findMax();
for (int i=0; i<480; i++) {
for (int j=0; j<480; j++) {
int c = (255 * (grid[i][j] - min)) / (max - min);
g.setColor(new Color(c, c, c));
g.fillRect(j, i, 1, 1);
}
}
}
/**
* Find a path from West-to-East starting at given row.
* Choose a foward step out of 3 possible forward locations, using greedy method described in assignment.
* #return the total change in elevation traveled from West-to-East
*/
public int drawLowestElevPath(Graphics g, int row){
int elevChange = 0;
// Implement this method
return elevChange;
}
private int minOfThree(int a, int b, int c) {
if ((a > b) && (a > c)) return a;
if ((b > a) && (b > c)) return b;
if ((c > a) && (c > b)) return c;
return 0;
}
}
These are the professors submitted files, of which I am unsure if I am supposed to be returning some value from one of these files or from the actual homework file (MapDataDrawer.java) https://drive.google.com/drive/folders/1siRoY1K0ngptE2rL-wscXLK8Ct7Qo1hb?usp=sharing
It also includes the topographic data we are supposed to use.
As you have filled grid:
public int findMin() {
int min = Integer.MAX_VALUE;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
int value = grid[i][j];
if (value < min) {
min = value;
}
}
}
return min;
}

Array required but int found

What's wrong with my progam?
public class Square{
public int x;
public Square() {
int x[] = new int[10];
int y;
x[0] = 7;
}
public void root() {
for (int i = 0; i < 10; i++) {
x[i+1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5));
System.out.println(x[i + 1]);
}
}
}
I don't get what's wrong, my for loop does not seem to be working and it keeps on displaying the error for some reason. Could someone help me figure this out?
Okay, I wrote this program now:
public class Square
{
public double x[];
public void root()
{
double x[] = new double[10];
x[0]=7;
for(int i=0; i<8; i++)
{
x[i+1]=x[i]-(Math.pow(x[i]-2.5,2))/(2*(x[i]-2.5));
System.out.println(x[i+1]);
}
}
}
And it is showing this output:
3.625
3.0625
2.78125
2.640625
2.5703125
2.53515625
2.517578125
java.lang.NullPointerException
at Square.root(Square.java:14)
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at Square.root(Square.java:11)
I don't know why I'm getting these errors. Also, the answer should be 6.25 at some point. But, it doesn't show that output.
Your constructor has a local variable int[] x which is disarded at the end of the constructor.
Try this:
public class Square{
// initialize to array of ten ints
public int x[] = new int[10];
public Square() {
x[0] = 7;
}
public void root() {
for (int i = 0; i < 10; i++) {
x[i+1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5));
System.out.println(x[i + 1]);
}
}
}
Edit: The int y is local to the constructor, it is discarded at the end of the constructor scope, too.
This is because you have defined x previously as just an int, instead of an array of ints.
Try this:
public class Square {
public int x[];
public Square() {
this.x = new int[10];
int y;
x[0] = 7;
}
public void root() {
for(int i = 0; i < 10; i++) {
x[i + 1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] -2.5));
System.out.println(x[i + 1]);
}
}
}
Here is the commented code explaining the problem :
public class Square
{
// Here, x is defined as an attribute of class Square, of type int
public int x;
public Square()
{
// Here, x is locally defined as a local variable, of type int[]
// It shadows the attribute x. This is considered as a bad practice.
int x[] = new int[10];
int y;
// Here, x is the local variable, of type int[]. It IS an array so
// this line is valid.
x[0]=7;
}// From this point, the local variable x is not defined anymore
// (that is the point of a local variable)
Now here :
public void root()
{
for(int i=0; i<10; i++)
{
// Here, x is referencing the attribute of class Square, which is an int
// But you try to access it as if it was and int[]
x[i+1]
First you must declare x as an array:
public int[] x;
notice that the java style is not int x[];
Then inside Square() you have to initialize x like this:
x = new int[10];
Finally, this:
(Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5))
returns a double so you have to cast it to int:
x[i+1] = x[i] - (int) ((Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5)));
So your code should be:
public int[] x;
public void Square() {
x = new int[10];
x[0] = 7;
}
public void root() {
if (x == null)
Square();
for(int i = 0; i < x.length - 1; i++) {
x[i+1] = x[i] - (int) ((Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5)));
System.out.println(x[i+1]);
}
}
Inside the loop you are accessing the i + 1 item so the counter of the loop must take values up to x.length - 2, this is why I have in the code: i < x.length - 1.
I have removed the declaration of y from Square() as it is not used.
public class Square
{
public double x[];
public Square()
{
this.x = new double[10];
x[0]=7;
}
public void root()
{
System.out.println(x[0]);
for(int i=1; i<10; i++)
{
x[i]=x[i-1]-(Math.pow(x[i-1]-2.5,2))/(2*(x[i-1]-2.5));
System.out.println(x[i]);
}
}
}
Try use this code
public class Square
{
public double x[];
public void root()
{
x = new double[10];
x[0]=7;
for(int i=1; i<10; i++)
{
x[i]=x[i-1]-(Math.pow(x[i-1]-2.5,2))/(2*(x[i-1]-2.5));
System.out.println(x[i]);
}
}
}

CopyOf returning array

jump is an array that has been initialised.
FunctionMonius3.difRandoms method returns an array
jump = FunctionMonius3.difRandoms(posMonius.length, lines * col, generator);
or
jump = Arrays.copyOf(FunctionMonius3.difRandoms(posMonius.length, lines * col, generator), v.length);
Does the first option just creates a reference that is destroyed when the method FunctionMonius3.difRandoms ends or is it ok?
* #param n - number of array elements
* #param sup - max value
* #param g - generator
public static int[] difRandom (int n, int sup, Random g){
int[] result = new int [n];
int i = 0;
while (i < result.length) {
int random = g.nextInt(sup) + 1;
if (!contidoEmParte(aleatorio,result,i)){
result[i] = random;
i++;
}
}
return result;
}

return new int[]{randomHeight, randomWidth};

I want to code some basic stuff for a little minesweeper-game, that we do in university. Now I have the problem that my code .
public class Minesweeper1 {
public static int[][] makeRandomBoard(int s, int z, int n){
//creating the field and fill with 0
int feld[][] = new int [s][z];
for(int i = 0; i < s; i++){
for(int j = 0; j < z; j++){
feld[i][j] = 0;
}
}
//n-times to fill the field
for( int i = 0; i < n; i++){
selectRandomPosition(s, z);
//want to get them from selectRandomPosition
feld[randomHeight][randomWidth] = 1;
}
}
}
So it starts the selectRandomPosition code:
public static int[] selectRandomPosition(int maxWidth, int maxHeight) {
int randomHeight = StdRandom.uniform(0, maxHeight);
int randomWidth = StdRandom.uniform(0, maxWidth);
return new int[]{randomHeight, randomWidth};
}
Here I'm not allowed to change anything, but it returns a new array. Now is my question how can I use the new array in my makeRandomBoard method, since I do not know any name of the array. When I use feld[randomHeight][randomWidth] = 1;, it says that it doesn't know these variables.
how I can use the new array in my makeRandomBoard method, since I do not know any name of the array?
Call the method, and assign its return value to a variable. Now you have a name for the array:
// Make a call
int[] randomArray = selectRandomPosition(maxW, maxH);
// Access the width
int randomW = randomArray[0];
// Access the height
int randomH = randomArray[1];

How to convert a 1d array to 2d array?

Say, I have a 1d array with 30 elements:
array1d[0] = 1
array1d[1] = 2
array1d[2] = 3
.
.
.
array1[29] = 30
How to convert the 1d array to 2d array?
Say 10x3?
array2d[0][0] = 1 array2d[0][1] =2 array2d[0][2] =3
.
.
.
array2d[9][0] = 28 array2d[9][1] =29 array2d[9][2] =30
Should I use a for loop?
But I cannot work it out.
Without writing any code for you...
Think about how big your 2d array needs to be.
Recognize that you'll need to loop over the contents of your source array to get each value into your destination array.
So it will look something like...
Create a 2d array of appropriate size.
Use a for loop to loop over your 1d array.
Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
I'm being intentionally vague, seeing as this is homework. Try posting some code so we can see where you get stuck.
int array2d[][] = new int[10][3];
for(int i=0; i<10;i++)
for(int j=0;j<3;j++)
array2d[i][j] = array1d[(j*10) + i];
Here a generic function to convert from 1D -> 2D array:
public int[][] monoToBidi( final int[] array, final int rows, final int cols ) {
if (array.length != (rows*cols))
throw new IllegalArgumentException("Invalid array length");
int[][] bidi = new int[rows][cols];
for ( int i = 0; i < rows; i++ )
System.arraycopy(array, (i*cols), bidi[i], 0, cols);
return bidi;
}
If you want to do the contrary (2D -> 1D), here the function:
public int[] bidiToMono( final int[][] array ) {
int rows = array.length, cols = array[0].length;
int[] mono = new int[(rows*cols)];
for ( int i = 0; i < rows; i++ )
System.arraycopy(array[i], 0, mono, (i*cols), cols);
return mono;
}
public class Test{
public static void main(String[] argv)
{
int x,y;
for(int num =0; num<81;num++)
{
if((num % 9)>0)
{
x = num/9;
y = num%9;
}else
{
x = num/9;
y = 0;
}
System.out.println("num ["+num+"]---["+x+","+y+"]");
}
}
}
/* Replace 9 by the size of single row of your 2D array */
You often will find the same problem: how to manipulate 2D array as 1D array.
I wrote a generic class Grid, that lets access objects by index or by (x,y).
See the following class and understand the idea behind it. :)
You could use the following class for data manipulation as 2D array or 1D array. Here is the code for that I wrote and use.
/**
* Grid represents a 2 dimensional grid.
*
* #param <E> the type of elements in this grid
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Grid<E>
{
private int size ;
private int width ;
private int height ;
private List<E> elements;
public int getCapacity()
{
return getWidth() * getHeight();
}
/**
* #return number of elements in grid. Null is also an element.
*/
public int getSize()
{
return getElements().size();
}
/**
* #param sideSize size of the grid side
*/
public Grid(int sideSize)
{
this(sideSize,sideSize);
}
/**
* #param width of the grid
* #param height of the grid
*/
public Grid(int width, int height)
{
this.width = width ;
this.height = height;
this.elements = new ArrayList<E>(
Collections.nCopies(width*height, (E)null));
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
/**
* #return all elements of the grid
*/
public List<E> getElements()
{
return elements;
}
/**
* #return iterator for a grid
*/
public Iterator<E> iterator()
{
return getElements().iterator();
}
/**
* Returns the element at position (x,y).
*
* #return the element at position (x,y)
*/
public E get(int x, int y)
{
return getElements().get(
idx(x,y));
}
/**
* Returns the element at index idx.
*
* #return the element at given index
*/
public E get(int idx)
{
return getElements().get(idx);
}
/**
* Puts an element to the position idx
*
* #param element to be added
*
* #param x position x to add element to
*
* #param y position y to add element to
*/
public void put(int x, int y, E element)
{
put(idx(x,y), element);
}
/**
* Puts an element to the position idx
*
* #param element to be added
*
* #param idx to add element at
*/
public void put(int idx, E element)
{
getElements().add(idx, element);
}
/**
* Returns the x coordinate from the index.
*
* #return x coordinate of the index
*/
public int x(int idx)
{
return idx % getHeight();
}
/**
* Returns the y coordinate from the index.
*
* #return y coordinate of the index
*/
public int y(int idx)
{
return (idx - idx % getHeight()) / getHeight();
}
/**
* Returns index of element at (x,y).
*
* #return index of the coordinates
*/
public int idx(int x, int y)
{
return y*getHeight() + x;
}
}
Here is how to use the class (see a test example):
public class TestGrid
{
public static final int SIZE = 10;
public static final Integer el1 = new Integer(2);
public static final Integer el2 = new Integer(3);
public static final Integer el3 = new Integer(3);
public static void main(String[] args)
{
Grid<Integer> grid = new Grid<>(SIZE);
assert grid.getCapacity() == SIZE*SIZE ;
assert grid.idx(0,0) == 0 ;
assert grid.idx(1,0) == 1 ;
assert grid.idx(0,1) == 10;
assert grid.idx(6,1) == 16;
assert grid.idx(9,9) == 99;
grid.put(1, el1);
assert grid.get(1) == el1 : grid.get(1);
grid.put(0, 1, el2);
assert grid.get(0,1) != el1 && el1 != el2 && grid.get(0,1) == el2;
grid.put(15, el3);
assert grid.get(5,1) == el3;
}
}
This is just a pseudo code. ROWS represent the length of the 2d array, and COLUMNS represent the length of the 1st element in the array
for(i=0; i<ROWS; i++)
for(j=0; j<COLUMNS; j++)
array2d[i][j] = array1d[ (i*COLUMNS) + j];
package com.vikrant;
import java.util.Arrays;
public class TwoD {
public static void main(String args[])
{
int a[][]=new int[4][3];
int d[]={10,20,30,40,50,60,70,80,90,100,110,120};
int count=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<3;j++)
{
if(count==d.length) break;
a[i][j]=d[count];
count++;
}}
int j=0;
for (int i = 0; i<4;i++)
{
for(j=0;j<3;j++)
System.out.println(a[i][j]);
}
}}
THIS DOES THE WORK
int[] oneDArray = new int[arr.length*arr.length];
//Flatten 2D array to 1D array...
int s = 0;
for(int i = 0; i < arr.length; i ++)
for(int j = 0; j < arr.length; j ++){
oneDArray[s] = arr[i][j];
s++;
}
You can't "convert" a 1D array to a 2D array, but an array can be multi-dimensionnal when you declare it.
int myArray2d[][] = new int[10][3]

Categories

Resources