Calculating all possible sub-sequences of a given length (C#)

前端 未结 4 1416
悲&欢浪女
悲&欢浪女 2020-12-16 06:21

If I have a sequence as follows (let\'s say it\'s an IEnumerable):

[A, B, C, D, E]

Then what\'s the cleanest way to c

4条回答
  •  清酒与你
    2020-12-16 07:07

    I would suggest a recursive algorithm for this. I'm sorry, but it has been a while since I did anything in C#, so I'll just give pseudo-code here.

    function allPossible(iterator, length, currSubSeq, allResults) {
        // Add the current sub sequence to the results if it is the correct length.
        if (currSubSeq.length == length) {
            copy = currSubSeq.copy();
            allResults.add(copy);
        }
        // If it is too long, return early.
        else if (currSubSeq.length > length) {
            return allResults;
        }
    
        // Get the next item from the iterator and handle both cases:
        // I.E. when it is, and when it isn't in a sub sequence.
        item = iterator.getNext();
        allPossible(iterator, currSubSeq, allResults);
        currSubSeq.add(item);
        allPossible(iterator, currSubSeq, allResults);
    
        return allResults;
    }
    

    Then you find all possible sub sequences by calling allPossible with an iterator that produces all elements in your original sequence, the length that you want your sub-sequences, an empty sequence of items for currSubSeq, and an empty sequence of item sequences for allResults. I'm assuming pass-by-reference semantics for all the parameters. Sorry that I couldn't give you the proper C# implementation, but I'm sure you know more than enough to take my algorithm sketch and turn it into code.

    One last thing. Because this algorithm is recursive, you may have a stack overflow if you run it on a very long sequence with a large length parameter since stack usage is O(2^N) where N = length. I don't think this is a big problem because the algorithm has O(2^N) run-time because of the nature of the problem, so you shouldn't try to run it with a large enough length to overflow the stack anyway!

    CAVEAT I haven't actually tested this pseudo-code, so there may be something subtle I haven't thought of.

提交回复
热议问题