Created
March 29, 2015 00:06
-
-
Save jonathanstowe/ff0885b0841b39aeebed to your computer and use it in GitHub Desktop.
Euclidean / Björlund / Toussaint algorith in Perl 6
This file contains hidden or 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
#!perl6 | |
use v6; | |
# From Björklund via http://cgm.cs.mcgill.ca/~godfried/publications/banff.pdf | |
class Euclid | |
{ | |
method build_string(Int $level, @count, @remainder ) | |
{ | |
my @bitmap; | |
if ($level == -1) | |
{ | |
push @bitmap, 0; | |
} | |
elsif ( $level == -2 ) | |
{ | |
push @bitmap, 1; | |
} | |
else | |
{ | |
for 0 .. @count[$level] - 1 | |
{ | |
push @bitmap, self.build_string($level-1, @count, @remainder); | |
} | |
if (@remainder[$level] != 0) | |
{ | |
push @bitmap, self.build_string($level-2, @count, @remainder); | |
} | |
} | |
return @bitmap; | |
} | |
method compute_bitmap($num_slots, $num_pulses) | |
{ | |
my @count; | |
my @remainder; | |
my $divisor = $num_slots - $num_pulses; | |
@remainder[0] = $num_pulses; | |
my $level = 0; | |
while (@remainder[$level] > 1 ) | |
{ | |
@count[$level] = $divisor / @remainder[$level]; | |
@remainder[$level+1] = $divisor % @remainder[$level]; | |
$divisor = @remainder[$level]; | |
$level++; | |
} | |
@count[$level] = $divisor; | |
my @bits = self.build_string($level, @count, @remainder); | |
while (@bits[0] == 0) | |
{ | |
shift @bits; | |
push @bits, 0; | |
} | |
return @bits; | |
} | |
} | |
sub MAIN(Int :$slots, Int :$fills) { | |
say Euclid.new.compute_bitmap($slots, $fills); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment