骰子游戏算分算法

有一个骰子游戏,共有5个骰子,随机扔,然后算出总分,下面是点数对应得分值:

得分值

31=1000
36=600
35=500
34=400
33=300
32=200
11=100
15=50

例子

 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

算法1(推荐)

function score( dice ) {
  var dc = [0,0,0,0,0,0];
  var tdr = [1000,200,300,400,500,600];
  var sdr = [100,0,0,0,50,0];
  dice.forEach(function(x){ dc[x-1]++; });
  return dc.reduce(function(s,x,i){ 
    return s + (x >= 3? tdr[i] : 0) + sdr[i]*(x % 3);
  },0);
}

算法2(一般)

function score( dice ) {
  if (dice.length != 5) return 0;
  var scoreTable = {
    "3_1": 1000,
    "3_6": 600,
    "3_5": 500,
    "3_4": 400,
    "3_3": 300,
    "3_2": 200,
    "2_1": 200,
    "2_5": 100,
    "1_1": 100,
    "1_5": 50
  };
  var c = [0,0,0,0,0,0,0];
  for (var i = 0; i < dice.length; i++) {
    c[dice[i]]++;
  }
  ret = cnt = 0;
  for (var i = 1; i < c.length; i++) {
    cnt = c[i];
    var idx = cnt;
    if (cnt > 3) {
      idx = 3;
      if (scoreTable[(cnt-3)+"_"+i]) ret += scoreTable[(cnt-3)+"_"+i];
    }
    if (scoreTable[idx+"_"+i]) {
      ret += scoreTable[idx+"_"+i];
    }
  }
  console.log(dice);
  console.log(ret);
  return ret;
}