简体   繁体   中英

How am I supposed to write over an array given the number of times it has to be copied in Java

I am supposed to "multiply" an array for given number of times, using the int copy variable. However, I am stuck on "writing over the array" as arrays can not be modified, and copying the array a given amount of times. Clearer instructions can be found below. Thanks! :)

int[] arrayMultiplier(int[] arr, int copies)
This method should return an array generated by writing the array arr
several (copies) times in a row.
For example if the array nums = [3, 5, 6]:
arrayMultiplier(nums, 3)
would return the array [3, 5, 6, 3, 5, 6, 3, 5, 6]

I should clarify that I found two other posts on how to do this, but they used C++ and Javascript instead of Java

Try creating the array you want to return from the multiplier

int[] multiplied = new int[arr.length * copies];

Then loop through the new array and populate it.

for(int i = 0;i<=multiplied.length-1;i++){
   multiplied[i] = arr[i%copies];
}

You could use an ArrayList then convert it into an array when you return it. Probably not the most efficient answer, but it works.

public int[] arrayMultiplier(int[] arr, int copies) {
    ArrayList<Integer> temp = new ArrayList<Integer>();
    for(int i = 0; i < copies; i++) {
        for(int j = 0; j < arr.length; j++) {
            temp.add(arr[j]);
        }
    }
    return temp.stream().mapToInt(i->i).toArray();
}

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