Search code examples
swiftfactorial

Factorial with intermediate results - Swift playgrounds - index out of range error


Getting blind from looking at this for too long. Can't spot the error. Getting the "index out of range" error when calling the function factorialIntermediateResults(n: 4) Hope somebody can take a look with fresh eyes and help me spot the error. Thanks!

func factorialIntermediateResults(n: Int) -> [Int] {
    if n == 0 || n == 1 { return [1] }
    var results = [Int]()
    doAllFactorials(n, &results, 0)
    return results
}

func doAllFactorials(_ n: Int, _ results: inout [Int], _ level: Int) -> Int {
    if n > 1 {
        results[level] = n * doAllFactorials(n-1, &results, level+1)
        return results[level]
    } else {
        results[level] = 1
        return 1
    }
}

factorialIntermediateResults(n: 4)

Solution

  • results is an empty array but you try to access values without appending values first.

    The simplest solution might be to pre-populate your array with zeros.

    var results: [Int] = Array(repeating: 0, count: n)