给定一个固定长度的int数组,找到最小的数字,然后添加并返回剩余数字的总和

1 java arrays int

这不是功课.我正在设计一个RPG,对于能力分数,我正在滚动4d6,删除最低滚动,然后添加剩余总数.我的内容如下,如果有人有任何其他更好的建议,我只是好奇.为简洁起见,我删除了滚动操作,我只插入了四个整数.

int[] rolls = { 6, 3, 2, 5 };
int abilityScore = rolls[0] + rolls[1] + rolls[2] + rolls[3];
int low = rolls[0];

for (int i = 1; i < rolls.length; i++)
{
    if (rolls[i] < low)
    {
        low = rolls[i];
    }
}

return abilityScore -= low;
Run Code Online (Sandbox Code Playgroud)

sch*_*der 5

我会这样做 - 不需要数组并在循环内计算总和:

int get_total_without_lowest_roll(int roll_count) {
  int abilityScore = 0;
  int low = MAX_INTEGER;
  int roll;
  for (int i = 0; i < roll_count; i++)
  {
    roll = roll_dice(); // Roll your dice here
    if (roll < low)
    {
        low = roll;     
    } // By the way, good alternative would be low = min(low,roll);
    abilityScore += roll;
  }

  return (abilityScore - low);
}
Run Code Online (Sandbox Code Playgroud)