[Python] Algorithm to select multiple non-overlapping subsequences of given sequence

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    You have been given the input data (a sequence of items), for example:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]


    and your task is to randomly select M non-overlapping samples (subsequences) of the same size N.

    For example, if the task was to select 3 samples of size 3, one of the solutions would be:

    [3, 4, 5]
    [8, 9, 10]
    [11, 12, 13]


    My algorithm:

    1. Select randomly first sample: [11, 12, 13]
    2. Remaining input data are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and [14, 15, 16].
    3. Select randomly second sample from the remaining input data: [3, 4, 5].
    4. Remaining input data (big enough) are [6, 7, 8, 9, 10] and [14, 15, 16].
    5. Select randomly third sample from the remaining input data: [8, 9, 10].

    Sadly, this algorithm does not work when the samples are too big. If the task was to select 3 samples of size 5, there exists a solution, but if you use my algorithm and select randomly the first sample as [3, 4, 5, 6, 7], the algorithm will fail.


    Of course there is also an obvious brute-force algorithm: find all possible solutions and select randomly one of them. But I was hoping for something more "clever" (time and space efficient).

    Continue reading...

Compartilhe esta Página