Skip to content

Instantly share code, notes, and snippets.

@colomon
Created February 23, 2011 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colomon/840013 to your computer and use it in GitHub Desktop.
Save colomon/840013 to your computer and use it in GitHub Desktop.
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