SashaZ
SashaZ

Reputation: 403

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.

Upvotes: 0

Views: 991

Answers (1)

user94559
user94559

Reputation: 60143

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]

Upvotes: 5

Related Questions