All pastes #931376 Raw Edit

Something

public java v1 · immutable
·published 2008-03-07 03:25 UTC
rendered paste body
public class WeightedItemSelector {	private class Item {		public Object thing;		public int weight;		public int lowerBound;		public int upperBound;				public Item(Object thing, int weight, int lowerBound, int upperBound) {			this.thing = thing;			this.weight = weight;			this.lowerBound = lowerBound;			this.upperBound = upperBound;		}		public boolean inRange(int num) {			return num < upperBound && num > lowerBound;		}	}		private ArrayList<Item> items = new ArrayList<Item>();	private int totalWeight = 0;		public void addItem(Object thing, int weight) {		items.add(new Item(thing, weight, totalWeight, totalWeight+weight));		totalWeight += weight;	}		// Since we always want to use the stored seed, just pass in your Random object.	public Object getRandomItem(Random rand) {		int randChoice = rand.nextInt(totalWeight);		for(Item item: items) {			if (item.inRange(randChoice))				return item.thing;		}		return null; // if there are no items	}}