Reputation: 16715
I'd like to filter an array of numbers and use reduce on them, but I need to exclude a specific index
and I can't divide. Is it possible to do this with methods that are part of Foundation
in Swift?
I've tried breaking the array into two using prefix
& suffix
, but there are some edge cases where it blows up w/ an out of bounds exception.
while currentIndex < nums.count - 2 {
for _ in nums {
let prefix = nums.prefix(currentIndex)
let suffix = nums.suffix(from: currentIndex + 1)
if prefix.contains(0) || suffix.contains(0) {
incrementIndex(andAppend: 0)
}
let product = Array(prefix + suffix).reduce(1, *)
incrementIndex(andAppend: product)
}
}
Upvotes: 0
Views: 1283
Reputation: 534925
I'm seeking to figure out how to exclude a specific index
What about this sort of thing?
var nums2 = nums
nums2.remove(at:[currentIndex])
let whatever = nums2.reduce // ...
Where remove(at:)
is defined here: https://stackoverflow.com/a/26308410/341994
Upvotes: 1
Reputation: 5215
You can use enumerated()
to convert a sequence(eg. Arrays) to a sequence of tuples with an integer counter and element paired together
var a = [1,2,3,4,5,6,7]
var c = 1
let value = a.enumerated().reduce(1) { (_, arg1) -> Int in
let (index, element) = arg1
c = index != 2 ? c*element : c
return c
}
print(value) // prints 1680 i.e. excluding index 2
Upvotes: 2