简体   繁体   中英

How to use reduce() on multidimensional arrays in swift

I want to iterate through a multidimensional array and compare the elements with one another and increment a value if a condition is met

   var arrayExample = [[4,8],[15,30],[25,50]];

   var noOfSimiRect: Int = 0

   arrayExample.reduce(0) {
    
   let a = $0[0]      //error: Value of type 'int' has no subscripts
   let b = $0[1]      //error: Value of type 'int' has no subscripts
   let c = $1[0]      
   let d = $1[1]      

    
if a.isMultiple(of: c) && b.isMultiple(of: d) {
    noOfSimiRect += 1
    
}
}

print(noOfSimiRect)
   

Alternatively, if I used the following syntax, I am still getting the error there

   var arrayExample = [[4,8],[15,30],[25,50]];
   var noOfSimiRect: Int = 0

   arrayExample.reduce(0) {
    
    let a = $0.0     //error: value of type 'int' has no member '0'
    let b = $1.0    //error: value of type 'int' has no member '1'
    let c = $0.0    //error: value of type '[int]' has no member 0'
    let d = $1.0     //error: value of type '[int]' has no member '1'
    
if a.isMultiple(of: c) && b.isMultiple(of: d) {
    noOfSimiRect += 1
    
}
}

 print(noOfSimiRect)

Thank you to David and Martin for answering my question but I found a catch in both your solutions.

var arrayExample = [[4,8],[15,30],[25,50]];

In the given array I want the following:

  1. compare [4,8] with [15,30] and [25,50]
  2. compare [15,30] with [4,8] and [25,50]
  3. compare [25,50] with [4,8] and [15,30]

It seems you misunderstand the inputs to the closure of reduce . The first input argument is the accumulating result, while the 2nd is the current element of the array. $0 and $1 are not the current and next elements of the array as you assume they are.

You need to iterate over the indices of the array to access 2 subsequent nested arrays and be able to check their elements against each other.

var noOfSimiRect: Int = 0
for index in arrayExample.indices.dropLast() {
    let current = arrayExample[index]
    let next = arrayExample[index + 1]
    
    if current[0].isMultiple(of: next[0]) && current[1].isMultiple(of: next[1]) {
        noOfSimiRect += 1
    }
}

print(noOfSimiRect)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM