Home > Back-end >  Size of the loop is printing less numbers than i want to be in my Set JAVA
Size of the loop is printing less numbers than i want to be in my Set JAVA

Time:08-19

Basically i want to generate random numbers between 1-10, which are put into my set. The thing is that my loop size is from 0 to 9 and it generates random numbers but, once it's 5 numbers, once 7 numbers, once 3 numbers and not exactly 9 numbers. Why?

private static Set<Integer> losowanie() {
   
    Set<Integer> result = new TreeSet<>();
    Random random = new Random();

    for (int i = 0; i < 10; i  ){
        result.add(random.nextInt(10)   1);
    }
    return result;

    }
}

also i was doing the same thing with while loop and it does the same.

CodePudding user response:

Because Set collections cannot have duplicate properties, that is, when you generate numbers, if the same number is generated in the random number, your Set can only hold a unique number.

public static void main(String[] args) {
        Set<Integer> result=new TreeSet<>();
        for (int i = 0; i < 10; i  ) {
            result.add(1);
        }
        //only one data: [1]
        System.out.println(result);
        result=new TreeSet<>();
        for (int i = 0; i <10 ; i  ) {
            result.add(i);
        }
        //ten data:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        System.out.println(result);

    }

CodePudding user response:

First of all, your loop indexes from 0 to 9, and that's ten iterations.

So, you might expect ten numbers in your set. But set elements have to be unique, and you are inserting elements randomly selected from a set of only ten possibilities.

The chances of that happening are 10! ÷ 1010 or about 0.036%. Keep running your program.

If your goal is to have ten different numbers in a random order, do this instead:

List<Integer> result = IntStream.rangeClosed(1, 10)
    .boxed()
    .collect(Collectors.toList());
Collections.shuffle(random);

CodePudding user response:

Can you also post your results also. It would be easy to work on. Also, for loop and while loop do have the same conditions- works untill the condition is not satisfied.

  • Related