M. Aktas
M. Aktas

Reputation: 131

Java How to copying larger array to the small array?

I want to copy a larger array that some elements randomly removed by remove() method into the a small array.

I have used System.arraycopy() but this method copies elements respectively. Therefore some elements in the larger array don't be copied.

I want to copy the larger array's all non-removed elements into small array which has the length is equal to number of non-removed elements in larger array.

Upvotes: 1

Views: 3281

Answers (2)

GhostCat
GhostCat

Reputation: 140525

In case you are allowed to use other "system libraries", the solution is super-simple:

  • Shuffle the large array (or a copy of it; if you have to preserve the large array as is)
  • use arraycopy() and copy smaller.length elements from larger to smaller

The point is: when you shuffle the large array, you put it into random order!

But in case you are not allowed to use "system" libraries; you "shuffle" yourself:

  • iterate larger; and for each iteration, compute a random int within larger.length
  • swap the element of the current iteration with that randomly selected index

Afterwards, you can again use arraycopy.

Upvotes: 1

noobcoder
noobcoder

Reputation: 343

import java.util.concurrent.ThreadLocalRandom;  //for shuffling array
import java.util.Random;                        //for shuffling solution

public class BigToSmallArray    {
    public static void main(String[] args)  {
        int[] bigArray = new int[]{0,1,2,3,4,5,6,7,8,9};
        int[] smallArray = new int[5];
        int[] shuffledBigArray = shuffleArray(bigArray);
        for(int i = 0; i < smallArray.length; i++)  {
            smallArray[i] = shuffledBigArray[i];
        }
    }

    public static int[] shuffleArray(int arr[])   {
        Random rnd = ThreadLocalRandom.current();
        for (int i = arr.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            int a = arr[index];
            arr[index] = arr[i];
            arr[i] = a;
        }
        return arr;
    }
}

Upvotes: 0

Related Questions