Skip to content

Instantly share code, notes, and snippets.

@Snack-X
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Snack-X/25ea3baec5f026476419 to your computer and use it in GitHub Desktop.
Save Snack-X/25ea3baec5f026476419 to your computer and use it in GitHub Desktop.
Convert number to aheui expression
/**
* TODO
* optimize algorithm
* support negative numbers
*/
var readline = require("readline");
var rl = readline.createInterface({input: process.stdin, output: process.stdout, terminal: false});
var cho = {"+": 3, "*": 4, "-": 16, "/": 2, ">": 8};
var jong = [0, 0, 1, 7, 16, 8, 18, 9, 15, 10];
function han_assemble(cho, jung, jong) {
return String.fromCharCode(0xac00 + (((cho * 21) + jung) * 28) + jong);
}
function try_dis(num) {
for(var i=2 ; i<=9 ; i++) {
var nr = Math.floor(num / i);
var diff = nr * i - num;
if(Math.abs(diff) >= 2 && Math.abs(diff) <= 9)
return get_expr(nr).concat([i, "*", Math.abs(diff), diff > 0 ? "-" : "+"]);
else if(i * nr === num)
return get_expr(nr).concat([i, "*"]);
}
}
function try_sqrt(num) {
var rt = Math.floor(Math.sqrt(num));
var remainder = num - rt * rt;
var exp_plus = get_expr(rt).concat(">", "*", get_expr(remainder), "+");
rt = Math.ceil(Math.sqrt(num));
remainder = rt * rt - num;
var exp_minus = get_expr(rt).concat(">", "*", get_expr(remainder), "-");
return exp_plus.length < exp_minus.length ? exp_plus : exp_minus;
}
function get_basic(num) {
if(num === 0)
return [2, 2, "-"];
else if(num === 1)
return [2, 2, "/"];
else if(num >= 2 && num <= 9)
return [num];
else if(num >= 10 && num <= 18) {
var n1 = Math.ceil(num / 2);
var n2 = num - n1;
return [n1, n2, "+"];
}
}
function get_expr(num) {
if(num <= 18) return get_basic(num);
for(var i=2 ; i<=9 ; i++) {
var nr = Math.floor(num / i);
if(nr >= 2 && nr <= 9 && nr * i === num)
return [i, nr, "*"];
}
var rt = Math.sqrt(num);
if(Math.floor(rt) === rt)
return get_expr(rt).concat([">", "*"]);
var arr_dis = try_dis(num);
var arr_sqrt = try_sqrt(num);
return arr_dis.length < arr_sqrt.length ? arr_dis : arr_sqrt;
}
function get_aheui_expression(num) {
if(num < 0) {
console.log("not supported");
return [];
}
if(num <= 18) return get_basic(num);
var exp = get_expr(num);
for(var i=2 ; i<=9 ; i++) {
var temp = get_expr(num - i).concat([i, "+"]);
if(temp.length < exp.length) exp = temp.slice(0);
temp = get_expr(num + i).concat([i, "-"]);
if(temp.length < exp.length) exp = temp.slice(0);
}
return exp;
}
rl.on("line", function(input) {
var num = parseInt(input, 10);
var expr = get_aheui_expression(num);
var expr_str = expr.join(" ");
var output = "";
for(var i in expr) {
var v = expr[i];
if(typeof v === "number") output += han_assemble(7, 0, jong[v]);
else output += han_assemble(cho[v], 0, 0);
}
console.log(num + " = " + expr_str);
console.log(output);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment