Created
May 21, 2015 20:45
-
-
Save rlespinasse/fb9ebe5384c7f7f5b808 to your computer and use it in GitHub Desktop.
kata roman numerals in Go
This file contains 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
all: testAndCover | |
testAndCover: | |
@go test -coverprofile=cover.out . | |
@go tool cover -html=cover.out |
This file contains 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
package main | |
import "strings" | |
var romanLetter map[string]int | |
var romanNum map[int]string | |
var romanNumKeys []int | |
func init() { | |
romanLetter = make(map[string]int) | |
romanLetter["I"] = 1 | |
romanLetter["V"] = 5 | |
romanLetter["X"] = 10 | |
romanNum = make(map[int]string) | |
romanNum[10] = "X" | |
romanNum[5] = "V" | |
romanNum[1] = "I" | |
romanNumKeys = []int{10, 5, 1} | |
} | |
func romanSum(op1 string, op2 string) string { | |
var sumRest int | |
var sum string | |
sum = "" | |
sumRest = opSum(op1) + opSum(op2) | |
if sumRest == 4 { | |
return "IV" | |
} else if sumRest == 9 { | |
return "IX" | |
} | |
for _, n := range romanNumKeys { | |
for sumRest >= n { | |
sum = sum + romanNum[n] | |
sumRest = sumRest - n | |
} | |
} | |
return sum | |
} | |
func opSum(op string) int { | |
if op == "IV" { | |
return 4 | |
} else if op == "IX" { | |
return 9 | |
} else { | |
var opsum int | |
opsum = 0 | |
for key, value := range romanLetter { | |
opsum = opsum + strings.Count(op, key)*value | |
} | |
return opsum | |
} | |
} |
This file contains 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
package main | |
import "testing" | |
func TestSum(t *testing.T) { | |
cases := []struct { | |
op1 string | |
op2 string | |
exp string | |
}{ | |
{"I", "I", "II"}, | |
{"I", "II", "III"}, | |
{"II", "I", "III"}, | |
{"II", "II", "IV"}, | |
{"III", "I", "IV"}, | |
{"I", "III", "IV"}, | |
{"III", "II", "V"}, | |
{"II", "III", "V"}, | |
{"IV", "I", "V"}, | |
{"I", "IV", "V"}, | |
{"III", "III", "VI"}, | |
{"III", "IV", "VII"}, | |
{"III", "V", "VIII"}, | |
{"III", "VI", "IX"}, | |
{"V", "V", "X"}, | |
{"IX", "I", "X"}, | |
{"X", "I", "XI"}, | |
} | |
for _, c := range cases { | |
sum := romanSum(c.op1, c.op2) | |
if sum != c.exp { | |
t.Errorf("op1(%q) + op2(%q) = got(%q) != want(%q)", c.op1, c.op2, sum, c.exp) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment