-2

I wrote a program that generates twenty random numbers. the chance of repeating the program is about 1/3. How can I rebuild my program? could anyone help me?

        for (int i = 0; i <= 19; i++) {
            rand[i] = (int) (Math.random() * 60 + 1);
        }
        for(int i=0;i<=19;i++)
        {
            rand_back[i]=rand[i];
        }

        for (int i = 0; i<=19;) {
            for(int j=0;j<=19;j++) {
                //porównaj czy wsytapiła juz taka sama liczba
                if((rand[i]==rand_back[j])&&(j!=i)) {
                    rand[j]=(int) (Math.random()*60+1);
                }
                if(j==19){
                    j=0;
                    i++;
                }
                if(i==19) {
                    break;
                }
            }
            if(i==19) {
                break;
            }
        }
  • 3
    Possible duplicate of [Creating random numbers with no duplicates](https://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates) – KevinO Apr 01 '19 at 14:13
  • `Random r = new Random(); List randomNumbers = IntStream.range(1, 60).boxed().sorted((i, j) -> r.nextInt()).collect(Collectors.toList()).subList(0, 20);` – Arnaud Denoyelle Apr 01 '19 at 14:15
  • You have 2 options : 1) the most generic : use a while loop and check on each iteration that the generated random number had not been already added. 2) generate a sequence of all elligible numbers then shuffle it. – Arnaud Denoyelle Apr 01 '19 at 14:17

1 Answers1

1
Set<Integer> ds = new LinkedHashSet<>();


System.out.println("step-1");

for( int i=0; i<10; i++ )
    ds.add( i );

ds.add( (int) (7d) );
ds.add( (int) (7d) );
ds.add( (int) (17d) );

ds.forEach(System.out::println);


System.out.println("step-2");

while (ds.size() < 20)
    ds.add( (int) (Math.random()*100) );

System.out.println("Size: " + ds.size());
ds.forEach(System.out::println);

No duplicate for 7 or any other int. If you have to generate a second array, just add 20 more positions with the while-loop and take the last 20 items of the list.

SvenJu
  • 31
  • 1
  • 5
  • No duplicates, but you don't know howmany numbers you get. Also, the example is not relevant with doubles (which should be considered as unique) – Arnaud Denoyelle Apr 01 '19 at 14:21
  • The answer could be improved by modifying the `for` condition : `i < 10` could be `ds.size() < 10`. Also, the order is not preserved with a `HashSet`, you should use another implementation, such as `LinkedHashSet`. – Arnaud Denoyelle Apr 01 '19 at 14:23
  • Trying to write the first answer and to have a good code is quite a challange. thx for ur suggestions @ArnaudDenoyelle – SvenJu Apr 01 '19 at 14:41