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)
        }
    }
2
  • I don't see the filter part, and what is incrementIndex(andAppend:)? What's the real goal here? Commented Jan 29, 2020 at 6: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. Commented Jan 29, 2020 at 6:19

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain what c is in var c = 1?
a temporary value that will hold the multiplication result
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.