Skip to content

Instantly share code, notes, and snippets.

@H2CO3
Last active December 26, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save H2CO3/7075911 to your computer and use it in GitHub Desktop.
Save H2CO3/7075911 to your computer and use it in GitHub Desktop.
Sparkling demo: solution to Project Euler problem #89
/*
* Created by Árpád Goretity on 21/10/2013
*
* Sparkling demo: solution to Project Euler problem #89
* (http://projecteuler.net/problem=89)
*
* For demonstration purposes only -- please don't abuse or cheat.
*/
function int2roman(r)
{
var s = "";
var nums = array(
1000,
900,
500,
400,
100,
90,
50,
40,
10,
9,
5,
4,
1
);
var strs = array(
"M",
"CM",
"D",
"CD",
"C",
"XC",
"L",
"XL",
"X",
"IX",
"V",
"IV",
"I"
);
var i;
for i = 0; i < sizeof nums; i++ {
while r >= nums[i] {
s ..= strs[i];
r -= nums[i];
}
}
return s;
}
function roman2int(s)
{
if sizeof s == 0 {
return 0;
}
var chars = array('I', 'V', 'X', 'L', 'C', 'D', 'M');
var nums = array(1, 5, 10, 50, 100, 500, 1000);
var i;
for i = 0; i < sizeof chars; i += 2 {
if s[0] == chars[i] {
if sizeof s == 1 {
return nums[i];
} else if s[1] == chars[i + 1] {
return nums[i + 1] - nums[i] + roman2int(substrfrom(s, 2));
} else if s[1] == chars[i + 2] {
return nums[i + 2] - nums[i] + roman2int(substrfrom(s, 2));
} else {
return nums[i] + roman2int(substrfrom(s, 1));
}
} else if s[0] == chars[i + 1] {
return nums[i + 1] + roman2int(substrfrom(s, 1));
}
}
print("invalid character in Roman numeral");
exit(-1);
}
var f = fopen("/Users/h2co3/Projects/ProjectEuler/roman.txt", "r");
var line, longlen = 0, shortlen = 0;
while (line = fgetline(f)) != nil {
/* remove newline, if any */
if line[-1] == '\n' {
line = substrto(line, sizeof line - 1);
}
longlen += sizeof line;
var compact = int2roman(roman2int(line));
shortlen += sizeof compact;
print(line, " = ", compact);
}
fclose(f);
print("long: ", longlen, "; short: ", shortlen, "; diff: ", longlen - shortlen);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment