View Javadoc
1   /**
2    * Copyright (c) 2009, The JUNG Authors 
3    *
4    * All rights reserved.
5    *
6    * This software is open-source under the BSD license; see either
7    * "license.txt" or
8    * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
9    * Created on Jan 13, 2009
10   * 
11   */
12  package edu.uci.ics.jung.algorithms.util;
13  
14  import java.util.HashMap;
15  import java.util.Map;
16  
17  import junit.framework.TestCase;
18  
19  /**
20   * @author jrtom
21   *
22   */
23  public class TestWeightedChoice extends TestCase 
24  {
25  	private WeightedChoice<String> weighted_choice;
26  	private Map<String, Double> item_weights = new HashMap<String, Double>();
27  	private Map<String, Integer> item_counts = new HashMap<String, Integer>();
28  	
29  	@Override
30      public void tearDown()
31  	{
32  		item_weights.clear();
33  		item_counts.clear();
34  	}
35  
36  	private void initializeWeights(double[] weights)
37  	{
38  		item_weights.put("a", weights[0]);
39  		item_weights.put("b", weights[1]);
40  		item_weights.put("c", weights[2]);
41  		item_weights.put("d", weights[3]);
42  		
43  		for (String key : item_weights.keySet())
44  			item_counts.put(key, 0);
45  
46  	}
47  
48  	private void runWeightedChoice()
49  	{
50  		weighted_choice = new WeightedChoice<String>(item_weights, new NotRandom(100));
51  		
52  		int max_iterations = 10000;
53  		for (int i = 0; i < max_iterations; i++)
54  		{
55  			String item = weighted_choice.nextItem();
56  			int count = item_counts.get(item);
57  			item_counts.put(item, count+1);
58  		}
59  		
60  		for (String key : item_weights.keySet())
61  			assertEquals((int)(item_weights.get(key) * max_iterations), 
62  						item_counts.get(key).intValue());
63  	}
64  	
65  	public void testUniform() 
66  	{
67  		initializeWeights(new double[]{0.25, 0.25, 0.25, 0.25});
68  		
69  		runWeightedChoice();
70  	}
71  	
72  	public void testNonUniform()
73  	{
74  		initializeWeights(new double[]{0.45, 0.10, 0.13, 0.32});
75  		
76  		runWeightedChoice();
77  	}
78  }