Kisuna97
Kisuna97

Reputation: 37

Shifting a certain column in a 2D array

Can I get a general idea of shifting a specific column of a 2D array? I have the array populated through a double for loop however I'm stuck on how to approach this. I don't necessarily need code. I just need a way of thinking to approach.

I also have another question. array.length prints out the length of the array but I saw around the internet, and people used:

for (int i=0; i<array.length; i++)
{
   for (int j=0; j<array[i].length; j++)
   array[i][j] =(int)(Math.random()*((9)+1));
}

What is the functionality of array[i].length?

Upvotes: 0

Views: 649

Answers (1)

Captain Prinny
Captain Prinny

Reputation: 469

Specifically to your question, array[i].length is the length of "dimension 2" for "dimension 1". Specifically, a two dimensional array is not a "grid", it is an actual table of sorts. If you think about a data-table, each row is a single "entry" (commonly tuple, or an ordered collection), and if you put in your first dimension, you get the whole row, and then the second dimension refines your selection. This can be done vertically, but data is commonly read left to right so you reference a row.

The outer loop is dimension i, and then for a given dimension i, you go through it as dimension j.

Basically, int x[i][j] is an array that contains i arrays that contains j integers.

    1    2    3   ...    i
1
2
3
...
j

The arrangement here is purely based on however you choose to utilize it, as you could swap i and j in the diagram and change nothing, you just have to work on it consistently (rows have to always be rows, etc).

Depending on how you're arranging the data logically, your question has one of two answers. If columns are your dim1, then you just swap it identically to a 1-dimensional array. That's because each array is itself a container, so you can move the entire container.

    1      >>      2    3   ...    i
1          shift
2          shift
3          shift
...        ....
j          shift

If you're trying to do it on the second dimension... You should be able to do it by iterating over every "second" one and shifting each array, internally, by one.

    1    2    3   ...    i
1
VV  sh  sh   sh          sh
2
3
...
j

Upvotes: 2

Related Questions