我有 100 条记录 [1 -> 100],我想在其中随机获取 50 条记录,在 java 中怎么做?谢谢。
问问题
810 次
4 回答
5
Set<T> set;
List<T> list = new ArrayList<T>(set);
Collections.shuffle(list);
List<T> random50 = list.subList(0, 50);
于 2012-11-04T10:56:48.313 回答
1
您可以获得 50 个随机值。
Random rand = new Random();
List<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < 50; i++)
ints.add(rand.nextInt(100)+1);
您可以使用 shuffle 以随机顺序获得 50 个唯一值。
List<Integer> ints = new ArrayList<Integer>();
for(int i = 1; i <= 100; i++)
ints.add(i);
Collections.shuffle(ints);
ints = ints.subList(0, 50);
于 2012-11-04T11:08:48.333 回答
0
生成四位长唯一代码的唯一可靠方法。
我发现首先声明 4 个整数变量,为它们分配 1 到 9 之间的随机数字。
然后我将这些整数转换为字符串,将它们连接在一起,使它们形成一个四位数的长字符串,然后我将生成的字符串转换为整数。
生成的四位随机整数存储在一个数组中。
“请注意!!我是 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);
}
}
于 2014-06-12T08:35:35.430 回答
0
fun generateCode(@IntRange(from = 1, to = 9) digits: Int, uniqueDigits: Boolean = false): String {
var number = 0
val numbersSet = mutableSetOf<Int>()
for (i in 1..digits) {
var x: Int
do {
x = Random.nextInt(9)
} while (uniqueDigits && numbersSet.contains(x))
numbersSet.add(x)
number += (10.0.pow((digits - i).toDouble()) * x).toInt()
}
return String.format("%0${digits}d", number)
}
这是允许生成长度为 1-9 的数字代码的 Kotlin 代码。用于uniqueDigits = true
使数字不重复。
于 2021-03-12T10:27:21.810 回答