简体   繁体   中英

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM