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};
2
  • 1
    Please add your solution so far Commented Dec 3, 2019 at 5:46
  • Also, do you require a primitive integer array input/output, or would Integer[] also be acceptable? Commented Dec 3, 2019 at 5:48

2 Answers 2

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];
}
Sign up to request clarification or add additional context in comments.

4 Comments

.flatMap(x -> IntStream.range(0, n).map(e -> x)) may avoid the infinite stream + limit
Is there a reason why infinite stream + limit should be avoided though? Infinite stream + limit feels more natural to me at least. @ernest_k
This is beautiful. I wanted to post something looking nicer, but I give up :D
@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? - sorry, took me some time to find that post...
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++;
}

3 Comments

You should follow the Java Naming Conventions: variabele names are always written in camelCase.
Yeah sorry, i have a C++ background. Updated, thanks !
This looks better :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.