DAY31:Greed is Good


Posted by birdbirdmurmur on 2023-08-13

題目連結

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
  }

#javascript #Codewars #for...of #object







Related Posts

[FE102] 前端必備:JavaScript (上)

[FE102] 前端必備:JavaScript (上)

JS review

JS review

JS Project - Drum Kit

JS Project - Drum Kit


Comments