add methods to sum up the values in a dict, and return percentages for each

This commit is contained in:
Ben Fry
2013-07-24 10:53:21 -04:00
parent 3fc5a78825
commit 0f92ad1c94
2 changed files with 38 additions and 0 deletions

View File

@@ -621,6 +621,25 @@ public class IntDict {
}
/**
* Sum all of the values in this dictionary, then return a new FloatDict of
* each key, divided by the total sum. The total for all values will be ~1.0.
* @return a Dict with the original keys, mapped to their pct of the total
*/
public FloatDict getPercentages() {
double sum = 0;
for (int value : valueArray()) {
sum += value;
}
FloatDict outgoing = new FloatDict();
for (int i = 0; i < size(); i++) {
double percent = value(i) / sum;
outgoing.set(key(i), (float) percent);
}
return outgoing;
}
/** Returns a duplicate copy of this object. */
public IntDict copy() {
IntDict outgoing = new IntDict(count);