Skip to content

Instantly share code, notes, and snippets.

@masak
Created November 23, 2011 19:29
Show Gist options
  • Save masak/1389646 to your computer and use it in GitHub Desktop.
Save masak/1389646 to your computer and use it in GitHub Desktop.
Doing roman numerals with TDD in Perl 6
class Roman {
my %map =
'units' => ['I', 'V', 'X'],
'tens' => ['X', 'L', 'C'],
'hundreds' => ['C', 'D', 'M'],
;
method step($size, $n) {
my ($one, $five, $ten) = %map{$size}.list;
given $n {
when * < 4 { $one x $n }
when 4 { "$one$five" }
when * < 9 { $five ~ $one x ($n - 5) }
when 9 { "$one$ten" }
}
}
method roman($n) {
return self.step('hundreds', $n div 100)
~ self.step('tens', ($n div 10) % 10)
~ self.step('units', $n % 10);
}
}
use Test;
use Roman;
my @mapping =
0, '',
1, 'I',
2, 'II',
3, 'III',
4, 'IV',
5, 'V',
6, 'VI',
7, 'VII',
8, 'VIII',
9, 'IX',
10, 'X',
11, 'XI',
14, 'XIV',
19, 'XIX',
20, 'XX',
30, 'XXX',
40, 'XL',
49, 'XLIX',
50, 'L',
90, 'XC',
666, 'DCLXVI',
;
for @mapping -> $number, $roman {
is Roman.roman($number), $roman,
"conversion of number $number";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment