Defqon
Defqon

Reputation: 107

Insert column in desired location of 2D array

I'm looking to choose a column of my array, lets say column 2. I want this column to be inserted at a specific location in the 2D array, lets say column 4.

For example:

1 3 5 5 2
2 4 6 2 1
3 6 9 1 1

The desired output would be:

1 5 5 3 2
2 6 2 4 1
3 9 1 6 1

I know I could loop the following code until I 1 by 1 swap every column until the column is in the desired location.

for (int[] array1 : array) {
    int temp = array1[col1];
    array1[col1] = array1[col1];
    array1[col2] = temp;
}

However, if I'm using large matrices such as 30 columns wide, this would be incredibly inefficient. Is there a way to insert the column anywhere in the 2D array without iterating through each swap until it is in the right spot?

Upvotes: 1

Views: 157

Answers (2)

user4910279
user4910279

Reputation:

Try this.

public static void moveColumn(int[][] matrix, int from, int to) {
    --from; --to;  // If column number begins with zero, remove this line.
    int srcPos = from < to ? from + 1 : to;
    int destPos = from < to ? from : to + 1;
    int length = Math.abs(from - to);
    for (int[] array : matrix) {
        int temp = array[from];
        System.arraycopy(array, srcPos, array, destPos, length);
        array[to] = temp;
    }
}

and

int[][] matrix = {
    {1, 3, 5, 5, 2},
    {2, 4, 6, 2, 1},
    {3, 6, 9, 1, 1}
};
moveColumn(matrix, 2, 4);
for (int[] row : matrix)
    System.out.println(Arrays.toString(row));

output

[1, 5, 5, 3, 2]
[2, 6, 2, 4, 1]
[3, 9, 1, 6, 1]

Upvotes: 1

Nowhere Man
Nowhere Man

Reputation: 19545

Possibly, a performance may be improved by using parallel processing with streams.

IntStream of row indexes should be used to handle each row separately.

    // basic shift method
    // from, to - indexes starting from 1
    public static void shiftArray(int[] arr, int from, int to) {
        int tmp = arr[from - 1];
        for (int i = from; i < to; i++) {
            arr[i - 1] = arr[i];
        }
        arr[to - 1] = tmp;
    }

    public static void main(String[] args) {
        int[][] arr2d = {
            {1, 3, 5, 5, 2},
            {2, 4, 6, 2, 1},
            {3, 6, 9, 1, 1}
        };
        int fromColumn = 2;
        int toColumn = 4;

        IntStream.range(0, arr2d.length)
              .parallel()
              .forEach(i -> shiftArray(arr2d[i], fromColumn, toColumn)); // shift each row in parallel

        // print the 2D array after shift
        Arrays.stream(arr2d)
              .map(Arrays::toString)
              .forEach(System.out::println);
    }

Output:

[1, 5, 5, 3, 2]
[2, 6, 2, 4, 1]
[3, 9, 1, 6, 1]

Upvotes: 2

Related Questions