Skip to content

Commit

Permalink
Add exercise: roman-numerals (JuliaLang#29)
Browse files Browse the repository at this point in the history
* Add exercise: roman-numerals

* Fix config.json add missing comma

* Fix roman-numerals example

* Fix roman-numerals test sets as suggested

* Fix roman-numerals test set cycle as suggested

* Remove hint from roman-numerals example

* Fix roman-numerals test set

Added more samples, added negative number test
  • Loading branch information
Andrey authored and SaschaMann committed Feb 7, 2017
1 parent 8cb6022 commit 97bac59
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
9 changes: 9 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@
"strings"
]
},
{
"slug": "roman-numerals",
"difficulty": 1,
"topics": [
"control-flow (loops)",
"strings",
"mathematics"
]
},
{
"slug": "anagram",
"difficulty": 2,
Expand Down
21 changes: 21 additions & 0 deletions exercises/roman-numerals/example.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Aliases: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000.
function to_roman(number::Integer)
number < 1 && error("Invalid number")
alias = [
["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"],
["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],
["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"],
["M", "MM", "MMM"],
]
i = 1
result = []
while number > 0
j = rem(number, 10)
if j > 0
push!(result, alias[i][j])
end
i += 1
number = div(number, 10)
end
join(reverse(result))
end
3 changes: 3 additions & 0 deletions exercises/roman-numerals/roman-numerals.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function to_roman(number::Integer)

end
37 changes: 37 additions & 0 deletions exercises/roman-numerals/runtests.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Base.Test

include("roman-numerals.jl")

# HINT: There is no need to be able to convert numbers larger than about 3000.
samples = Dict(
1 => "I",
2 => "II",
3 => "III",
4 => "IV",
5 => "V",
6 => "VI",
9 => "IX",
27 => "XXVII",
48 => "XLVIII",
59 => "LIX",
93 => "XCIII",
141 => "CXLI",
163 => "CLXIII",
402 => "CDII",
575 => "DLXXV",
911 => "CMXI",
1024 => "MXXIV",
1703 => "MDCCIII",
1991 => "MCMXCI",
2017 => "MMXVII",
3000 => "MMM"
)

@testset "convert $sample[1] to roman numeral" for sample in samples
@test to_roman(sample[1]) == sample[2]
end

@testset "error handling" begin
@test_throws ErrorException to_roman(0)
@test_throws ErrorException to_roman(-2017)
end

0 comments on commit 97bac59

Please sign in to comment.