Skip to content

Commit 6405faa

Browse files
committed
add methods to sum up the values in a dict, and return percentages for each
1 parent db0e2c0 commit 6405faa

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

core/src/processing/data/FloatDict.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,25 @@ public void swap(int a, int b) {
680680
}
681681

682682

683+
/**
684+
* Sum all of the values in this dictionary, then return a new FloatDict of
685+
* each key, divided by the total sum. The total for all values will be ~1.0.
686+
* @return a Dict with the original keys, mapped to their pct of the total
687+
*/
688+
public FloatDict getPercentages() {
689+
double sum = 0;
690+
for (float value : valueArray()) {
691+
sum += value;
692+
}
693+
FloatDict outgoing = new FloatDict();
694+
for (int i = 0; i < size(); i++) {
695+
double percent = value(i) / sum;
696+
outgoing.set(key(i), (float) percent);
697+
}
698+
return outgoing;
699+
}
700+
701+
683702
/** Returns a duplicate copy of this object. */
684703
public FloatDict copy() {
685704
FloatDict outgoing = new FloatDict(count);

core/src/processing/data/IntDict.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,25 @@ public void swap(int a, int b) {
621621
}
622622

623623

624+
/**
625+
* Sum all of the values in this dictionary, then return a new FloatDict of
626+
* each key, divided by the total sum. The total for all values will be ~1.0.
627+
* @return a Dict with the original keys, mapped to their pct of the total
628+
*/
629+
public FloatDict getPercentages() {
630+
double sum = 0;
631+
for (int value : valueArray()) {
632+
sum += value;
633+
}
634+
FloatDict outgoing = new FloatDict();
635+
for (int i = 0; i < size(); i++) {
636+
double percent = value(i) / sum;
637+
outgoing.set(key(i), (float) percent);
638+
}
639+
return outgoing;
640+
}
641+
642+
624643
/** Returns a duplicate copy of this object. */
625644
public IntDict copy() {
626645
IntDict outgoing = new IntDict(count);

0 commit comments

Comments
 (0)