G3: random number according to their weigtht

return random number according to their weigtht


package careercup;

import java.util.ArrayList;
import java.util.Random;

// A:0.3 B:1 C:3 D:4
// A:0.3 B:1.3 C:4.3 D:8.3

public class test2 {
	static ArrayList<Pair> list;
	
	public static void main(String[] args) {
		Pair p1 = new Pair('A', 0.3);
		Pair p2 = new Pair('B', 1);
		Pair p3 = new Pair('C', 3);
		Pair p4 = new Pair('D', 4);
		
		ArrayList<Pair> arr = new ArrayList<Pair>();
		arr.add(p1);
		arr.add(p2);
		arr.add(p3);
		arr.add(p4);
		preprocess(arr);
		char c = getRandom();
		System.out.println(c);
	}
	
	private static void preprocess(ArrayList<Pair> list){
		test2.list = list;
		for(int i=1; i<list.size(); i++) {
			list.get(i).d += list.get(i-1).d;
		}
		return;
	}
	
	public static char getRandom() {
		Random r = new Random();
		double p = r.nextDouble() * list.get(list.size()-1).d;  // [0,8.3)
		System.out.println(p);
		return binarySearch(list, p);
	}
	
	private static char binarySearch(ArrayList<Pair> list, double p) {
		int low = 0; 
		int high = list.size()-1;
		while(low<=high){
			int mid = low + (high-low)/2;
			if(list.get(mid).d == p) {
				return list.get(mid).c;
			} else if(list.get(mid).d < p ){
				low = mid + 1;
			} else {
				high = mid -1; 
			}
		}
		return list.get(low).c; 
	}
}


class Pair{
	char c;
	double d;
	
	Pair(char c, double d){
		this.c = c;
		this.d = d;
	}
}


你可能感兴趣的:(G3: random number according to their weigtht)