How to get random range number in set

2019-02-26 04:22发布

问题:

I have 100 record [1 -> 100], i want get random 50 record in this, how to do in java? Thanks.

回答1:

Set<T> set;

List<T> list = new ArrayList<T>(set);
Collections.shuffle(list);
List<T> random50 = list.subList(0, 50);


回答2:

You can get 50 random values.

Random rand = new Random();

List<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < 50; i++)
    ints.add(rand.nextInt(100)+1);

You can get 50 unique values in a random order using shuffle.

List<Integer> ints = new ArrayList<Integer>();
for(int i = 1; i <= 100; i++)
    ints.add(i);
Collections.shuffle(ints);
ints = ints.subList(0, 50);


回答3:

The only sure way to generate a four digit long unique code.

I found was to first declare 4 integer variables, assign them random digits between 1 and 9 each.

I then convert these integers into strings, join them together so that they form into a four digit long string and then I convert the resulting string into an integer.

The resulting four digit random integer is stored in an array.

"Please note!! that I am new to java"

import javax.swing.JOptionPane;
public class Rund4gen {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
   // I begin by creating an array to store all my numbers
   String userInput = JOptionPane.showInputDialog("How many 4 digit long numbers would you like to generate?");
   int input = Integer.parseInt(userInput);
   // Now lets convert user input to a string
   int[] passCode = new int[input];
   // We need to loop as many time as the user specified
   for(int i = 0; i < input; i++){
       // Here I declare my integer variables
       int one, two, three, four;
       // For each of the integer variable I assign a rundom number
       one = (int)Math.floor((Math.random()*9)+1);
       two = (int)Math.floor((Math.random()*9)+1);
       three = (int)Math.floor((Math.random()*9)+1);
       four = (int)Math.floor((Math.random()*9)+1);
       // I need to convert my digits into a string in order to join them
       String n1 = String.valueOf(one);
       String n2 = String.valueOf(two);
       String n3 = String.valueOf(three);
       String n4 = String.valueOf(four);
       // Once conversion is complete then I join them as follows
       String nV = n1+n2+n3+n4;
       // Once joined, I then need to convert the joined result into an integer
       int nF = Integer.parseInt(nV);
       // I then store the result in an array as follows
       passCode[i] = nF;
   }
   // Now I need to print each value in the array
   for(int c = 0; c < passCode.length; c++){
       System.out.print(passCode[c]+"\n");
   }
   // Finally I thank the user for participating or not
   //JOptionPane.showMessageDialog(null,"Thank you for participating");
   System.exit(0);
}

}



标签: java random