Apple Swift - Generate combinations with repetition

后端 未结 5 1928
自闭症患者
自闭症患者 2020-12-28 09:25

I\'m trying to generate a nested array containing all combinations with repetition in Apple\'s Swift programming language.

An detailed explanation of combinations wi

5条回答
  •  既然无缘
    2020-12-28 10:12

    The main mistake I was making was to use a var named the same as my function:

    combos += combos(array, k)
    

    Which is why I was seeing an error on this line and the other line where my function was being called.

    After fixing that the rest of the problems were easier to solve :)

    In case it will help anyone here's my working function:

    func combos(var array: Array, k: Int) -> Array> {
        if k == 0 {
            return [[]]
        }
    
        if array.isEmpty {
            return []
        }
    
        let head = array[0]
    
        var ret: Array> = []
        var subcombos = combos(array, k - 1)
        for subcombo in subcombos {
            var sub = subcombo
            sub.insert(head, atIndex: 0)
            ret.append(sub)
        }
        array.removeAtIndex(0)
        ret += combos(array, k)
    
        return ret
    }
    

    If anyone can improve it I'd be happy

    For example can anyone explain how to get rid of the line var sub = subcombo. i.e. how do I make subcombo mutable by default?

提交回复
热议问题