如何在特定范围内生成随机int值?
以下方法存在与整数溢出相关的错误:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
使用Java 8 IntStream和Collections.shuffle的不同方法
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
IntStream range = IntStream.rangeClosed(5,10);
ArrayList<Integer> ls = new ArrayList<Integer>();
//populate the ArrayList
range.forEach(i -> ls.add(new Integer(i)) );
//perform a random shuffle using the Collections Fisher-Yates shuffle
Collections.shuffle(ls);
System.out.println(ls);
}
}
Scala中的等价项
import scala.util.Random
object RandomRange extends App{
val x = Random.shuffle(5 to 10)
println(x)
}