From 0f92ad1c941bd6ca6e8759824e4c38198a3c810d Mon Sep 17 00:00:00 2001 From: Ben Fry Date: Wed, 24 Jul 2013 10:53:21 -0400 Subject: [PATCH] add methods to sum up the values in a dict, and return percentages for each --- core/src/processing/data/FloatDict.java | 19 +++++++++++++++++++ core/src/processing/data/IntDict.java | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/core/src/processing/data/FloatDict.java b/core/src/processing/data/FloatDict.java index 7207a179a..e725d4806 100644 --- a/core/src/processing/data/FloatDict.java +++ b/core/src/processing/data/FloatDict.java @@ -680,6 +680,25 @@ public class FloatDict { } + /** + * 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 (float 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 FloatDict copy() { FloatDict outgoing = new FloatDict(count); diff --git a/core/src/processing/data/IntDict.java b/core/src/processing/data/IntDict.java index 23e4fc48f..d812d76d0 100644 --- a/core/src/processing/data/IntDict.java +++ b/core/src/processing/data/IntDict.java @@ -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);