Needs advice with Java 2d array

I need to create a method that uses a 2d array of lanes and columns. The lanes represent lanes of a road and columns segment of measurement of the road. These are varied numbers initialized in the class constructor. cars, represented by ones get added to the road at param specific location.

I need my method when called to move all cars one column forward, and if they reach the array.legth they start back at spot 0.

I am lost around here.

public void advanceAllForward() {
    for (int currColumn = 0; currColumn <= this.position.length; 
        currColumn++) {
        column = currColumn;
    this.position[lane][column] = this.position[lane][column];

1 answer

  • answered 2019-06-11 23:07 Jason

    Let's break this down into individual steps.

    You want to take the value stored at a specific location in the 2d array and put it into the location for the next 'column'.

    But, you don't want to lose the value in that position, because you need to move it as well.

    The easiest way to do this, is to start at the last column and work backwards. That way, the value you overwrite will already have been moved, so it is safe to overwrite it.

    First, you'll need to store the values in the last column, so they can be inserted into column 0 when you are done.

    Then, you can iterate backwards through the columns, moving each value into the next column.

    Finally, you can insert those saved values from the last column into column zero.

    for(int lane = 0; lane < position.length; lane++) { // for each lane in the 2d array
        int lastValue = position[lane][position[lane].length - 1]; // save the last value in that lane
        for(int column = position[0].length - 2; column >= 0; column--) { // for each column in the lane starting at the second to last item
            position[lane][column + 1] = position[lane][column]; // move the value to the right
        position[lane][0] = lastValue; // write the last value into position zero