Skip to content

Instantly share code, notes, and snippets.

@yanxi-me

yanxi-me/gist:8754172

Last active Aug 29, 2015
Embed
What would you like to do?
4张牌算24
/*
* Author: <yanxi@yanxi.com>
* $ curl https://gist.github.com/yanxi-com/8754172/raw/gistfile1.js > 24.js
* $ npm install underscore
* $ node 24.js 8 8 9 7
*/
var _ = require('underscore');
function add(a, b) {
return a+b;
};
function minus(a, b) {
return Math.abs(a-b);
};
function multi(a, b) {
return a*b;
};
function divide(a, b) {
return Math.max(a,b)/Math.min(a,b);
};
var ops = [add, minus, multi, divide];
var name = ['+', '-', '*', '/'];
var nums = _.map(process.argv.slice(2, 6), function(num){return parseInt(num)});
var _2 = function(a, b) {
var results = [];
for (var i in ops) {
var how = a[1] + '(' + Math.max(a[0],b) + name[i] + Math.min(a[0],b) + ')';
results.push([ops[i](a[0],b), how]);
}
return results;
};
var _3 = function(a, b, c) {
var result = [];
_.each(_2([a, ''],b), function(ab) {
result = result.concat(_2(ab, c))
});
_.each(_2([a, ''],c), function(ab) {
result = result.concat(_2(ab, b))
});
_.each(_2([c, ''],b), function(ab) {
result = result.concat(_2(ab, a))
});
return result;
}
var _4 = function(a,b,c,d) {
var result = [];
_.each(_3(a,b,c), function(ab) {
result = result.concat(_2(ab, d))
});
_.each(_3(a,b,d), function(ab) {
result = result.concat(_2(ab, c))
});
_.each(_3(d,b,c), function(ab) {
result = result.concat(_2(ab, a))
});
_.each(_3(a,c,d), function(ab) {
result = result.concat(_2(ab, b))
});
return result;
}
var results = _.uniq(_4(nums[0],nums[1],nums[2],nums[3]), false, function(result){
return result[1];
});
_.each(results, function(result){
if (result[0]>23.99 && result[0]<24.01) {
console.log(result[1] + '=' + result[0]);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment