gpt4 book ai didi

java - 从android中的xml文件中随机生成问题并且不重复

转载 作者:行者123 更新时间:2023-12-02 07:59:08 25 4
gpt4 key购买 nike

我有一个 xml 文件,其中包含 50 个不同的问题,我只需要其中的 15 个随机且不重复的问题。我使用了下面的代码

int n = ((int)(Math.random()*100))%50;
if(temp<15)
{
for(int i=0;i<temp;i++)
{
System.out.println("hello naresh");
if(n==check[i])
{
n=((int)(Math.random()*100))%50;
}
}
check[temp]=n;
}

temp++;
return n;

但是通过使用这个,一些问题会重复。请建议我一些可以帮助我生成不重复问题的东西。

最佳答案

将数字 0,1,...49 打乱并取出前 15 个数字:

ArrayList<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < 50; i++)
indices.add(i);

Collections.shuffle(indices);
List<Integer> random15 = indices.subList(0,15);

它还会对其他 35 个数字进行洗牌,这是一些不必要的工作,但对于这么小的数字来说,这不是问题。

关于java - 从android中的xml文件中随机生成问题并且不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9156313/

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