0

I am trying to implement the following procedure in Java. I have an array where each element is a triplet. For example:

int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };

I want to swap every triplet in the array (with the others triplets at their right hand) in order to get each of the following matrix:

b = { {1,2,1},{0,1,0},{1,0,0},{0,2,0} };
c = { {1,0,0},{1,2,1},{0,1,0},{0,2,0} };
d = { {0,2,0},{1,2,1},{1,0,0},{0,1,0} };
e = { {0,1,0},{{1,0,0},{1,2,1},{0,2,0} };
f = { {0,1,0},{0,2,0},{1,0,0},{1,2,1} };
g = { {0,1,0},{1,2,1},{0,2,0},{1,0,0} };

In general for a Matrix of k triplets there are [(k*(k-1))/2] possibles swap.

How do I solve the problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
Fco.Jav.Y
  • 65
  • 9

1 Answers1

0

A doubly-nested loop should work here. Note that the output for which you are asking is actually a 3D array (array of 2D arrays):

public int[][] copy2DArray (int[][] input) {
    int[][] output = new int[input.length][];
    for (int r=0; r < input.length; ++r) {
        output[r] = new int[input[r].length];
        for (int c=0; c < input[0].length; ++c) {
            output[r][c] = input[r][c];
        }
    }

    return output;
}

public static void main(String[] args) {
    int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };
    int numSwaps = a.length*(a.length-1) / 2;
    int[][][] result = new int[numSwaps][][];

    int counter = 0;
    for (int i=0; i < a.length-1; ++i) {
        for (int j=i+1; j < a.length; ++j) {
            result[counter] = copy2DArray(a);
            int[] temp = result[counter][j];
            result[counter][j] = result[counter][i];
            result[counter][i] = temp;
            ++counter;
        }
    }

    System.out.println(Arrays.deepToString(result));
}

This prints:

[
    [[1, 2, 1], [0, 1, 0], [1, 0, 0], [0, 2, 0]],
    [[1, 0, 0], [1, 2, 1], [0, 1, 0], [0, 2, 0]],
    [[0, 2, 0], [1, 2, 1], [1, 0, 0], [0, 1, 0]],
    [[0, 1, 0], [1, 0, 0], [1, 2, 1], [0, 2, 0]],
    [[0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 2, 1]],
    [[0, 1, 0], [1, 2, 1], [0, 2, 0], [1, 0, 0]]
]

For some notes, the strategy I used to is to loop over all positions swap positions, using a two level for loop. For each possible swap, we start by cloning your input 2D a array. Then, we swap the individual 1D arrays at whatever positions are chosen. Finally, we add that swapped array to the 3D result array. We could have also used something like a list to store the swapped 2D arrays.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thank you for taking the time to respond to this question. I was wondering if there a way to print separately each of the arrays of triplets (in the example 6 arrays of 4 triplets each). That – Fco.Jav.Y Jul 19 '19 at 05:18
  • Yes, just iterate the 3D array result, then print each array. I will leave that to you as part of the assignment! – Tim Biegeleisen Jul 19 '19 at 05:25