Last active
December 19, 2015 00:09
-
-
Save torazuka/5866966 to your computer and use it in GitHub Desktop.
This file contains 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
var _ = require("./lib/underscore-min.js"); | |
exports.Ball = function(i, w){ | |
return {i: i, w: w}; | |
}; | |
exports.solve = function(balls){ | |
// 3, 3, 2ずつ取り出して比べる | |
var right = balls.slice(0, 3); | |
var left = balls.slice(3, 6); | |
var other = balls.slice(6, 8); | |
if(sum(left) === sum(right)){ | |
// 3, 3が釣り合ったら残り2つで比べる | |
return other[0].w < other[1].w ? other[1].i : other[0].i; | |
} | |
// 右(左)の方が重ければ右(左)から1つずつ取り出して比べる | |
if(sum(left) < sum(right)){ | |
return comp(right); | |
} else { | |
return comp(left); | |
} | |
function sum(ball_array){ | |
return _.reduce(ball_array, function(memo, num){ return memo + num.w; }, 0); | |
}; | |
function comp(targets){ | |
if(targets[0].w === targets[1].w){ | |
return targets[2].i; | |
} | |
return targets[0].w < targets[1].w ? targets[1].i : targets[0].i; | |
}; | |
}; |
This file contains 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
var assert = require('assert'); | |
var gb = require("./googleBall.js"); | |
describe('8つのボールから1つだけ重いボールのインデックスを返す', function(){ | |
it('重いボールが先頭にある場合', function(){ | |
var Ball = gb.Ball; | |
var answer = gb.solve([Ball(0, 7), Ball(1, 5), Ball(2, 5), Ball(3, 5), Ball(4, 5), Ball(5, 5), Ball(6, 5), Ball(7, 5)]); | |
assert(answer === 0); | |
}) | |
it('重いボールが中央付近にある場合', function(){ | |
var Ball = gb.Ball; | |
var answer = gb.solve([Ball(0, 5), Ball(1, 5), Ball(2, 5), Ball(3, 5), Ball(4, 7), Ball(5, 5), Ball(6, 5), Ball(7, 5)]); | |
assert(answer === 4); | |
}) | |
it('重いボールが末尾にある場合', function(){ | |
var Ball = gb.Ball; | |
var answer = gb.solve([Ball(0, 5), Ball(1, 5), Ball(2, 5), Ball(3, 5), Ball(4, 5), Ball(5, 5), Ball(6, 5), Ball(7, 7)]); | |
assert(answer === 7); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment