how to avoid repetition and zero's with java random function? -


i have array contains 100 elements, want print out 20 random elements without repetition or having zeros.

i have printed random set of 20 numbers out of 1000 cannot stop printing out repetitions and/or zeros. help?!

here code :-

import java.util.random;   public class myclass {     public static void main(string args[]) {         int[] persons = new int[1000];         int[] person  = new int[20];         random random = new random();          (int = 0; < person.length; i++)         {             person[i] = random.nextint(persons.length);             system.out.println(person[i]);         }     } } 

how using hashset?

import java.util.hashset; import java.util.random; import java.util.set;  public class nonrepeatrandom {     public static void main(string[] args){         final int low = 1;         set<integer> set = new hashset<integer>();         random rand = new random();            while (set.size() < 20) {             set.add(rand.nextint(1000) + low); // set bound between 1 , 1000         }         system.out.println(set);     } } 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -