Arduino Analog and Digital Pin scanning permutation

This is handled differently in real code.

Google

 index permutation algorithm

and poke around a bit. There are algorithms to go directly from an index to a corresponding permutation.

Then you can call such a function with a number N and get the Nth permutation like reading it right off a list, without the necessity of keeping track of where you were, or suspending and resuming an algorithm that goes one by one from the first to the last.

You can get arbitrary permutations in any order you want.

Your code looks like lotsa fun, but would be a smallish nightmare to accommodate your use case.

a7