aboutsummaryrefslogtreecommitdiff
path: root/challenge-010/zapwai/javascript/ch-1.js
blob: e5912564271326164e639f611dc2fc54f3010a15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
let r = ["I", "V", "X", "L", "C", "D", "M"];
let v = [1, 5, 10, 50, 100, 500, 1000];

function roman(c) {
    for (let i = 0; i < r.length; i++) 
        if (r[i] == c) 
            return v[i];
}

let basic = [ "IIII", "VIIII", "XXXX", "LXXXX", "CCCC", "DCCCC" ];
let modern = [ "IV", "IX", "XL", "XC", "CD", "CM" ];

function convert_from_roman(s) {
    console.log("Input:",s);
    for (let i = 0; i < basic.length; i++) {
        let key = modern[i];
        let val = basic[i];
        s = s.replace(key, val);
    }
    let sum = 0;
    for (let c of s)
        sum += roman(c);
    console.log("Output:", sum);
}

function convert_to_roman(num) {
    console.log("Input:", num);
    let ans = "";
    let stack = [];
    for (let i = 0; i < r.length; i++) 
        if (num >= v[i])
	    stack.push(v[i]);
    let i = stack.length - 1
    while (i >= 0) {
        let x = stack.pop();
        let d = Math.floor(num/x);
        for (let j = 0; j < d; j++)
            ans += r[i];
        num -= d*x;
        i -= 1;
    }
    for (let j = 0; j < basic.length; j++) {
        key = basic[basic.length - 1 - j];
        val = modern[basic.length - 1 - j];
        ans = ans.replace(key, val);
    }
    console.log("Output:", ans);
}
convert_from_roman("CCXLVI");
convert_to_roman(39);