Array permutations

jfondren julian.fondren at gmail.com
Sat Sep 11 19:57:26 UTC 2021


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

I don't see the pattern just from the required output. If you 
have an English description of what you want, it might be easier.

Anyway, take a look at

```d
unittest {
     import std.algorithm : cartesianProduct, filter, map, sort;
     import std.range : drop;
     import std.array : array;

     auto list = [1,2,3,4,5];
     auto required = 
[[1,2],[2,3],[3,4],[4,5],[1,3],[1,4],[1,5],[2,4],[2,5],[3,5]];
     auto pairs = list.cartesianProduct(list.drop(1))
         .filter!"a[0] < a[1]"
         .map!array
         .array;
     assert(pairs == [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 
4], [2, 5], [3, 4], [3, 5], [4, 5]]);
     assert(required.sort.array == pairs);
}
```


More information about the Digitalmars-d-learn mailing list