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
Related
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};
}
I'm trying to populate a 2d array in java for a sudoku board. The numbers come from a csv file. The issue is the code just reads the first four numbers, then restarts at 0 again for a new row. How do I stop this from happening, and get it to continue to the end of the numbers?
String[] lines = Cell.toCSV().split(",");
int[] intArray = new int[lines.length];
for (int i = 0; i < intArray.length; i++) {
intArray[i] = Integer.parseInt(lines[i]);
} //convert string to int
int[][] dataArray = new int[4][4]; //4x4 sudoku game
for (int col = 0; col < size; col++) {
for (int row = 0; row < dataArray[col].length; row++) {
dataArray[col][row] = intArray[row];
}
You need a separate counter for the original array :
int index = 0;
for (int col = 0; col < dataArray.length; col++) {
for (int row = 0; row < dataArray[col].length; row++) {
dataArray[col][row] = intArray[index++];
}
This is assuming the intArray has enough values to populate the 2D array. You should probably validate that prior to this loop.
BTW, the first dimension of a 2D array is usually considered as the row, not the column, so your loop variable names are a bit confusing.
public static int[][] rotate(int[][] array){
int height = array.length;
int width = array[0].length;
int[][] rotatedArray = array;
for(int col = 0; col < width; col++){
for(int row = 0; row < height; row++){
rotatedArray[row][col] = array[col][row];
}
}
return rotatedArray;
}
This is my code as method to rotate image 90 degree counter-wise, but it doesn't work. I have no idea how to arrange new rows and columns and rotate it properly, how can I fix it? Thanks!
Try rotatedArray[row][col] = array[col][height - row - 1];.
Also, you need to define rotatedarray as a new array. Right now, you're assigning it array, which means they are both referencing the same data.
Here's how you can do it:
public static int[][] rotate(int[][] array) {
int height = array[0].length;
int width = array.length;
int[][] rotatedArray = new int[height][];
for(int row = 0; row < height; row++) {
rotatedArray[row] = new int[width];
for(int col = 0; col < width; col++) {
rotatedArray[row][col] = array[col][height - row - 1];
}
}
return rotatedArray;
}
Note that the height of the original array becomes the width of the new array and vice versa.
By transposing the row & column indices with rotatedArray[row][col] = array[col][row], you are mirroring the image along the diagonal, instead of rotating it. Think about it - any entry where both indices are matching such as array[0][0] or array[1][1] is unchanged. That's not what you want!
I would recommend drawing a picture to see what pattern you see. You can start with very small examples, 2-by-2 or 3-by-3.
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++){ ... ... }}
I have 2 1d arrays and im trying to populate them into a single 2d array in JAVA.
For instance:
x[] = {2,5,7,9}
y[] = {11,22,33,44}
The results should then be:
result[][] = {{2,5,7,9}, {11,22,33,44}}
How do I go about this? I currently have something like this:
for(int row = 0; row < 2; row++) {
for(int col = 0; col == y.length; col++) {
???
}
}
Im sort of stuck from there...
2D array is an array of arrays. So why don't you try this?
int result[][] = {x,y};
And to make sure that it is so simple and works, test this:
for(int i=0; i<result.length; i++)
{
for(int j=0; j<result[0].length; j++)
System.out.print(result[i][j]+ " ");
System.out.println();
}
Try this:
ArrayList<Integer[]> tempList = new ArrayList<Integer[]>();
tempList.add(x);
tempList.add(y);
Integer result[][] = new Integer[tempList.size()][];
result = tempList.toArray(tempList);
You have to revert the row and column indices
for(int row = 0; row < 2; row++)
{
for(int col = 0; col = y.length; col++)
{
....
}
}