2

I have an array in Java.

// original array
int[] arr = {1, 2, 3, 4};

How do I get another array that has the duplicated elements of the original array next to the original elements n number of times like so...

// n = 2
int[] arr2 = {1, 1, 2, 2, 3, 3, 4, 4};

// n = 3
int[] arr3 = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
Hat
  • 202
  • 1
  • 6

2 Answers2

4

You can use streams :)

int[] result = Arrays.stream(arr)
                .flatMap(x -> IntStream.range(0, n).map(e -> x))
                .toArray();

Because this looks like a homework requirement, you are not likely to be allowed to use streams, so here's a solution with for loops:

int[] result = new int[arr.length * n];
for (int i = 0 ; i < result.length ; i++) {
    result[i] = arr[i / n];
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • `.flatMap(x -> IntStream.range(0, n).map(e -> x))` may avoid the infinite stream + limit – ernest_k Dec 03 '19 at 07:17
  • 1
    Is there a reason why infinite stream + limit should be avoided though? Infinite stream + limit feels more natural to me at least. @ernest_k – Sweeper Dec 03 '19 at 07:22
  • This is beautiful. I wanted to post something looking nicer, but I give up :D – xenteros Dec 03 '19 at 07:30
  • @Sweeper - I probably still think like that. But I kinda started watching out after I saw this post some time back: [Quickly degrading stream throughput with chained operations?](https://stackoverflow.com/questions/52646345/quickly-degrading-stream-throughput-with-chained-operations) - sorry, took me some time to find that post... – ernest_k Dec 03 '19 at 07:51
0

If using loops is fine,

int origArr = {1,2,3,4};
int[] newArr = new int[n*origArr.length];    // default initialized with zero in Java

int i=0;    // loop over new array
int j=0;    // loop over original array
while(j<origArr.length){
  for(int k=0; k<n; k++){
    newArr[i] = origArr[j];
    i++;
  }
  j++;
}
PiNaKa30
  • 608
  • 7
  • 20