Skip to content

Instantly share code, notes, and snippets.

@matnogaj
Last active February 7, 2017 11:59
Show Gist options
  • Save matnogaj/e455520feb003f8512e2857596e2748f to your computer and use it in GitHub Desktop.
Save matnogaj/e455520feb003f8512e2857596e2748f to your computer and use it in GitHub Desktop.
Calculate percentage distribution of values
func calculatePercentageDistribution(ofValues inputValues: [Double]) -> [Double] {
let totalValue = inputValues.reduce(0.0) { $0.0 + $0.1 }
guard totalValue > 0 else {
return Array<Double>(repeating: 0.0, count: inputValues.count)
}
var fractionSum: Double = 0.0
var percentArray = inputValues.map { value -> Double in
let value = (value * 100.0) / totalValue
let roundedValue = round(value)
fractionSum += (value - roundedValue)
return roundedValue / 100.0
}
// Find an index of the last positive value to adjust it.
var lastPositiveValueIndex = percentArray.count - 1
while lastPositiveValueIndex > 0, !(percentArray[lastPositiveValueIndex] > 0.0) {
lastPositiveValueIndex -= 1
}
// This adjustment is for the greater good. The last percent value will be incorrect (at max by 0.9999%).
// But the sum of all array values will be 100% which is nice.
percentArray[lastPositiveValueIndex] = percentArray[lastPositiveValueIndex] + round(fractionSum)/100.0
return percentArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment