本文目錄一覽:
求一段JAVA的概率算法
public class Zhuq {
public static void main(String[] args) {
ListPerson listP=new ArrayListPerson();
listP.add(new Person(“小李”, “1”, 200));
listP.add(new Person(“小王”, “2”, 210));
listP.add(new Person(“小趙”, “3”, 230));
listP.add(new Person(“小孫”, “4”, 100));
listP.add(new Person(“小錢”, “5”, 3));
listP.sort(new ComparatorPerson() {
@Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return (((Person)o1).count)*(Math.random()*10+1)(((Person)o2).count)*(Math.random()*10+1)?-1:1;
}
});
System.out.println(listP);
}
}
class Person {
String personName;
String id;
int count;
public Person(String personName, String id, int count) {
super();
this.personName = personName;
this.id = id;
this.count = count;
}
@Override
public String toString() {
return “Person [personName=” + personName + “, id=” + id + “, count=” + count + “]”;
}
}
//本質還是隨機數
java程序中概率問題
用概率模型,先隨機一次看取用哪個概率,隨後再隨機一次。代碼示例如下: import java.util.Random;public class HelloWorld { public static void main(String[] args) { Random random = new Random(); double p1=0.7; //1~4的概率 double p=(…
java中如何讓A的輸出的概率為50%B輸出的概率為30%C輸出的概率為20%
public class Test {
public static void main(String[] args) {
double d = Math.random();//生成一個0~1的隨機數
if(d=0.5){
System.out.println(“A”);//50%概率
}else if(d=0.8){
System.out.println(“B”);//30%概率
}else{
System.out.println(“C”);//20%概率
}
}
}
java中概率的問題
你的問題描述不清。
如果是別的數字是均等的,那把一個單獨處理,別的數字分享17/20的概率。實際上是一個映射的問題。具體實現就是拿20個數字做random,然後取整,比如1-1,2、3-2,若是其它,則重新獲取一個3的random,當然要把1和2給去掉
——————————————
那不就更容易了,剩下的不需要重新獲取random了,直接就是3
————————————————————————
public static void main(String arg[]) {
System.out.println(getInt());
}
private static long getInt() {
long a = Math.round(Math.random() * 20);
if (a == 0 || a == 1) {
return 1;
} else if (a == 2) {
return 2;
} else {
return 3;
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/151311.html