0

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)
        }
    }
Adrian
  • 16,233
  • 18
  • 112
  • 180
  • I don't see the `filter` part, and what is `incrementIndex(andAppend:)`? What's the real goal here? – matt Jan 29 '20 at 06:09
  • `filter` only lets me remove a value, not an index, so I didn't include it in my question. `prefix` & `suffix` get the job done for most cases, but not all cases and I'm seeking to figure out how to exclude a specific index. I don't know how many indices I'll have and there are some edge cases which throw out of bounds exception. It seems like something that's build in somewhere to the standard library, but I can't figure it out. – Adrian Jan 29 '20 at 06:19

2 Answers2

2

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
Keshu R.
  • 5,045
  • 1
  • 18
  • 38
1

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

matt
  • 515,959
  • 87
  • 875
  • 1,141