View Javadoc

1   /*
2    * Copyright (C) 2010 Unreal Visualizer Authors
3    *
4    * This program is free software: you can redistribute it and/or modify
5    * it under the terms of the GNU General Public License as published by
6    * the Free Software Foundation, either version 3 of the License, or
7    * (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU General Public License
15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16   */
17  package nl.tudelft.goal.ut2004.visualizer.util;
18  
19  import java.util.ArrayList;
20  import java.util.Collections;
21  import java.util.HashMap;
22  
23  /**
24   * Utility object that allows scores from players to be sorted in descending
25   * order.
26   * 
27   * @author Lennard de Rijk
28   *
29   */
30  public class Score implements Comparable<Score>{
31  
32  	private final int id;
33  	private final double score;
34  
35  	public Score(int id, double score){
36  		this.id = id;
37  		this.score = score;
38  	}
39  
40  	/**
41  	 * {@inheritDoc}
42  	 * Default order is descending.
43  	 */
44  	@Override
45  	public int compareTo(Score o) {
46  		double diff =  o.score - this.score;
47  
48  		if(diff > 0){
49  			return 1;
50  		}else if(diff < 0)
51  		{
52  			return -1;
53  		}else{
54  			return 0;
55  		}
56  	}
57  
58  	/**
59  	 * @return the ID from the player who has this score
60  	 */
61  	public int getId() {
62  		return id;
63  	}
64  
65  	/**
66  	 * @return the score
67  	 */
68  	public double getScore() {
69  		return score;
70  	}
71  
72  	/**
73  	 * Returns an ordered lists of {@link Score} objects that is constructed
74  	 * from the given {@link HashMap}.
75  	 * @param scoreMap The {@link HashMap} that maps UnrealIDs to a score
76  	 * @return An {@link ArrayList} of {@link Score} in descending order
77  	 */
78  	public static ArrayList<Score> getOrderedScoresFor(
79  			HashMap<Integer, Double> scoreMap){
80  
81  		ArrayList<Score> scores = new ArrayList<Score>(scoreMap.size());
82  
83  		// For each entry create a new Score object
84  		for (Integer id : scoreMap.keySet()) {
85  			double s = scoreMap.get(id);
86  			Score score = new Score(id, s);
87  			scores.add(score);
88  		}
89  
90  		// Sort and return
91  		Collections.sort(scores);
92  		return scores;
93  	}
94  
95  }