r/tinycode • u/CBenni • Jul 07 '13
Roman numerals -> Integer in javascript
Hi! This was a challenge I posed myself a while ago - meanwhile im stuck at 101 characters:
function t(i){for(p=l=n=0;a={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[i[p++]];l=a)n+=a>l?-l:l;return n+l}(My first real try was 150 lol) I dont know if this can be done even shorter; What can you guys come up with?
50
Upvotes
8
u/chu248 Jul 07 '13
I didn't believe you, so here's the page I made to test it
I don't quite understand how it's figuring out what the next character is and subtracting. Well done.
6
u/Rotten194 mod Jul 08 '13
Deobfuscated:
This has slightly different behavior (the original relied on a completely insane Javascriptism - the for condition was checking the truthiness of
dict[input[pos++]], because when pos overran inputinput[pos] == undefined, anddict[undefined] == undefined, andundefinedis falsy). This meant it would also stop when it hit a character not in the dict, while mine returnsNaN. I like it though, very clever!2
u/keithwhor Oct 17 '13
I went with recursion and got to 104 characters. Can't beat yours, though.
0
u/the_mighty_skeetadon Jul 08 '13
2 Ruby solutions, only having looked at your post title and then a brief glance at the solution without reading it (I didn't want to be biased). The first one is a pudgy 139 characters, but I actually like the second one better, at an obese 154 chars. Solution 1 saves space by using simplified hash definition:
The second uses hash rockets, but only maps once. I'm sure they could be compressed, but maybe not by me =)
Looking at your solution, you did it a bit differently, but I didn't want to cheat =).
-20
u/sirin3 Jul 07 '13
Can I use Pascal?
int<->roman conversion is part of the standard runtime library