Reputation: 5
I will be happy with your help!
How can I find number of elements of array in same range?
For example, var arrayOfInt = [1, 4, 9, 19, 38, 41]
contains 3 elements of range 1...9, 1 element of range 10...19, 1 and 1 of ranges 30...39 and 40...49 respectively.
I need to count number of elements in each range (1...9, 10...19, 20...29, etc.). I suppose to use constant Dictionary with description of the ranges set, but to the end didn't understand how to solve that task.
Here is what I've got:
func finDRange(line: [Int]) -> [String: Int] {
let sourceRange = ["R0": 1...9, "R1": 10...19, "R2": 20...29, "R3": 30...39, "R4": 40...49]
var rangeDescription: [String: Int] = ["R0": 0, "R1": 0, "R2": 0, "R3": 0, "R4": 0]
var count = 0
for number in line {
for (key, range) in sourceRange {
if range.contains(number) {
rangeDescription.updateValue(+1, forKey: key)
}
}
}
return rangeDescription
}
But it works correctly if only one number of array belongs to each range. That's where I stuck!
Upvotes: 0
Views: 208
Reputation: 47886
I cannot be sure, but isn't this what you want to do?
func findRange(line: [Int]) -> [String: Int] {
let sourceRange = ["R0": 1...9, "R1": 10...19, "R2": 20...29, "R3": 30...39, "R4": 40...49]
var rangeDescription: [String: Int] = ["R0": 0, "R1": 0, "R2": 0, "R3": 0, "R4": 0]
for number in line {
for (key, range) in sourceRange {
if range.contains(number) {
rangeDescription[key] = (rangeDescription[key] ?? 0) + 1 //<- add 1 to the entry for the range
break
}
}
}
return rangeDescription
}
var arrayOfInt = [1, 4, 9, 19, 38, 41]
let result = findRange(line: arrayOfInt)
print(result) //->["R0": 3, "R1": 1, "R2": 0, "R4": 1, "R3": 1]
As suggested by Leo Dabus, you can re-write the line: rangeDescription[key] = (rangeDescription[key] ?? 0) + 1
as:
rangeDescription[key] = rangeDescription[key, default: 0] + 1
This may be the preferred way when you want to supply default value for Dictionary access in Swift 4.
(I prefer using contains
than ~=
, but you can re-write it as in the comment of Leo Dabus.)
Upvotes: 1