Greed is Good

题目

Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values.

1
2
3
4
5
6
7
8
Three 1's => 1000 points
Three 6's => 600 points
Three 5's => 500 points
Three 4's => 400 points
Three 3's => 300 points
Three 2's => 200 points
One 1 => 100 points
One 5 => 50 point

A single die can only be counted once in each roll. For example, a “5” can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll.

Example scoring

1
2
3
4
5
Throw       Score
--------- ------------------
5 1 3 4 1 50 + 2 * 100 = 250
1 1 1 3 1 1000 + 100 = 1100
2 4 4 5 4 400 + 50 = 450

In some languages, it is possible to mutate the input to the function. This is something that you should never do. If you mutate the input, you will not be able to pass all the tests.

思路

别的不会,就会强上……菜的可以啊……

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function score (dice) {
let arrDiceCount = [0, 0, 0, 0, 0, 0]
let score = 0
for (let i in dice) {
switch (dice[i]) {
case 1:
arrDiceCount[0] += 1
break
case 2:
arrDiceCount[1] += 1
break
case 3:
arrDiceCount[2] += 1
break
case 4:
arrDiceCount[3] += 1
break
case 5:
arrDiceCount[4] += 1
break
case 6:
arrDiceCount[5] += 1
break
}
}
if (arrDiceCount[1] > 2) {
score += 200
}
if (arrDiceCount[2] > 2) {
score += 300
}
if (arrDiceCount[3] > 2) {
score += 400
}
if (arrDiceCount[5] > 2) {
score += 600
}
if (arrDiceCount[0] >= 3) {
score += 1000
arrDiceCount[0] -= 3
}
while (arrDiceCount[0] > 0) {
score += 100
arrDiceCount[0] -= 1
}
if (arrDiceCount[4] >= 3) {
score += 500
arrDiceCount[4] -= 3
}
while (arrDiceCount[4] > 0) {
score += 50
arrDiceCount[4] -= 1
}
console.log(dice)
console.log(score)
return score
}

简单优化一下

第一次填充骰子个数数组的时候可以用forEach()简化

1
2
3
dice.forEach(function (n) {
arrDiceCount[n - 1]++
})