简体   繁体   中英

Creating an array that has duplicated elements of an original array without using ArrayList?

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};

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];
}

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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM