How to create lazy combinations

后端 未结 2 2015
眼角桃花
眼角桃花 2020-12-12 04:24

My question is very simple, how do I make this code lazy:

/*
input: [
    [1, 2],
    [3, 4],
    [5, 6]
]

output: [
    [1, 3, 5],
    [1, 3, 6],
    [1, 4         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 05:10

    I found one possible solution, but I'll leave this answer not accepted for a while to see if someone knows a better one.

    func combinations(options: [[T]]) -> LazySequence> {
        guard let head = options.first else {
            return AnySequence([].lazy.map({ [$0] })).lazy
        }
    
        if options.count == 1 {
            return AnySequence(head.lazy.map({ [$0] })).lazy
        }
    
        let tailCombinations = combinations(options: Array(options.dropFirst()))
    
        return AnySequence(head.lazy.flatMap({ option in
            return tailCombinations.lazy.map({ [option] + $0 })
        })).lazy
    }
    

    The solution was to use AnySequence instead of AnyCollection. I'm not sure why though, I'd still like to have the AnyCollection interface rather than AnySequence, since it provides me with a few more methods, like count.

提交回复
热议问题