The shuffling approach is no good, for two reasons:
- There may ne no solution, hence your program would shuffle until end of all time.
- It will get quite time consuming as the number of elements change.
I suggest another solution:
- We are given a set of numbers (may be represented by a list)
- We need a boolean function
canFollow
that returns true if a given number may extend the result list we have so far. (The rules you have given would allow an easier function that takes two numbers, but for more complex conditions like5 can be followed by 8 only when not preceded by 6
the more general function would work.) - Once you have this, you can construct a solution: Start out with an empty list. While the given set is not empty, take one element from it, and check if it can follow the result. If so, repeat until the given set is empty, in which case you have a solution. Otherwise, try the next number:
In pseudo code:
List<Int> brute(List<Int> result, List <Int> given) {
if (given is empty) return result;
foreach i in given
if i can follow result
r = brute(result + i, given - i)
if r != null return r
return null
}
solution = brute([], [1,2,3,4,5,6])
(Note that result + i is short for result with i appended and given - i is given without i, but make sure you construct this without destryoing the original result and given.)
If you need all solutions, this can easily be changed by adding a valid result to some list that starts out empty.