'How to code for generate multiple sets of random number?
How to code if the sets of random numbers can be indicated by users? I am now having java program for generating one set of random numbers, I want to add the function that I can indicate how many sets of random numbers generated. How can I do? Please help.
int[] numberSet = new int[6];
int randomNumber;
boolean duplicate;
//input
//processing
for (int i=0; i<numberSet.length; i++){
duplicate = false;
randomNumber = generateRandomValue();
//output
System.out.println("The numbers for the set : ");
for (int i=0; i<numberSet.length; i++){
if(i==(numberSet.length-1)){
System.out.print( numberSet[i]);
}
else{
System.out.print( numberSet[i] + ", ");
}
}
System.out.println("");
}
public static int generateRandomValue(){
return (int) (Math.random()*49) + 1 ;
}
Solution 1:[1]
You could do some thing like this :
public static int[] generateRandomValueSet(int n){
Set<Integer> set = new HashSet();
while(set.size() < n ){
set.add( (int) (Math.random()*49) + 1);
}
int[] arr = new int[n];
int index = 0;
for(Integer x :set ){
arr[index++] = x;
}
return arr;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rvp |
