Initializing a 2-D Array in java - java

Little confused why this isn't working could use a little help, I want to set all the values to false:
boolean[][] seatArray = new boolean[4][4];
for(int x = 0; x < seatArray.length; x++){
for(int y = 0; y < seatArray.length; y++){
seatArray[x][y] = false;
}
}

You have to ensure that you are iterating over the correct array element in your inside for loop to set every value to be false. Try this:
boolean[][] seatArray = new boolean[4][4];
for(int x = 0; x < seatArray.length; x++){
for(int y = 0; y < seatArray[x].length; y++){
seatArray[x][y] = false;
}
}
EDIT: Your code should still work, but for convention you should still probably do this.

You don't actually need to explicitly set any value.
The primitive boolean defaults to false.
Hence:
boolean[][] seatArray = new boolean[4][4];
System.out.println(seatArray[0][1]);
Output
false

BY defaultif u initialize a 2D boolean array it will contain value as false
Lets say you have a two dimensional array as
boolean[][] seatArray=new boolean[4][4];//all the value will be false by default
so it is a 4*4 matrix
boolean[0] represents the the 1st row i.e Lets say it contains value like {true,true,true,true} if you need the value in individual cell you need to iterate 2 for each loop like
for (boolean[] rowData: seatArray){
for(int cellData: rowData)
{
System.out.printn("the indiviual data is" +cellData);
cellData=Boolean.false;
}
}

Your code should work but here is another solution for filling a 2D array:
boolean[][] b = new boolean[4][4];
for (int i = 0; i < b.length; i++)
Arrays.fill(b[i], false);

Another way to make sense of iterating over multi dimensional arrays is like this.
boolean[][] seatArray = new boolean[4][4];
//Foreach row in seatArray
for(boolean[] arr : seatArray){
for(int i = 0; i < arr.length; i ++){
arr[i] = false;
}
}

If you have already given a constant size of array, avoid using .length and use the constant instead.
for(int x = 0; x < 4; x++){for(int y = 0; y < 4; y++){ ... ... }}

Related

How do I read through a 2D array without searching out of bounds?

I have a 2D array acting as a grid.
int grid[][] = new int[5][5];
How do I search through the grid sequentially as in (0,0), (1,0), (2,0), (3,0), (4,0) then (0,1), (1,1), (2,1) ... without getting any array out of bounds exceptions.
I'm new to programming and I just can't get my head around how to do this.
You know your lengths, now use a for loop to circle through the array.
for (int i = 0;i<5;i++){
for (int j = 0;i<5;i++){
int myInt = grid[i][j];
//do something with my int
}
}
To get the lengths at runtime you could do
int lengthX = grid.length; //length of first array
int lengthY = 0;
if ( lengthX>0){ //this avoids an IndexOutOFBoundsException if you don't know if the array is already initialized yet.
lengthY = grid[0].length; //length of "nested" array
}
and then do the for loop with lengthX and lengthY.
You will need two nested loop in order to access the two dimensions of your array:
int grid[][] = new int[5][5];
for(int i = 0; i < 5; i++ ) {
for(int j = 0; j < 5; j++ ) {
int value = grid[i][j];
}
}
Use 2 forloops like the following example:
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
System.out.println(grid[i][j]);
}
}
Also i would suggest that when initializing an array to write it like this:
int[][] grid = new int[5][5]; // note the double brackets are after int and not grid
Try this:
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.println(grid[j][i]);
}
}
This code (like the other answers) uses two for loops.
It does however add some handling of edge-cases
static int[] find(int[][] mtx, int valueToLookFor)
{
int rows = mtx.length;
if(rows == 0)
return new int[]{-1,-1};
int cols = mtx[0].length;
if(cols == 0)
return new int[]{-1, -1};
for(int r=0;r<rows;r++)
{
for(int c=0;c<cols;c++)
{
if(mtx[r][c] == valueToLookFor)
return new int[]{r,c};
}
}
return new int[]{-1,-1};
}

Java: Dynamically size Columns in 2D Array

How can I size my columns dynamically to support a possible ragged array?
int[][] x;
x = new int[3][] //makes 3 rows
col = 1;
for( int i = 0; i < x.length; i++){
x = new int[i][col]
col++; }
Would the above code assign each col length?
Thank you in advance for any help.
since you are re-assigning x, what you are doing is creating the entire 2D array each loop, which is wrong.
You need to do inside your loop:
x[i] = new int[col];
// create the single reference
int[][] x;
// create the array of references
x = new int[3][] //makes 3 rows
int col = 1;
for( int i = 0; i < x.length; i++){
// this create the second level of arrays // answer
x[i] = new int[col];
col++;
}
More on 2D Arrays.
- https://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm

Get a Matrix from another Matrix

So guys, I'm developping a program for Structural Analysis and I came across a problem that I'm having some problem to solve. Basically, I have a system of equations, of which I only need to solve some of them.
The ones I need to solve depend on a boolean array, true if I do, false if I don't. This way, having a true value in the nth element of the array means I'll have to solve the nth equation, therefore meaning that I have to get the nxn element of the matrix of the system of equations.
Do you guys have any insight on it?
So, this is what I've come up with:
//Firstly, define the size of the subsystem:
int size = 0;
for(int i = 0; i < TrueorFalseMatrix.m; i++) {
if(TrueorFalseMatrix.data[i][0] != 0)
size+= 1;
}
//Then we can assign the size values to the Matrix of the subsystem
System_A = Matrix.matrizEmpty(size,size);
System_B = Matriz.matrizEmpty(size, 1);
//This array will store the coordinates of the coefficients that
//will be used
int[] Coordinates = new int[size];
//We store these coordinates in the array
int count = 0;
for(int i = 0; i < TrueorFalseMatrix.m; i++) {
if(TrueorFalseMatrix.data[i][0] != 0) {
Dtrue[count] = i;
count++;
}
}
//We can now assign values to our system Matrix
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
System_A.data[i][j] = SourceMatrix.data[Dtrue[i]][Dtrue[j]];
}
System_B.data[i][0] = SourceResultVector.data[Dtrue[i]][0]
}
//Results
double[] Results = System.solve(System_A,System_B);

How to create multiple arrays with a loop?

I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}

Returning arrays to main method

I have a question about returning an array from one method back to main. It is seriously starting to annoy me and I cannot wrap my brain around this. It seems as if even though I have changed the array in my method, when I go to display it in main it displays the old array. I'm trying to remove the duplicate numbers in my array and I know it works because I have stepped through it in the debugger yet after I return it and go back to main, it displays the whole array again! I know it must be something easy that I am missing here. Can someone please point me in the right direction? Here is my code...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter 10 numbers: ");
for (int x = 0; x < numbers.length; ++x)
numbers[x] = input.nextInt();
eliminateDuplicates(numbers);
for (int y = 0; y < numbers.length; ++y)
System.out.print(numbers[y] + " ");
}
public static int[] eliminateDuplicates(int[] numbers) {
int[] temp = new int[numbers.length];
int size = 0;
boolean found = false;
for (int x = 0; x < numbers.length; ++x) {
for (int y = 0; y < temp.length && !found; ++y) {
if (numbers[x] == temp[y])
found = true;
}
if (!found) {
temp[size] = numbers[x];
size++;
}
found = false;
}
int[] result = new int[size];
for (int z = 0; z < result.length; ++z)
result[z] = temp[z];
return result;
}
}
Look at this call:
eliminateDuplicates(numbers);
You're ignoring the return value. Perhaps you wanted:
numbers = eliminateDuplicates(numbers);
I sometimes wish that Java had a way of indicating that a method's return value shouldn't be ignored. It would save a lot of questions around InputStream.read as well...
It should be: numbers = eliminateDuplicates(numbers);
You were essentially ignoring the returned result from the method.
Do like this:
int[] result =eliminateDuplicates(numbers);
for (int y = 0; y < result.length; ++y)
System.out.print(numbers[y] + " ");
Also, In your eliminateDuplicates() method, use result array directly by removing temp array. Or rename temp to result and return it. Following code is unnecessary :
int[] result = new int[size];
for (int z = 0; z < result.length; ++z)
result[z] = temp[z];
In Java, parameters are passed by value, so you can't use numbers as an in/out parameter.
e.g. if you C# you could have done
eliminateDuplicates(ref numbers);
But as others have pointed out, the most obvious issue is that you forgot to assign the result :)
In your main, try this:
numbers = eliminateDuplicates(numbers);
Method calling should be like this -
numbers = eliminateDuplicates(numbers);
You are not catching the result returning by eliminateDuplicates function.

Categories

Resources