gpt4 book ai didi

java - 随机生成1和0作为队列

转载 作者:行者123 更新时间:2023-12-01 09:29:44 26 4
gpt4 key购买 nike

我希望我的程序随机生成 1 和 0,但它应该看起来像在队列中。 1代表有人,0代表没有人。它应该像这样生成随机 1 和 0 0 0 0 0 1 1 1 1 1 1 ,如果该线位于左侧​​,则反之亦然,如果该线位于右侧,则不是这样 1 1 1 0 0 1 0 0 1 1

public void randPeople(){
int person1 = rand.nextInt((1 - 0) + 1) + 0;
int person2 = rand.nextInt((1 - 0) + 1) + 0;
int person3 = rand.nextInt((1 - 0) + 1) + 0;
int person4 = rand.nextInt((1 - 0) + 1) + 0;
int person5 = rand.nextInt((1 - 0) + 1) + 0;
int person6 = rand.nextInt((1 - 0) + 1) + 0;
int person7 = rand.nextInt((1 - 0) + 1) + 0;
int person8 = rand.nextInt((1 - 0) + 1) + 0;
int person9 = rand.nextInt((1 - 0) + 1) + 0;
int person10 = rand.nextInt((1 - 0) + 1) + 0;

EntryFloor1.setText(Integer.toString(person1) + " " + Integer.toString(person2) + " " +
Integer.toString(person3) + " " + Integer.toString(person4) + " " +
Integer.toString(person5) + " " + Integer.toString(person6) + " " +
Integer.toString(person7) + " " + Integer.toString(person8) + " " +
Integer.toString(person9) + " " + Integer.toString(person10));
}

最佳答案

实现了一个简单的随机函数来生成 0 和 1

    int[] queue = new int[10];
Random r = new Random();
int rand = r.nextInt(queue.length);
int r1 = 1 - rand % 2;
int r2 = rand % 2;
for (int i = 0; i < queue.length; i++) {
if (i <= rand) {
queue[i] = r1;
} else {
queue[i] = r2;
}
}
System.out.println("Queue " + Arrays.toString(queue));

输出

Queue [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]

使用 Java8 生成器

    final int size = 10;
final Random random = new Random();
boolean order = random.nextBoolean();
Object[] arr = IntStream.generate(() -> random.nextInt(size) % 2).limit(size).boxed().sorted((i1, i2) -> order ? i1 - i2 : i2 - i1).toArray();
System.out.println("Arrays " + Arrays.toString(arr));

输出

Arrays [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

关于java - 随机生成1和0作为队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com