Looping on ranges (Modular iterations)

Is it possible to make the following code modular, so that it works up till depth n, and returns an array of all possible combinations for used{}?

ranges is an nx2 array which contains the ranges for the ith loop.

    used = Table[0, lb]
For[i = ranges[[1, 1]], i <= ranges[[1, 2]], i++,
used[] = i;
For[j = ranges[[2, 1]], j <= ranges[[2, 2]], j++,
If[FreeQ[used, j],
used[] = j;
For[k = ranges[[3, 1]], k <= ranges[[3, 2]], k++,
If[FreeQ[used, k],
used[] = k;
For[l = ranges[[4, 1]], l <= ranges[[4, 2]], l++,
If[FreeQ[used, l],
used[] = l;
For[m = ranges[[5, 1]], m <= ranges[[5, 2]], m++,
If[FreeQ[used, m],
used[] = m;
(*operations*)

used[] = 0;
];
];
used[] = 0;
];
];
used[] = 0;
];
];
used[] = 0;
];
];
used[] = 0
];


I am not able to find the proper tags, so suggestions are welcome.

• The code has syntax errors... And it's not clear to me what the aim is. – Henrik Schumacher Apr 7 '18 at 23:16
• @HenrikSchumacher i hope its clearer now. I want to find all possible sets of the matrix used without using all these nested loops, and preferably in a parametric fashion (taking the number of nested loops as an input, say) – Ashwin Kumar Apr 7 '18 at 23:20

Maybe the following does what you look for.

step = {x, ran} \[Function] Select[
Flatten[Outer[Join, x, Partition[Range @@ ran, 1], 1], 1],
DuplicateFreeQ
];

lb = 3;
ranges = Sort /@ RandomInteger[{1, 10}, {lb, 2}];
Join @@ FoldList[
step,
{{}},
ranges
]


Maybe you are only interested in (the result of) Select[Tuples[Range @@@ ranges],DuplicateFreeQ]. Then

Fold[step, {{}}, ranges]


provides a much faster alternative (compare for lb = 10).

• { {1, 2, 3, 4, 5}, {1, 2, 3, 5, 4}, {1, 2, 4, 3, 5}, {1, 2, 4, 5, 3}, {1, 2, 5, 3, 4}, {1, 2, 5, 4, 3}, {1, 3, 2, 4, 5}, {1, 3, 2, 5, 4}, {1, 3, 4, 2, 5}, {1, 3, 4, 5, 2}, {1, 3, 5, 2, 4}, {1, 3, 5, 4, 2}, {1, 4, 2, 3, 5}, {1, 4, 2, 5, 3}, {1, 4, 3, 2, 5}, {1, 4, 3, 5, 2}, {1, 4, 5, 2, 3}, {1, 4, 5, 3, 2}, {1, 5, 2, 3, 4}, {1, 5, 2, 4, 3}, {1, 5, 3, 2, 4}, {1, 5, 3, 4, 2}, {1, 5, 4, 2, 3}, {1, 5, 4, 3, 2}, {2, 1, 3, 4, 5}, {2, 1, 3, 5, 4}, {2, 1, 4, 3, 5}, {2, 1, 4, 5, 3}, {2, 1, 5, 3, 4}, {2, 1, 5, 4, 3}} – Ashwin Kumar Apr 9 '18 at 7:49
• The previous comment is the output i expect when I have ranges as {{1, 2}, {1, 5}, {2, 5}, {2, 5}, {2, 5}}. Your suggestion seems to achieve a different objective. Can you suggest something for this?Also, lb=5 – Ashwin Kumar Apr 9 '18 at 7:50
• Then you are in fact interested in Select[Tuples[Range @@@ ranges], DuplicateFreeQ] or Fold[step, {{}}, ranges]. Both yield the same but for more and longer lists with many duplicates, the latter will be significantly faster. – Henrik Schumacher Apr 9 '18 at 8:29
• Thanks, that solved it! – Ashwin Kumar Apr 9 '18 at 12:32
• Good to hear that! – Henrik Schumacher Apr 9 '18 at 12:36