in reply to Odometer pattern iterator (in C). (Updated.)
I know you won't like me saying this, but I think that this comment:
It appears to me that the actual output (in the revised OP ...), is “give me all 3-tuples in the domain 0..5 such that none of the values in the tuple are duplicated.” You can construct the bit-sequences from this if you need them.from your very dear friend sundialsvc4 is actually interesting and relevant and the idea of using a recursive function also makes some sense (although, to tell the truth, I fail to see the relevance of sundialsvc4's subsequent comments on the eight-queens problem).
So, forgetting the bits in your original question and directly searching for all unique N-tuples in a set of M unique elements, I came up with this try:
which produces the following output:use strict; use warnings; my $M = 5; my @a = 1..$M; my $N = 3; get_all_tuples ($N, [], @a); sub get_all_tuples { my ($level, $valref, @a) = @_; if ($level <= 1) { print "@$valref $_\n" for @a; } else { while (@a) { my $i = shift @a; push @$valref, $i; get_all_tuples ($level-1, $valref, @a); pop @$valref; } } }
Changing M to 10 and N to 4:$ perl N_among_M.pl 1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5
Removing the printing of the solutions and just storing them in an array, and printing only the array count at the end, and using M = 20 and N = 10, the program completes in just slightly over half a second:$ perl N_among_M.pl 1 2 3 4 1 2 3 5 1 2 3 6 1 2 3 7 1 2 3 8 1 2 3 9 1 2 3 10 1 2 4 5 ... 5 7 9 10 5 8 9 10 6 7 8 9 6 7 8 10 6 7 9 10 6 8 9 10 7 8 9 10
Computing almost 1.7m solutions in just over half a second is not too bad, it seems to me, but I have no idea on the dimensions of the actual problem you are trying to solve. This solution can easily be ported to C, I think, if performance needs to be higher.$ time perl N_among_M.pl 167960 real 0m0.524s user 0m0.499s sys 0m0.015s
Sorry to come back relatively late on the subject, but this weekend of mine was primarily aimed at filling my tax returns. One of the most boring task each year, I am happy that I could enjoy doing some Perl programming afterwards, this is really more pleasing and more fun.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Odometer pattern iterator (in C). (Updated.)
by BrowserUk (Patriarch) on May 31, 2015 at 22:03 UTC | |
by Laurent_R (Canon) on Jun 01, 2015 at 08:59 UTC | |
Re^2: Odometer pattern iterator (in C). (Updated.)
by Anonymous Monk on May 31, 2015 at 23:08 UTC | |
by Laurent_R (Canon) on Jun 01, 2015 at 08:07 UTC | |
Re^2: Odometer pattern iterator (in C). (Updated.)
by Anonymous Monk on Jun 01, 2015 at 06:20 UTC |