Last active
August 19, 2019 10:00
-
-
Save Cycymomo/6053345 to your computer and use it in GitHub Desktop.
140bytes - romanize (arabic to roman) http://www.developpez.net/forums/d1362763/webmasters-developpement-web/javascript/ludique-defis-code-en-tweet/
This file contains hidden or 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
// 140bytes - http://www.developpez.net/forums/d1362763/webmasters-developpement-web/javascript/ludique-defis-code-en-tweet/ | |
/* 98b: */ | |
function romanize(n,a,b,c,d){ | |
for(a='',b=0,c=5;n;b++,c^=7)for(d=n%c,n=n/c^0;d--;a='IVXLCDM'[d>2?b+n-(n&=-2)+(d=1):b]+a);return a | |
} | |
/* Explain */ | |
function romanize(n){ | |
for(a='', // final string | |
b=0, // IVXLCDM[b] | |
c=5; // we have to start to divide by 5 | |
n; // while n not falsy (equals 0), divided by 5, and 2, and 5, etc ... | |
b++, | |
c^=7) { // c^=7 equals 2, and then, next cycle, c^=7 will be 5, etc | |
console.log('d='+(n%c)+'/n='+(n/c^0)); | |
for(d=n%c, // store the rest. never be more than 4 | |
n=n/c^0; // divide by 5 or 2 and then round to floor => this is like n=Math.floor(n/c) or n=~~(n/c) | |
d--;) { // while n not falsy (equals 0) | |
console.log('n='+n+'/m='+(n&~1)+'/a='+a+'/b='+b+'/c='+c+'/d='+d+'/x='+(1+(d>2?b+n-(n&-2)+1:b))); | |
a='IVXLCDM'[d>2? // for the 4's or 9's | |
b+ // handle the 5ish, 10ish, 50ish, etc | |
n-(n&=-2) // add 1 or 0 and transform n to the even number just below | |
// n-(n&=-2) equals 0 if n is even et 1 if not. | |
// because if n equals 9 we have to handle the next 5ish : example IX | |
// whereas if n equals 4 we are in the right 5ish : example IV | |
// if n is event, (n&-2) === n. if not (n&-2) === n-1 | |
+(d=1) // one turn left (example : IV if 4, IX if 9, XC if 90) | |
:b]+a; // for the others cases, repeat the letter until "d" | |
} | |
} | |
return a; | |
} |
This file contains hidden or 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
console.log( romanize(12) + ' / ' + (romanize(12) === "XII") ); | |
console.log( romanize(49) + ' / ' + (romanize(49) === "XLIX") ); | |
console.log( romanize(74) + ' / ' + (romanize(74) === "LXXIV") ); | |
console.log( romanize(383) + ' / ' + (romanize(383) === "CCCLXXXIII")); | |
console.log( romanize(1000) + ' / ' + (romanize(1000) === "M")); | |
console.log( romanize(3888) + ' / ' + (romanize(3888) === "MMMDCCCLXXXVIII")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment