summaryrefslogtreecommitdiff
path: root/roman.go
diff options
context:
space:
mode:
Diffstat (limited to 'roman.go')
-rw-r--r--roman.go28
1 files changed, 20 insertions, 8 deletions
diff --git a/roman.go b/roman.go
index d1d382f..f57e655 100644
--- a/roman.go
+++ b/roman.go
@@ -1,23 +1,35 @@
// Package roman numerals
+//
+// For fluff, the unicode overbar is recognized as a factor of 1000.
+//
+// If you see boxes in the code below, those are supposed to be the
+// Unicode combining overline (U+0305) and look like I̅V̅X̅L̅C̅D̅M̅. Or, if
+// you see overstruck combinations of letters, that's a different font
+// rendering problem. (If you need roman numerals > 3999 reliably, it
+// might best to stick to chiseling them in stone...)
+//
+// Source: https://www.rosettacode.org/wiki/Roman_numerals/Encode#Go
package roman
var (
m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
- m3 = []string{"", "M", "MM", "MMM"}
+ m3 = []string{"", "M", "MM", "MMM", "I̅V̅", "V̅", "V̅I̅", "V̅I̅I̅", "V̅I̅I̅I̅", "I̅X̅"}
+ m4 = []string{"", "X̅", "X̅X̅", "X̅X̅X̅", "X̅L̅", "L̅", "L̅X̅", "L̅X̅X̅", "L̅X̅X̅X̅", "X̅C̅"}
+ m5 = []string{"", "C̅", "C̅C̅", "C̅C̅C̅", "C̅D̅", "D̅", "D̅C̅", "D̅C̅C̅", "D̅C̅C̅C̅", "C̅M̅"}
+ m6 = []string{"", "M̅", "M̅M̅", "M̅M̅M̅"}
)
-// Roman numeral in interval 0 < x < 4000
+// Roman represents a roman numeral in interval 0 < x < 4e6
type Roman int
-func (n Roman) Valid() bool {
- return n > 0 && n < 4000
-}
-
func (n Roman) String() string {
- if !n.Valid() {
+ if n <= 0 || n >= 4e6 {
return ""
}
- return m3[n/1000] + m2[n%1000/100] + m1[n%100/10] + m0[n%10]
+ // this is efficient in Go. the seven operands are evaluated,
+ // then a single allocation is made of the exact size needed for the result.
+ return m6[n/1e6] + m5[n%1e6/1e5] + m4[n%1e5/1e4] + m3[n%1e4/1e3] +
+ m2[n%1e3/1e2] + m1[n%1e2/1e1] + m0[n%1e1]
}