Reputation: 75
I have an array of fruit as in the below code. I then have 3 arrays with a dictionary inside which gives a value based on position that the fruit has been positioned in array. I plan to do this within a TableView. For instance, a fruit in
[0] element would give a value of 4 (fruitName.count)
[1] element would give a value of 3 (fruitName.count - 1) etc...
My problem is that I need to calculate the total amount of fruit from all the arrays for the specific piece of fruit.
var fruitName = ["Apple", "Pear", "Banana", "Orange"]
var Group1 = ["Apple": (fruitName.count), "Pear": (fruitName.count-1),"Banana": (fruitName.count - 2), "Orange": (fruitName.count - 3)]
var Group2 = ["Apple": (fruitName.count), "Orange": (fruitName.count - 1), "Pear": (fruitName.count - 2), "Bananna": (fruitName.count - 3)]
var Group3 = ["Pear": (fruitName.count), "Apple": (fruitName.count - 1), "Orange": (fruitName.count - 2), "Bananna": (fruitName.count - 3)]
So the result should provide the answer below. How would I go about solving this? I appreciate that the code isn't written perfectly. I hope I've explained myself ok... Thanks
Apple - 4 (Group1) + 4 (Group2) + 3 (Group3) = 11
Pear - 3 (Group1) + 2 (Group2) + 4 (Group3) = 9
Banana - 2 (Group1) + 1 (Group2) + 1 (Group3) = 4
Orange - 1 (Group1) + 3 (Group2) + 2 (Group3) = 6
Upvotes: 0
Views: 98
Reputation: 4343
It's not like I don't like the previous answers by @vadian and @Shades, but here it's another way:
var x = [String:Int]()
[Group1, Group2, Group3].flatMap({$0}).forEach({ x[$0.0] = $0.1 + (x[$0.0] ?? 0) })
And then print them:
for (k,v) in x.enumerate() {
print ("\(k) : \(v)")
}
Upvotes: 0
Reputation: 5616
A dictionary value is accessed by its key, so we can run through each fruit in the array, use it as the key to access the count in each array, then add them all together. Note changing the array names to a lowercase "g."
Edit From the comments, the nil coalescing operator is used in case the fruit is not even in the array. Then, the count will be set to 0.
for fruit in fruitName {
let count1 = group1[fruit] ?? 0, count2 = group2[fruit] ?? 0, count3 = group3[fruit] ?? 0
let fruitTotal = count1 + count2 + count3
print(fruitTotal)
}
Prints
11
9
4
6
Upvotes: 1
Reputation: 285160
First of all you have a couple of Banannas in the arrays...
Second of all, all your variables are constants (let
)
Create an array from the groups
let groups = [Group1, Group2, Group3]
Then iterate thru the fruitName
array, (flat)map the corresponding values to an array and add the values (reduce:combine:
)
for name in fruitName {
let max = groups.flatMap({$0[name]}).reduce(0, combine: {$0 + $1})
print(name + " = \(max)")
}
In Swift 3 the flatMap
/ reduce
line is
let max = groups.flatMap({$0[name]}).reduce(0, {$0 + $1})
Upvotes: 2