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);
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));
}
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
}
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. Ie, 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);
}
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));
}
One more solution based on Streams:
final Random random = new Random();
final Set<Integer> set = IntStream.generate(() -> random.nextInt(100) + 1)
.limit(10)
.boxed()
.collect(Collectors.toSet());
You can achieve this with one line using IntStream
:
Set<Integer> hash = new Random().ints(1, 101).distinct().limit(10)
.boxed().collect(Collectors.toSet());
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.