improved speed and added BytesToInt

This commit is contained in:
Branden Colen
2021-04-02 11:41:13 -05:00
parent d98473f5cc
commit b4f47359bc
3 changed files with 103 additions and 49 deletions
+5 -4
View File
@@ -11,10 +11,11 @@ Quickly and efficiently convert to and from roman numerals in Go.
goos: darwin goos: darwin
goarch: arm64 goarch: arm64
pkg: github.com/brandenc40/romannumeral pkg: github.com/brandenc40/romannumeral
BenchmarkToRomanNumeral BenchmarkIntToString-8 18174510 65.95 ns/op 24 B/op 2 allocs/op
BenchmarkToRomanNumeral-8 10997846 108.5 ns/op BenchmarkStringToInt-8 17507576 67.26 ns/op 0 B/op 0 allocs/op
BenchmarkToInteger BenchmarkBytesToInt-8 18342873 64.75 ns/op 0 B/op 0 allocs/op
BenchmarkToInteger-8 18861016 62.29 ns/op PASS
ok github.com/brandenc40/romannumeral 5.151s
``` ```
### Example ### Example
+30 -20
View File
@@ -6,8 +6,8 @@
package romannumeral package romannumeral
import ( import (
"bytes"
"errors" "errors"
"strings"
) )
const ( const (
@@ -23,25 +23,27 @@ var (
// numeral describes the value and symbol of a single roman numeral // numeral describes the value and symbol of a single roman numeral
type numeral struct { type numeral struct {
val int val int
sym string sym []byte
} }
// _numerals are all unique numerals ordered from largest to smallest // _numerals are all unique numerals ordered from largest to smallest
var _numerals = []numeral{ var _numerals = []numeral{
{1000, "M"}, {900, "CM"}, {500, "D"}, {1000, []byte("M")}, {900, []byte("CM")},
{400, "CD"}, {100, "C"}, {90, "XC"}, {500, []byte("D")}, {400, []byte("CD")},
{50, "L"}, {40, "XL"}, {10, "X"}, {100, []byte("C")}, {90, []byte("XC")},
{9, "IX"}, {5, "V"}, {4, "IV"}, {50, []byte("L")}, {40, []byte("XL")},
{1, "I"}, {10, []byte("X")}, {9, []byte("IX")},
{5, []byte("V")}, {4, []byte("IV")},
{1, []byte("I")},
} }
// FromInt converts an integer value to a roman numeral string. An error is // IntToString converts an integer value to a roman numeral string. An error is
// returned if the integer is not between 1 and 3999. // returned if the integer is not between 1 and 3999.
func FromInt(input int) (string, error) { func IntToString(input int) (string, error) {
if outOfBounds(input) { if outOfBounds(input) {
return "", IntegerOutOfBounds return "", IntegerOutOfBounds
} }
return intToRoman(input), nil return string(intToRoman(input)), nil
} }
// outOfBounds checks to ensure an input value is valid for roman numerals without the need of // outOfBounds checks to ensure an input value is valid for roman numerals without the need of
@@ -50,21 +52,29 @@ func outOfBounds(input int) bool {
return input < _minRoman || input > _maxRoman return input < _minRoman || input > _maxRoman
} }
func intToRoman(input int) string { func intToRoman(input int) []byte {
var output string output := bytes.Buffer{}
for _, rom := range _numerals { for _, rom := range _numerals {
for input >= rom.val { for input >= rom.val {
output += rom.sym output.Write(rom.sym)
input -= rom.val input -= rom.val
} }
} }
return output return output.Bytes()
} }
// ToInt converts a roman numeral string to an integer. Roman numerals for numbers // StringToInt converts a roman numeral string to an integer. Roman numerals for numbers
// outside of the range 1 to 3,999 will return an error. // outside of the range 1 to 3,999 will return an error. Empty strings will return 0
func ToInt(input string) (int, error) { // with no error thrown.
if input == "" { func StringToInt(input string) (int, error) {
return BytesToInt([]byte(input))
}
// BytesToInt converts a roman numeral byte array to an integer. Roman numerals for numbers
// outside of the range 1 to 3,999 will return an error. Nil or empty []byte will return 0
// with no error thrown.
func BytesToInt(input []byte) (int, error) {
if input == nil || len(input) == 0 {
return 0, nil return 0, nil
} }
if output, ok := romanToInt(input); ok { if output, ok := romanToInt(input); ok {
@@ -73,10 +83,10 @@ func ToInt(input string) (int, error) {
return 0, InvalidRomanNumeral return 0, InvalidRomanNumeral
} }
func romanToInt(input string) (int, bool) { func romanToInt(input []byte) (int, bool) {
var output int var output int
for _, rom := range _numerals { for _, rom := range _numerals {
for strings.HasPrefix(input, rom.sym) { for bytes.HasPrefix(input, rom.sym) {
output += rom.val output += rom.val
input = input[len(rom.sym):] input = input[len(rom.sym):]
} }
+68 -25
View File
@@ -26,72 +26,115 @@ var testCases = map[string]int{
"MMMCMLXXIX": 3979, "MMMCMXCIX": 3999, "MMMCMLXXIX": 3979, "MMMCMXCIX": 3999,
} }
func TestFromInt(t *testing.T) { func TestIntToString(t *testing.T) {
for expected, input := range testCases { for expected, input := range testCases {
out, err := FromInt(input) out, err := IntToString(input)
if err != nil { if err != nil {
t.Errorf("FromInt(%d) returned an error %s", input, err.Error()) t.Errorf("IntToString(%d) returned an error %s", input, err.Error())
} }
if out != expected { if out != expected {
t.Errorf("FromInt(%d) = %s; want %s", input, out, expected) t.Errorf("IntToString(%d) = %s; want %s", input, out, expected)
} }
} }
_, err := FromInt(100000) _, err := IntToString(100000)
if err == nil { if err == nil {
t.Errorf("FromInt(%d) expected an error", 100000) t.Errorf("IntToString(%d) expected an error", 100000)
} }
_, err = FromInt(0) _, err = IntToString(0)
if err == nil { if err == nil {
t.Errorf("FromInt(%d) expected an error", 0) t.Errorf("IntToString(%d) expected an error", 0)
} }
} }
func TestToInt(t *testing.T) { func TestStringToInt(t *testing.T) {
for input, expected := range testCases { for input, expected := range testCases {
out, err := ToInt(input) out, err := StringToInt(input)
if err != nil { if err != nil {
t.Errorf("ToInt(%s) returned an error %s", input, err.Error()) t.Errorf("StringToInt(%s) returned an error %s", input, err.Error())
} }
if out != expected { if out != expected {
t.Errorf("ToInt(%s) = %d; want %d", input, out, expected) t.Errorf("StringToInt(%s) = %d; want %d", input, out, expected)
} }
} }
_, err := ToInt("IVCMXCIX") _, err := StringToInt("IVCMXCIX")
if err == nil { if err == nil {
t.Error("ToInt(IVCMXCIX) expected an error") t.Error("StringToInt(IVCMXCIX) expected an error")
} }
val, err := ToInt("") val, err := StringToInt("")
if val != 0 { if val != 0 {
t.Errorf("ToInt(\"\") = %d; want 0", val) t.Errorf("StringToInt(\"\") = %d; want 0", val)
} }
if err != nil { if err != nil {
t.Errorf("ToInt(\"\") returned an error %s", err.Error()) t.Errorf("StringToInt(\"\") returned an error %s", err.Error())
} }
} }
func BenchmarkToRomanNumeral(b *testing.B) { func TestBytesToInt(t *testing.T) {
for input, expected := range testCases {
out, err := BytesToInt([]byte(input))
if err != nil {
t.Errorf("StringToInt(%s) returned an error %s", input, err.Error())
}
if out != expected {
t.Errorf("StringToInt(%s) = %d; want %d", input, out, expected)
}
}
_, err := BytesToInt([]byte("IVCMXCIX"))
if err == nil {
t.Error("BytesToInt(IVCMXCIX) expected an error")
}
var in []byte
val, err := BytesToInt(in)
if val != 0 {
t.Errorf("BytesToInt(nil) = %d; want 0", val)
}
if err != nil {
t.Errorf("BytesToInt(nil) returned an error %s", err.Error())
}
in = []byte("")
val, err = BytesToInt(in)
if val != 0 {
t.Errorf("BytesToInt([]byte(\"\")) = %d; want 0", val)
}
if err != nil {
t.Errorf("BytesToInt([]byte(\"\")) returned an error %s", err.Error())
}
}
func BenchmarkIntToString(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_, _ = FromInt(2999) _, _ = IntToString(3999)
} }
} }
func BenchmarkToInteger(b *testing.B) { func BenchmarkStringToInt(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_, _ = ToInt("DCCCXLIX") _, _ = StringToInt("MMMCMXCIX")
} }
} }
func ExampleToInt() { func BenchmarkBytesToInt(b *testing.B) {
integer, err := ToInt("IV") b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = BytesToInt([]byte("MMMCMXCIX"))
}
}
func ExampleStringToInt() {
integer, err := StringToInt("IV")
if err != nil { if err != nil {
panic(err) panic(err)
} }
fmt.Println(integer == 4) fmt.Println(integer == 4)
} }
func ExampleFromInt() { func ExampleIntToString() {
roman, err := FromInt(4) roman, err := IntToString(4)
if err != nil { if err != nil {
panic(err) panic(err)
} }