As one can see easily, the running time inside the main loop is independent of the size of the array, hence, O(1), making the entire program run in linear time.
Yep. Linear, but twice as slow as my code above for the OPs stated requirements:
c:\test>713977-javafan -N=1e6 Took 0.00029 seconds/iteration c:\test>713977 -N=1e6 Took 0.00015 seconds/iteration
How much bigger than the requirements does the problem need to get before the additional complexity achieves parity?
And how much bigger still, before the additional complexity of your solution starts to save enough time that the user will actually notice?
Finally, what affect does that re-pick have upon the fairness of the shuffle?
#713977-javafan.pl #! perl -slw use strict; use Time::HiRes qw[ time ]; our $N ||= 1000; my @animals = qw[ dog cat bird mouse rat snake horse cow pig lizard lamb zebra lion elephant monkey ]; my $start = time; for( 1 .. $N ) { my @scratch = @animals; my @want; foreach my $animal (@animals) { for (my $j = @scratch - 1; $j >= @scratch - 3; $j --) { my $r = rand ($j + 1); @scratch[$j, $r] = @scratch[$r, $j]; if ($scratch[$j] eq $animal) { my $r = rand ($j); @scratch[$j, $r] = @scratch[$r, $j]; } } push @want, "$animal @scratch[ -3 .. -1 ]"; } } printf "Took %7.5f seconds/iteration\n", ( time() - $start ) / $N; #713977.pl #! perl -slw use strict; use List::Util qw[ shuffle ]; use Time::HiRes qw[ time ]; our $N ||= 1000; my @start = qw[ dog cat bird mouse rat snake horse cow pig lizard lamb zebra lion elephant monkey ]; my $start = time; for ( 1 .. $N ) { my @want = map{ join ' ', $start[ $_ ], ( shuffle @start[ 0 .. $_-1, $_+1 .. $#start ] )[ 0 .. 2 ] } 0 .. $#start; } printf "Took %7.5f seconds/iteration\n", ( time() - $start ) / $N;
In reply to Re^6: Array problem
by BrowserUk
in thread Array problem
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |