Last active
August 8, 2016 02:01
-
-
Save BenGoldberg1/7a4527bc27f7a75fa403e6d6f4a59677 to your computer and use it in GitHub Desktop.
Recursive quickshuffle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sub shuffle( @arr is copy ) { | |
my sub qshuf ( $first is copy, $cnt is copy ) { | |
loop { | |
return if $cnt <= 1; | |
my ($left, $right) = ($first, $first+$cnt); | |
SWAPLOOP: loop { | |
++$left >= $right and last SWAPLOOP while Bool.pick; | |
--$right <= $left and last SWAPLOOP while Bool.pick; | |
@arr[$left++, --$right] .= reverse; | |
last if $left >= $right; | |
} | |
my $lsize = $left - $first; | |
my $rsize = $cnt - $lsize; | |
if $lsize < $rsize { | |
qshuf( $first, $lsize ); | |
($first, $cnt) = ( $left, $rsize ); | |
} else { | |
qshuf( $left, $rsize ); | |
$cnt = $lsize; | |
} | |
} | |
} | |
qshuf( 0, +@arr ); | |
return @arr; | |
} | |
say shuffle( flat ^30 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment