Created
January 29, 2018 14:13
-
-
Save honzabrecka/ccb4a36ba34d63fb740975fcdaab358b to your computer and use it in GitHub Desktop.
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
const template = (i, v, x) => ({ | |
0: '', | |
1: `${i}`, | |
2: `${i}${i}`, | |
3: `${i}${i}${i}`, | |
4: `${i}${v}`, | |
5: `${v}`, | |
6: `${v}${i}`, | |
7: `${v}${i}${i}`, | |
8: `${v}${i}${i}${i}`, | |
9: `${i}${x}`, | |
10: `${x}`, | |
}) | |
const ranges = { | |
1: ['I', 'V', 'X'], | |
2: ['X', 'L', 'C'], | |
3: ['C', 'D', 'M'], | |
} | |
const to = (n) => { | |
const $ = (r, n, c) => { | |
const cc = Math.pow(10, c - 1) | |
const m = n % cc | |
const x = (n - m) / cc | |
const res = r + (c === 4 ? Array.from({ length: x }, _ => 'M').join('') : template.apply(null, ranges[c])[x]) | |
return c === 1 ? res : $(res, m, c - 1) | |
} | |
return $('', n, Math.min((n + '').length, 4)) | |
} | |
const dictFrom = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000, | |
} | |
const from = (n) => { | |
return n.split('').reduce(([res, p1, p2], char) => { | |
const m = dictFrom[char] | |
if (!m) throw new Error('Invalid input.') | |
if (p1 < m && p2 < m) throw new Error('Invalid input.') | |
return [res + (p1 < m ? m - 2 * p1 : m), m, p1] | |
}, [0, 1000, 1000])[0] | |
} | |
// console.log(from('MMMIXF')) | |
// console.log(g(2)) | |
// console.log(g(58)) | |
// console.log(g(346)) | |
// console.log(g(1666)) | |
// console.log(g(2008)) | |
// console.log(g(9000)) | |
const { forAll, generators } = require('rapid-check') | |
const prop = (n) => console.log(n, to(n), from(to(n))) || from(to(n)) === n | |
console.log(forAll(generators.fmap((n) => n + 1, generators.uint), prop, 10000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment