SashaZ SashaZ - 4 months ago 17
Swift Question

Swift: number of occurrences of element in Array as a percentage?

I have a varying array that I want to find the number of occurrences of an element but expressed as a percentage for example:

var filteredArray = [1,2,4,5,2,1,2,1,5,5]

var counts:[Int: Int] = [:]

for item in zeroRemovedArray2 {
counts[item] = (counts[item] ?? 0) + 1
}


This gives the occurrences [1:3, 2:3, 3:0, 4:1, 5:3]
but I want to have a dictionary of [1:0.3, 2:0.3, 3:0, 4:0.1, 5:0.3]

I can see using /.count of each value in a loop somewhere but can't figure it out.

Answer

Maybe something like this?

var filteredArray = [1,2,4,5,2,1,2,1,5,5]

var counts:[Int: Double] = [:]

for item in filteredArray {
  counts[item] = (counts[item] ?? 0) + (1.0/Double(filteredArray.count))
}

print(counts)

// Output:
// [5: 0.30000000000000004, 2: 0.30000000000000004, 4: 0.10000000000000001, 1: 0.30000000000000004]
Comments