On Saturday, 11 September 2021 at 19:37:42 UTC, Vino wrote:
Hi All,

Request your help on the below to print the below array as "Required output", Was able to get these values "[1,2],[2,3],[3,4],[4,5]" by using list.slide(2), need your help to get values "1,3],[1,4],[1,5],[2,4],[2,5],[3,5]"

auto list[] = [1,2,3,4,5]

Required output
[1,2],[2,3],[3,4],[4,5],[1,3],[1,4],[1,5],[2,4],[2,5],[3,5]

From,
Vino

Would this be a valid solution to your problem?

```D
pure @safe nothrow
T[][] computeChoices(T)(T[] values, size_t tupleSize = 2)
{
    if (tupleSize == 0) {
        return [[]];
    }

    T[][] choices = [];
    tupleSize--;
    foreach(i, element; values[0 .. $ - tupleSize])
    {
        import std.algorithm.iteration : map;
        import std.array : array;
        choices ~= computeChoices(values[i+1 .. $], tupleSize)
                        .map!(choice => element ~ choice)
                        .array;
    }

    return choices;
}

unittest
{
    assert(computeChoices([1, 2, 3, 4, 5], 2)
== [[1,2], [1,3], [1,4], [1,5], [2,3], [2,4], [2,5], [3,4], [3,5], [4,5]] );
}
```

You can choose in the 2nd parameter how large the inner arrays should be. It uses GC to allocate the result via the function `array`. If that is a problem, you could choose an allocator from `std.experimental.allocator` and use the `makeArray` function with the allocator instead of the `array` function. (Manual deallocation could be required then as well.)

Reply via email to