I'm trying to randomly select 100 values from an array of 1000.
How do I do this?

Also, after selection, how can I add these 100 values into a new array.

Do I need to do something like this with a loop?

for (x = 0; x < 100; x++){
    smallArray = smallArray + (value1);
};

Thanks!

Dani AI

Generated

Nice thread. Two quick clarifications to help future readers: (1) use the list’s size, not a hard-coded bound, when generating indices; that prevents out-of-bounds if the list size changes. (2) Type your collections (e.g., List<Integer>) so you do not have to cast. is right that picking by random index can repeat the same position; if you want each element at most once, sample without replacement.

Option A: shuffle indices and take the first 100 (does not modify the original list).

// unsorted is a List<Integer> of size 1000
List<Integer> indices = IntStream.range(0, unsorted.size())
                                 .boxed()
                                 .collect(Collectors.toList());
Collections.shuffle(indices, ThreadLocalRandom.current());

int[] sample = indices.stream()
                      .limit(100)
                      .mapToInt(unsorted::get) // picks unique positions
                      .toArray();

Option B: reservoir sampling, which gives a uniform 100-of-N sample in one pass and O(100) extra space. Useful for large inputs or streams.

int k = 100;
int[] sample = new int[k];
Random rnd = ThreadLocalRandom.current();

for (int i = 0; i < k; i++) sample[i] = unsorted.get(i);
for (int i = k; i < unsorted.size(); i++) {
    int j = rnd.nextInt(i + 1);
    if (j < k) sample[j] = unsorted.get(i);
}

Notes:

  • If the source list contains duplicate values, both approaches can still produce duplicates in the sample because they guarantee unique positions, not unique values. To enforce unique values, deduplicate first (e.g., put into a LinkedHashSet<Integer>), then sample.
  • Repeatedly calling remove on an ArrayList works but is O(n) per removal and mutates the list; shuffling indices or reservoir sampling avoids that cost and side effect.

Recommended Answers

All 14 Replies

I'll give you a c++ equivalent :

for(i=0;i<100;i++){
array100[i]= array1000[random(1000)];
}

All you need now is to find an equivalent random function in java ;)

I hope that's help for you:

for(i=0;i<100;i++){
   
          array100[i]= array1000[(int)(Math.random()*1000)];
   
      }

Sorry for english... I am Hungarian

You can also use Random.nextInt(int) for the random int.

Keep in mind that the suggestions tendered so far will allow the chance that an element is selected multiple times. If you don't want that to be possible then you'll need to put additional measures in place to prevent it.

You can also use Random.nextInt(int) for the random int.

Keep in mind that the suggestions tendered so far will allow the chance that an element is selected multiple times. If you don't want that to be possible then you'll need to put additional measures in place to prevent it.

Thanks for the help thusfar.

I'm a little confused.

for(int i=0;i<100;i++){
        keys_Array = random.nextInt(unsorted);
    }

keys_Array is size 100, and I want to have it select 100 elements from unsorted an arraylist filled with 1000 elements.

What do I need to change from this? I'm not so worried about multiple elements at the moment.

for(int i=0;i<100;i++){
        keys_Array[i] = unsorted.get( random.nextInt(100) );
    }

Note that get() is used if 'unsorted' is an arraylist and not an array.

for(int i=0;i<100;i++){
        keys_Array[i] = unsorted.get( random.nextInt(100) );
    }

Note that get() is used if 'unsorted' is an arraylist and not an array.

Thank you.
I changed to .get, says I have incompatible types.
Says found .Object, requires Int

Could you point out where I went wrong in this?
Appreciate it.

import java.util.*;

public class Lab5 {

    public static void main(String[] args) {
        Random random = new Random();
        ArrayList unsorted = new ArrayList(),
               sorted = new ArrayList();
        
        int[] keys_Array = new int[100];

        for(int count = 0; count < 1000; count++){
            int rand = random.nextInt(10000)+1;
            System.out.println(rand);

            unsorted.add(rand);
            sorted.add(rand);

        }
//    System.out.print("\n\nSize: " + unsorted.size());
 //   System.out.print("\n");
  //  System.out.print("Contents:" + unsorted);
        
        for(int i=0;i<100;i++){
            keys_Array[i] = unsorted.get(random.nextInt(100));
        }
    }
}

You have to cast the Object to Integer if you want to assign it to the array.

keys_Array[i] = (Integer)unsorted.get(random.nextInt(100));

Using generics to type your collections would avoid that.

Thanks a bunch!

If you don't want repeat selections, you can use this instead

keys_Array[i] = (Integer) unsorted.remove( random.nextInt(unsorted.size()) );

Can you explain the difference in that one? If I use it I would kind of like to know how it works.

It's actually removing the element from "unsorted". It grabs an element randomly between 0 and size()-1.

Alright, thats awesome. It can still get a repeat value though, based on what the first array contains right?

If "unsorted" contains any duplicates, yes. It just can't retrieve the same element from "unsorted" more than once. The first version could use unsorted.get(4) multiple times if 4 came up as the random number more than once.

Thanks for explaining in depth.
I understand this concept now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.