gpt4 book ai didi

java - 检查数组是否包含某些整数

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

我正在创建一个 10 个整数长的数组,因此 0-9 的每个位置都包含不同的整数 0-9。

我无法弄清楚如何检查数组是否已包含某个数字,如果是,则重新生成一个新的数字。

到目前为止我已经:

for (int i = 0; i < perm.length; i++)
{
int num = (int) (Math.random() * 9);
int []

perm[i] = num;
}

最佳答案

Arrays.asList(perm).contains(num) 

来自How can I test if an array contains a certain value?

for (int i = 0; i < perm.length; i++)

这样循环还不够,如果发生冲突,一些插槽将不会被初始化。

总体,对于此任务,您最好按顺序使用值初始化数组,然后 shuffle通过使用随机排列索引来实现

关于java - 检查数组是否包含某些整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13789109/

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