繁体   English   中英

生成范围 (0-4) 内的随机数,并限制每个数字只能生成一定次数?

[英]Generating random numbers in a range (0-4) with the constraint that each number can only be generated a certain amount of times?

我需要为 function 生成随机数 output,称为 randomize。 我正在尝试生成 0 到 4 范围内的数字。但是,

  • 一旦产生2次0,就停止产生0, blankCount计数0代
  • 一旦1生成4次,停止生成1, birdCount计数1代
  • 一旦2生成1次,就停止生成2, specialCount计数2代
  • 一旦3生成2次,就停止生成3, nullCount统计3代
  • 一旦生成1次4,就停止生成4, crashCount计数4代

我在数组中为这个 function 的 output 设置了一个位置。function 在帖子的末尾。 问题是让 function 停止调用自己。 我收到此代码的堆栈溢出错误。

目标是有两个 0、四个 1、一个 2、两个 3 和一个 4

0,0,1,1,1,1,2,3,3,4

任何人都可以帮助使这个 function 工作吗?

int blankCount = 0;
int birdCount = 0;
int specialCount = 0;
int nullCount = 0;
int crashCount = 0;

int randomize(){
  int num = 0;
  int randomNum = floor(random(0,5));
  
  if(randomNum == 0 && blankCount <= 1) {
    blankCount++;
    num = randomNum;
  }else if(randomNum == 0 && blankCount == 2){
    num = randomize();
  }else if(randomNum == 1 && birdCount <= 3){
    birdCount++;
    num = randomNum;
  }else if(randomNum == 1 && birdCount == 4){
    num = randomize();
  }else if(randomNum == 2 && specialCount <= 0){
    specialCount++;
    num = randomNum;
  }else if(randomNum == 2 && specialCount == 1){
    num = randomize();
  }else if(randomNum == 3 && nullCount <= 1){
    nullCount++;
    num = randomNum;
  }else if(randomNum == 3 && nullCount == 2){
    num = randomize();
  }else if(randomNum == 4 && crashCount <= 0){
    crashCount++;
    num = randomNum;
  }else if(randomNum == 4 && crashCount == 1){
    num = randomize();
  }else{
    print("H ");
  }
  return num;
}

首先制作一个清单,其中包含您可以合法退回的所有物品。

然后,洗牌。

然后,要生成一个随机数,只需从您的洗牌列表中消费下一个项目。 瞧 - 现在,如果您不想超过 4x a 1 ,请确保原始列表中最多只有 4 1值。

我不知道你的random(0, 5)做了什么,但是用它来生成随机数听起来像是被设计破坏了(鸽子洞原理) - java 有一个 Random class 和一个更好的 API 没有被破坏,通过一切都意味着使用它。

class Randomizer {
    private static final List<Integer> INPUTS = List.of(0, 0, 1, 1, 1, 1, 2, 3, 3, 4);

    private final List<Integer> list;
    private int pos = 0;

    public Randomizer() {
        list = new ArrayList<Integer>(INPUTS);
        Collections.shuffle(list);
    }

    public int next() {
        return list.get(pos++);
    }
}

注意:一旦你“用完”了随机数,上面的代码就会抛出IndexOutOfBoundsException 如果您想要其他行为,请将其编码。例如,如果您希望算法重新开始(以随机顺序重新返回 0/0/1/1/1/1/2/3/3/4,重新新鲜的订单),那么你可以做,说:

public int next() {
    if (pos == list.size()) {
        Collections.shuffle(list); // reshuffle
        pos = 0;
    }
    return list.get(pos++);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM