題目連結
https://www.codewars.com/kata/5270d0d18625160ada0000e4/train/javascript
解法
function score(dice) {
let score = 0
const map = {}
for (let num of dice) {
map[num] = (map[num] || 0) + 1
}
for (let i = 1; i <= 6; i++) {
if (map[i] >= 3) {
if (i === 1) {
score += 1000
} else {
score += i * 100
}
map[i] -= 3
}
}
score += (map[1] || 0) * 100
score += (map[5] || 0) * 50
return score
}
筆記
計算5顆6面骰子的分數
使用object來記錄數字出現的次數
//example
map = {
1: 1
2: 2
...
6: 0
}
for of
將dice裡面的資料做一次迭代
如果沒有出現過 就會在map{}裡面建立並+1
for (let num of dice) {
map[num] = (map[num] || 0) + 1
}