gpt4 book ai didi

java - 调试游戏逻辑

转载 作者:行者123 更新时间:2023-12-01 18:16:02 24 4
gpt4 key购买 nike

规范-

In the game the children sit in a circle and one person outside the ring (the leader) sings a song with a fixed number of words. Moving clockwise around the circle, the leader points to a new child in the ring for each word in the song. The child being pointed to on the last word of the song is out and must leave the circle. The leader then repeats the process with the smaller circle. The game continues until the last child is eliminated. This child is then the leader to start the next game.

我几乎已经弄清楚了这个逻辑,但是有一个错误,我在数组索引中找不到某个位置,在该位置我将当前元素添加到另一个数组(以显示被消除的 child ),然后删除它们从当前数组。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Practice {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter number of kids: ");
int kidCount = sc.nextInt();
List<Integer> kids = new ArrayList<Integer>();
List<Integer> rejects = new ArrayList<Integer>();

System.out.println("Enter number of words in the song: ");
int words = sc.nextInt();

int wordCount = 0;

for (int i = 1; i <= kidCount; i++) {
kids.add(i);
}

for (int i = 0; i < kids.size(); i++) {
wordCount++;

if (wordCount % words == 0) {
rejects.add(kids.get(i));
kids.remove(kids.get(i));

}

if (i == kids.size() - 1) {
if (wordCount % words != 0) {
i = 0;
} else {
rejects.add(kids.get(i));
kids.remove(kids.get(i));
}
}
}
System.out.println(rejects.toString());
}
}

预期输出(如果有 6 个 child 和 3 个单词):3 6 4 2 5 1

当前输出:[3, 2, 4, 6]

最佳答案

你循环遍历 child 的方式是有缺陷的。您“循环”的方式将始终跳过 child 1,因为您在执行 i++ 之前立即设置了 i=0。此外,如果您上次删除了 child ,例如 child 5,您将立即删除最后一个 child ,例如kids 6,因为 kids 数组的大小已更改,并且您有第二个删除子句。另外,删除最后一个 child 后,即使还有更多 child ,循环也会立即退出,因为它没有在 else 中设置 i=0 for列表末尾。

一般来说,您应该避免使用 for 来对计数器造成如此大的干扰。 for 应该代表单次传递。您想要完成的是循环,并进行就地删除。事实上,您的主要错误是 for 的条件,因为它不是对您想要的 child 进行迭代,而是循环直到只剩下一个 child 。

更简洁的实现是:

int i = 0;
while (kids.size() > 1) { // Loop until we have a winner
wordCount++; // Give the kid a word
if (wordCount >= words) { // It's the last word, he's out
rejects.add(kids.remove(i)); // Remove the kid at index i and place it into rejects
// P.S. Small issue with ArrayList API: If your object type is Integer, then there's ambiguity between remove(T) and remove(int), which will prevent auto boxing from being used
wordCount = 0; // And from the top
}
else {
i++; // This kid is okay, move to the next
// P.S. If we removed the kid, we're already pointing at the next one, hence the "else"
}
if (i >= kids.size()) { // Reached the end of the kids list
i = 0; // Loop around
}
}

关于java - 调试游戏逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447057/

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