Reputation: 69
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:
Upvotes: 0
Views: 243
Reputation: 54716
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)
Upvotes: 1