Home > Enterprise >  Combining (ALL individual) Elements of an Arrays in a Dictionary
Combining (ALL individual) Elements of an Arrays in a Dictionary

Time:10-18

The Dictionary is defined as

var weekActualPowerZoneTimes: [String:[Int]]()

weekActualPowerZoneTimes:
[
"Ride"  : [1, 1, 1, 1, 1, 1, 1, 1], 
"Run"   : [1, 1, 1, 1, 1, 1, 1, 1], 
"Swim"  : [1, 1, 1, 1, 1, 1, 1, 1], 
"Other" : [1, 1, 1, 1, 1, 1, 1, 1]
]

Goal: combine these arrays to become one. Namely, I'm looking for this output

[4, 4, 4, 4, 4, 4, 4, 4]

The Arrays to be sum, technically should be of equal size, but there could be a chance that they would not be depending on user preference. (Some user may choose to have 7 Power Zones, some may use 5 in the future)

I am currently able to sum 2 arrays using this

let arrayResult:[Int] = zip(array1,array2).map( )

but getting stuck on how to sum a possible arbitrary number of arrays (eg: User may only be doing Run/Swim or Run/Swim/Ride or Others/Swim) in the dictionary.

Update: I tried this, which works, but only if I define the initial "combined" Array

var combined = [0,0,0,0,0,0,0,0]

let aa =
[
"Ride"  : [1, 1, 1, 1, 1, 1, 1, 1],
"Run"   : [2, 1, 1, 1, 1, 1, 1, 1],
"Swim"  : [3, 1, 1, 1, 1, 1, 1, 1],
"Other" : [4, 1, 1, 1, 1, 1, 1, 1]
]

for (index,values) in aa.values.enumerated(){
    print(index, values)
    combined = zip(combined,values).map( )
    print("\(combined)") // [10, 4, 4, 4, 4, 4, 4, 4]
}

But it will result in [] if the initial combined array is defined as

var combined = [Int]()

CodePudding user response:

I found this variant of zipping on reddit that works for arrays of different length

func add(a: [Int], b: [Int]) -> [Int] {
    zip(a, b).map( )   (a.count < b.count ? b[a.count ..< b.count] : a[b.count ..< a.count])
}

So with that we can loop over the values of the dictionary

var combined = [Int]()
weekActualPowerZoneTimes.values.forEach {
    combined = add(a: combined, b: $0)
}

Using a forEach loop over values means we can have any number of values and the add function means the values arrays can be of different length

CodePudding user response:

The logic becomes clear to me in basic loops. Verbose but still.

var combine = [Int]()
for (_, powerzone) in weekActualPowerZoneTimes { 
   for i in powerzone.indices {
      if combine.endIndex > i {
         combine[i]  = array[i]
      } else {
         combine[i] = array[i]
      }
   }
}
  • Related