in reply to Re^5: Array problem
in thread Array problem
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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: Array problem
by ikegami (Patriarch) on Sep 29, 2008 at 01:33 UTC | |
by BrowserUk (Patriarch) on Sep 29, 2008 at 04:25 UTC | |
by ikegami (Patriarch) on Sep 29, 2008 at 04:57 UTC | |
by JavaFan (Canon) on Sep 29, 2008 at 09:42 UTC | |
by BrowserUk (Patriarch) on Sep 29, 2008 at 15:22 UTC | |
|
Re^7: Array problem
by ikegami (Patriarch) on Sep 29, 2008 at 00:37 UTC | |
by BrowserUk (Patriarch) on Sep 29, 2008 at 01:09 UTC |