Created
May 30, 2013 20:15
-
-
Save mkayman/5680796 to your computer and use it in GitHub Desktop.
weighted-random-selection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mkayman; | |
import java.util.Arrays; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) { | |
List<Item> items = Arrays.asList(new Item("item1", 40), new Item( | |
"item2", 10), new Item("item3", 10), new Item("item4", 10), | |
new Item("item5", 30)); | |
double totalWeight = 0.0d; | |
for (Item item : items) { | |
totalWeight += item.weight; | |
} | |
for (int i = 1; i <= 10000; i++) { | |
double random = Math.random() * totalWeight; | |
for (Item item : items) { | |
random -= item.weight; | |
if (random <= 0.0d) { | |
sum(item.name); | |
break; | |
} | |
} | |
} | |
System.out.println("item1: " + item1); | |
System.out.println("item2: " + item2); | |
System.out.println("item3: " + item3); | |
System.out.println("item4: " + item4); | |
System.out.println("item5: " + item5); | |
} | |
static int item1, item2, item3, item4, item5; | |
static void sum(String name) { | |
if (name == "item1") item1++; | |
else if (name == "item2") item2++; | |
else if (name == "item3") item3++; | |
else if (name == "item4") item4++; | |
else if (name == "item5") item5++; | |
} | |
static class Item { | |
public String name; | |
public double weight; | |
public Item(String name, double weight) { | |
this.name = name; | |
this.weight = weight; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment