Created
February 23, 2011 04:18
-
-
Save colomon/840013 to your computer and use it in GitHub Desktop.
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
use Test; | |
sub sorted-merge($lhs, $rhs) { | |
my $lhs-list = flat($lhs.list); | |
my $rhs-list = flat($rhs.list); | |
gather { | |
while ?$lhs-list && ?$rhs-list { | |
my $a = $lhs-list.shift; | |
my $b = $rhs-list.shift; | |
if $a == $b { | |
take $a; | |
} elsif $a < $b { | |
take $a; | |
$rhs-list.unshift($b); | |
} else { | |
take $b; | |
$lhs-list.unshift($a); | |
} | |
} | |
while ?$lhs-list { | |
take $lhs-list.shift; | |
} | |
while ?$rhs-list { | |
take $rhs-list.shift; | |
} | |
} | |
} | |
multi sub MAIN() { | |
my @hamming = (1, 2); | |
loop { | |
# say "@hamming: " ~ @hamming; | |
my $h = @hamming.shift; | |
say $h; | |
@hamming = sorted-merge(@hamming, ($h * 2, $h * 3, $h * 5)); | |
} | |
} | |
multi sub MAIN("test") { | |
is ~sorted-merge(1..10, (3, 5 ... 13)), ~(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13), "merged list correct"; | |
is ~sorted-merge((3, 5 ... *), 1..5)[^10], ~(1, 2, 3, 4, 5, 7, 9, 11, 13, 15), "merged list correct"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment