user      0
user 0

Reputation: 29

Multiplying size of 2d array in a specific way?

I looked around but haven't found an answer. It'd be easiest to explain with an example. Let's say I have a 2d array that has the values

{{1, 2, 3},
 {4, 5, 6}}

What I want to do is multiply the size of the 2d array such that the resulting array has each of those elements repeated x amount of times (preferably 32). Example end results:

{{1, 1, 2, 2, 3, 3},
 {1, 1, 2, 2, 3, 3},
 {4, 4, 5, 5, 6, 6},
 {4, 4, 5, 5, 6, 6}}

In this case the original was multiplied by 2, so it made squares 2 by 2 with each value. Any ideas?

Upvotes: 2

Views: 63

Answers (1)

fabian
fabian

Reputation: 82461

Assuming you use int:

int x = //...
int[][] input = //...
int[][] result = new int[input.length * x][];
final int size = input[0].length;

for (int i = 0; i < input.length; i++) {
    int[] inputArray = input[i];
    int[] array = new int[size * x];
    final int offset = i * x;

    result[offset] = array;

    // fill first of the equal lines
    for (int j = 0; j < size; j++) {
        final int offset2 = j * x;
        // copy every element x times
        Arrays.fill(array, offset2, offset2 + x, inputArray[j]);
    }

    // copy line x-1 times
    for (int j = 1; j < x; j++) {
        // if you needn't write to the result, use array as right hand side instead
        result[offset + j] = Arrays.copyOf(array, array.length);
    }
}

Upvotes: 1

Related Questions