基于Java的轮盘赌随机数(或者说权重随机数)的实现

首先,轮盘赌这种东西,大家应该不陌生吧。实在不清楚,可以百度。

简要说来,一个随机产生的数字,为我们指定了轮盘中的某一个扇区。或者说,这个随机数指示出了相应的权重范围所对应的数字。

很拗口?那就来举个例子吧:

假设,我们有个字符串数组:

String[] a = {"A", "B", "C", "D"};
同时,我们给这个数组中的每一个元素设定一个权重,也有的说出现的概率等。总之,下面这组数字是上面的字符串数组的权重因子:

int[] b = {10, 20, 30, 40};
我们就按出现概率来理解吧。那么,上面的意思就是:

A的概率:10%
B的概率:20%
C的概率:30%
D的概率:40%
需要说明的是,这不是说你随机得到的概率是上面说的那么多。你也可以把他们仅仅理解成:10, 20, 30, 40

接下来,重要的部分来了:

在轮盘赌的算法中,判定一个数字或者说对象是否符合条件的计算是:

当前给定的随机数,必须小于等于该随机数所对应的权重数组的值以及它前面所有值的累加。
好拗口啊!

randomNum <= sum(weightage[0]+...+weightage[currentPosition])
还是上代码吧:

package com.homeland.myapp;

import java.util.Random;


public class Roulette {

	public static void main(String[] args) {
		Random r = new Random();
		for (int i = 0; i < 10; i++) {
			int n = r.nextInt(100);
			RouletteDice rd = new RouletteDice(n);
			Thread t = new Thread(rd);
			t.start();
		}
	}
}

class RouletteDice implements Runnable {
	static String[] a = {"A", "B", "C", "D"};
	static int[] b = {10, 20, 30, 40};
	int randomNum;
	public RouletteDice(int randomNum) {
		this.randomNum = randomNum;
	}
	
	private static synchronized void printNum(int randomNum) {
		// define range
		// 0~10 11~30 31~60 61~100
		System.out.println("The random number is: " + randomNum);
		int sum = 0;
		for (int i = 0; i < b.length; i++) {
			sum += b[i];
			if (randomNum <= sum) {
				System.out.println("Your dice point to: " + a[i]);
				break;
			}
		}
		System.out.println("----------------------------------------------");
	}
	
	@Override
	public void run() {
		printNum(randomNum);
	}
	
}
得到如下类似的结果:

The random number is: 35
Your dice point to: C
----------------------------------------------
The random number is: 12
Your dice point to: B
----------------------------------------------
The random number is: 94
Your dice point to: D
----------------------------------------------
The random number is: 87
Your dice point to: D
----------------------------------------------
The random number is: 16
Your dice point to: B
----------------------------------------------
The random number is: 74
Your dice point to: D
----------------------------------------------
The random number is: 52
Your dice point to: C
----------------------------------------------
The random number is: 10
Your dice point to: A
----------------------------------------------
The random number is: 42
Your dice point to: C
----------------------------------------------
The random number is: 56
Your dice point to: C
----------------------------------------------



你可能感兴趣的:(多线程,Java,算法,Java技术)