-
-
Save nabetani/5900931 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){ | |
function slicer( balls ){ | |
var used=0; | |
return { | |
take:function(i){ | |
var r = balls.slice( used, used+i ); | |
used+=i; | |
return r; | |
}, | |
take_with_sum:function(i){ | |
var r = this.take(i); | |
return _.extend( r, { sum:sum(r) } ); | |
}, | |
}; | |
} | |
var s=slicer( balls ); | |
var right = s.take_with_sum(3); | |
var left = s.take_with_sum(3); | |
if( left.sum == right.sum ){ | |
// 3, 3が釣り合ったら残り2つで比べる | |
return comp( s.take(2) ); | |
} | |
// 右(左)の方が重ければ右(左)から1つずつ取り出して比べる | |
return comp( left.sum < right.sum ? right : left ); | |
function sum(ball_array){ | |
return _.reduce(ball_array, function(memo, num){ return memo + num.w; }, 0); | |
}; | |
function comp(targets){ | |
return _.max(targets, function( i ){ return i.w; } ).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