Skip to content

Commit

Permalink
convert arabic to roman
Browse files Browse the repository at this point in the history
  • Loading branch information
neftales committed Jun 8, 2024
1 parent 581154a commit 6eddda0
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 19 deletions.
32 changes: 26 additions & 6 deletions roman_numerals/numeral.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,35 @@ package romannumerals

import "strings"

type RomanNumeral struct {
Value int
Symbol string
}

var allRomanNumerals = []RomanNumeral{
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
}

func ConvertToRoman(arabic int) string {
var result strings.Builder

if arabic == 4 {
return "IV"
}

for i := 0; i < arabic; i++ {
result.WriteString("I")
for _, numeral := range allRomanNumerals {
for arabic >= numeral.Value {
result.WriteString(numeral.Symbol)
arabic -= numeral.Value
}
}

return result.String()
Expand Down
51 changes: 38 additions & 13 deletions roman_numerals/numeral_test.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,50 @@
package romannumerals

import "testing"
import (
"fmt"
"testing"
)

func TestRomanNumerals(t *testing.T) {
cases := []struct {
Description string
Arabic int
Want string
Arabic int
Roman string
}{
{Description: "1 gets converted to I", Arabic: 1, Want: "I"},
{Description: "2 gets converted to II", Arabic: 2, Want: "II"},
{Description: "3 gets converted to III", Arabic: 3, Want: "III"},
{Description: "4 gets converted to IV (can't repeat more than 4 times)", Arabic: 4, Want: "IV"},
{Arabic: 1, Roman: "I"},
{Arabic: 2, Roman: "II"},
{Arabic: 3, Roman: "III"},
{Arabic: 4, Roman: "IV"},
{Arabic: 5, Roman: "V"},
{Arabic: 6, Roman: "VI"},
{Arabic: 7, Roman: "VII"},
{Arabic: 8, Roman: "VIII"},
{Arabic: 9, Roman: "IX"},
{Arabic: 10, Roman: "X"},
{Arabic: 14, Roman: "XIV"},
{Arabic: 18, Roman: "XVIII"},
{Arabic: 20, Roman: "XX"},
{Arabic: 39, Roman: "XXXIX"},
{Arabic: 40, Roman: "XL"},
{Arabic: 47, Roman: "XLVII"},
{Arabic: 49, Roman: "XLIX"},
{Arabic: 50, Roman: "L"},
{Arabic: 100, Roman: "C"},
{Arabic: 90, Roman: "XC"},
{Arabic: 400, Roman: "CD"},
{Arabic: 500, Roman: "D"},
{Arabic: 900, Roman: "CM"},
{Arabic: 1000, Roman: "M"},
{Arabic: 1984, Roman: "MCMLXXXIV"},
{Arabic: 3999, Roman: "MMMCMXCIX"},
{Arabic: 2014, Roman: "MMXIV"},
{Arabic: 1006, Roman: "MVI"},
{Arabic: 798, Roman: "DCCXCVIII"},
}

for _, test := range cases {
t.Run(test.Description, func(t *testing.T) {
t.Run(fmt.Sprintf("%d gets converted to %q", test.Arabic, test.Roman), func(t *testing.T) {
got := ConvertToRoman(test.Arabic)

if got != test.Want {
t.Errorf("got %q, want %q", got, test.Want)
if got != test.Roman {
t.Errorf("got %q, want %q", got, test.Roman)
}
})
}
Expand Down

0 comments on commit 6eddda0

Please sign in to comment.