Skip to content

Instantly share code, notes, and snippets.

@udonchan
Last active December 26, 2015 07:49
Show Gist options
  • Save udonchan/7117544 to your computer and use it in GitHub Desktop.
Save udonchan/7117544 to your computer and use it in GitHub Desktop.
ボーリングのスコアを求める。初めはリストっぽい感じで書き始めたが1時間くらいで限界を迎えてしかたなく手続きっぽく書いた。
var processer = function(s){
var score = current = i = 0
,tokens = s.split('').map(function(t){return (t==='-')?'0':t});
for(;;i++){
if(/^\d$/.test(tokens[i])){
if(!/\/|\d$/.test(tokens[++i])){
throw new Error("Invalid Input");
}
score += tokens[i] === '/' ? 10 + (tokens[i+1]==='X'?10:parseInt(tokens[i+1])) : parseInt(tokens[i]) + parseInt(tokens[i-1]);
} else if(tokens[i] === 'X'){
switch(tokens[i+2]){
case '/':
score += 20;
break;
case 'X':
score += 30;
break;
default:
score += 10 + ((tokens[i+1]==='X') ? 10:parseInt(tokens[i+1])) + parseInt(tokens[i+2]);
break;
}
} else {
throw new Error("Invalid Input");
}
if(++current == 9){
++i;
break;
}
}
if(tokens[i+2] === undefined ||
(/^X$/.test(tokens[i]) || (/\X|\//.test(tokens[i+1])) && tokens[i+3] === undefined)){
for(;i<tokens.length;i++){
score += tokens[i] === 'X'?10:tokens[i] === '/'?10-parseInt(tokens[i-1]):parseInt(tokens[i]);
}
return score;
}
throw new Error("Invalid Input");
};
var printTest = function(testCase, result){
var actual = processer(testCase);
console.log('test case : ' + testCase + ' ' +
(actual === result ? 'success' : 'failed should : ' + result + ' actual : ' + actual));
};
[["--------------------", 0],
["9-9-9-9-9-9-9-9-9-9-", 90],
["X54----------------", 28],
["1/5-----------------", 20],
["1/5-2/-/8-----------", 56],
["------XX----------", 30],
["------XXX--------", 60],
["XXXXXXXXXXXX", 300],
["-------------------/5", 15],
["------------------X54", 19],
["5/5/5/5/5/5/5/5/5/5/5", 150]].forEach(function(a){
printTest.apply(null, a);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment