Home > OS >  how do I generate random numbers then add to a set in Java?
how do I generate random numbers then add to a set in Java?

Time:12-05

I want to make an empty set, then add N- many random numbers between 1 and 100 to a set. I used count to be up to 10 but I'm not sure if that is correct. I also am not sure how to add the generated numbers to the HashSet.

    //generates random birthdays
    Random coins = new Random();
    int number;

    for (int count = 1; count <= 10; count  ){
        number = 1 coins.nextInt(100);
    }
      HashSet<Integer> hash = new HashSet<Integer>();
      hash.add(number);

CodePudding user response:

You need to add the element inside the loop, to do it 10 times

Random coins = new Random();
HashSet<Integer> hash = new HashSet<>();
for (int count = 1; count <= 10; count  ) {
    hash.add(1   coins.nextInt(100));
}
System.out.println(hash); // [50, 23, 72, 9, 89, 10, 76, 13, 47]

Note that is a number is generated twice, you'll end up with 9 values as Set doesn't allow duplicate, to ensure a 10 item set, use a while loop

while (hash.size() != 10) {
    hash.add(1   coins.nextInt(100));
}

CodePudding user response:

Try this.

//generates random birthdays
Random coins = new Random();
int number;
HashSet<Integer> hash = new HashSet<Integer>();
for (int count = 1; count <= 10; count  ){
    number = 1 coins.nextInt(100);
    hash.add(number);           //Adds the number to set
}
  
 

CodePudding user response:

You have the right idea, but you need to add the generated random number(s) to the set inside the loop, not after it:

Set<Integer> set = new HashSet<>();
for (int count = 1; count <= 10; count  ) {
    number = 1   coins.nextInt(100);
    hash.add(number);
}

Note, however, there is a chance that you generate one or more identical random numbers, meaning the eventual set will have less than ten elements.

EDIT:
To answer the question in the comments, with such a small set, one way to make sure you have ten distinct random numbers is to continue looping until you get that restul. I.e., use a while condition and check the set's size explicitly:

Set<Integer> set = new HashSet<>();
while (set.size() < 10) {
    number = 1   coins.nextInt(100);
    hash.add(number);
}

CodePudding user response:

You can use some simple code like this to add 10 random numbers between 1 and 100 to a hashset.

    Set<Integer> randSet = new HashSet<>();

    while(randSet.size() != 10) {
        randSet.add((int) Math.round(1   Math.random() * 99));
    }
  • Related