Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何拥有唯一的随机数?_Java_Random - Fatal编程技术网

Java 如何拥有唯一的随机数?

Java 如何拥有唯一的随机数?,java,random,Java,Random,这就是我如何在1到6之间生成一个唯一的no,并从drawable文件夹中获取适当的图像 Random rand = new Random(); // n = the number of images, that start at idx 1 rndInt = rand.nextInt(6) + 1; String imgName = "card" + rndInt; int id = getResources().getIdentifier(imgName, "drawable", getPa

这就是我如何在1到6之间生成一个唯一的no,并从drawable文件夹中获取适当的图像

Random rand = new Random();
// n = the number of images, that start at idx 1
rndInt = rand.nextInt(6) + 1; 
String imgName = "card" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);

我想要的是,我必须调用这个方法7次,每次这个方法都应该返回一个唯一的随机编号,这样已经选择的数字就不会再出现了。

解决这类问题的通常方法是创建一个包含每个可能值的列表并将其洗牌(使用)。然后,每次需要一个值时,都会使用列表中的一项。这将确保您不会多次使用相同的值,但仍然允许随机顺序。

解决此类问题的通常方法是创建一个包含每个可能值的列表,并将其洗牌(使用)。然后,每次需要一个值时,都会使用列表中的一项。这将确保您不会多次使用相同的值,但仍然允许随机顺序。

创建一个静态列表,列出您已经获得的可能性

static ArrayList<int> listIdontWantAnymore = new ArrayList<int>();

int NextRandomNumber() {
    Random random = new Random();
    int myRandomInt;

    do {
        myRandomInt = random.NextInt(6) + 1;
    } while(listIdontWantAnymore.Contains(myRandomInt));

    listIdontWantAnymore.Add(myRandomInt);

    // now your 'myRandomInt' is what you want it to be.
    return myRandomInt;
}
static ArrayList listidontwantanimore=new ArrayList();
int NextRandomNumber(){
随机=新随机();
int-myRandomInt;
做{
myRandomInt=random.NextInt(6)+1;
}而(listidontwantanimore.Contains(myRandomInt));
添加(myRandomInt);
//现在你的“myRandomInt”就是你想要的。
返回myRandomInt;
}

创建一个静态列表,列出您已经获得的可能性

static ArrayList<int> listIdontWantAnymore = new ArrayList<int>();

int NextRandomNumber() {
    Random random = new Random();
    int myRandomInt;

    do {
        myRandomInt = random.NextInt(6) + 1;
    } while(listIdontWantAnymore.Contains(myRandomInt));

    listIdontWantAnymore.Add(myRandomInt);

    // now your 'myRandomInt' is what you want it to be.
    return myRandomInt;
}
static ArrayList listidontwantanimore=new ArrayList();
int NextRandomNumber(){
随机=新随机();
int-myRandomInt;
做{
myRandomInt=random.NextInt(6)+1;
}而(listidontwantanimore.Contains(myRandomInt));
添加(myRandomInt);
//现在你的“myRandomInt”就是你想要的。
返回myRandomInt;
}

下面是一个示例类,它使用Dan Dyer建议的方法创建一个随机排列。它确保每次.next()调用都会给出一个新的数字,最大为构造函数中给定的数字。之后,它环绕并再次给出相同的序列。 这对于洗牌播放列表很有用

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomPermutation{
    private List<Integer> list;
    private int index;

    /**
     * Create a random permutation the sequence of numbers 0, 1, ... , n - 1.
     * @param n Range specifier, must be positive
     */
    public RandomPermutation(int n) {
        if (n <= 1) {
            throw new IllegalArgumentException(
                    "Positive number expected, got: " + n);
        }
        list = new ArrayList<Integer>();
        newList(n);
    }

    /**
     * Creates a new list
     */
    public void newList(int n) {
        index = -1;
        list.clear();
        for (int i = 0; i < n; i++) {
            list.add(i);
        }
        Collections.shuffle(list);
    }

    /**
     * Retrieve the next integer in sequence. 
     */
    public int next() {
        index = (index + 1) % list.size();
        return list.get(index);
    }
}

下面是一个示例类,它使用Dan Dyer建议的方法创建一个随机排列。它确保每次.next()调用都会给出一个新的数字,最大为构造函数中给定的数字。之后,它环绕并再次给出相同的序列。 这对于洗牌播放列表很有用

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomPermutation{
    private List<Integer> list;
    private int index;

    /**
     * Create a random permutation the sequence of numbers 0, 1, ... , n - 1.
     * @param n Range specifier, must be positive
     */
    public RandomPermutation(int n) {
        if (n <= 1) {
            throw new IllegalArgumentException(
                    "Positive number expected, got: " + n);
        }
        list = new ArrayList<Integer>();
        newList(n);
    }

    /**
     * Creates a new list
     */
    public void newList(int n) {
        index = -1;
        list.clear();
        for (int i = 0; i < n; i++) {
            list.add(i);
        }
        Collections.shuffle(list);
    }

    /**
     * Retrieve the next integer in sequence. 
     */
    public int next() {
        index = (index + 1) % list.size();
        return list.get(index);
    }
}

对于您的特定用例,这应该可以做到

Random rand = new Random();
// n = the number of images
List<String> imgNames = new ArrayList<String>(n);
for (int i = 0; i < n; i++) { 
    imgNames.add("card" + (i + 1)) 
}
while (!imageNames.isEmpty()) {
    String imgName = imgNames.remove(rand.next(imageNames.size());
    int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
    imgView.setImageResource(id);
}
Random rand=new Random();
//n=图像的数量
列表imgNames=newarraylist(n);
对于(int i=0;i
注意,当
n
变大时,此操作不能很好地扩展。对于
ArrayList
LinkedList
,删除操作是
O(n)
。但是对于成百上千的
n
,这与加载和显示图像相比可能微不足道


此外,正如评论所指出的,“唯一随机数”在术语上是矛盾的。您所追求的是一组数字从
1
n
的随机排列。我的解决方案不需要显式的“洗牌”就可以做到这一点步骤,这对于您的用例来说已经足够了。

对于您的特定用例,这应该可以做到

Random rand = new Random();
// n = the number of images
List<String> imgNames = new ArrayList<String>(n);
for (int i = 0; i < n; i++) { 
    imgNames.add("card" + (i + 1)) 
}
while (!imageNames.isEmpty()) {
    String imgName = imgNames.remove(rand.next(imageNames.size());
    int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
    imgView.setImageResource(id);
}
Random rand=new Random();
//n=图像的数量
列表imgNames=newarraylist(n);
对于(int i=0;i
注意,当
n
变大时,此操作不能很好地扩展。对于
ArrayList
LinkedList
,删除操作是
O(n)
。但是对于成百上千的
n
,这与加载和显示图像相比可能微不足道


此外,正如评论所指出的,“唯一随机数”在术语上是矛盾的。您所追求的是一组数字从
1
n
的随机排列。我的解决方案不需要显式的“洗牌”就可以做到这一点步骤,这对于您的用例来说已经足够了。

生成一个包含您将使用的每个数字的数字列表。(这很好,因为我们讨论的是一个小范围,其中“N”是“小于1000的某个地方”)

当您选择一个数字时,请选择一个介于0和sizeof(列表)之间的随机索引,该数字将成为该列表的索引

删除该列表索引并返回编号


(对于读者来说,这是一个确定什么类型的“列表”在这里是合适的练习。)

生成一个包含您将使用的每个数字的数字列表。(这很好,因为我们讨论的是一个小范围,其中“N”是“小于1000的某个地方”)

当您选择一个数字时,请选择一个介于0和sizeof(列表)之间的随机索引,该数字将成为该列表的索引

删除该列表索引并返回编号


(对于读者来说,这是一个确定什么类型的“列表”在这里是合适的练习。)

使用具有适当选择参数的a。

使用具有适当选择参数的a。

以下是最简单的代码,可以执行此操作并将其存储到数组中,无需重复:

Random rand = new Random();
int[] ar;
ar = new int[5];

int random = 0;
int [] result_arr=new int[5];
boolean flag=false;

for(int i=0;i<5;i++)
{  
    ar[i]=0;

    do{
        random =rand.nextInt(10);
        flag=false;
        for(int j=0;j<i;j++)
        {
            if(ar[j]==random)
            flag=true;
        }
        if(!flag)
        {
            ar[i]=random;
            break;
        }
     }
     while(true) ;
}
Random rand=new Random();
int[]ar;
ar=新整数[5];
int随机=0;
int[]结果_arr=新的int[5];
布尔标志=假;

对于(int i=0;i,下面是最简单的代码,可以在不重复的情况下将其存储到数组中:

Random rand = new Random();
int[] ar;
ar = new int[5];

int random = 0;
int [] result_arr=new int[5];
boolean flag=false;

for(int i=0;i<5;i++)
{  
    ar[i]=0;

    do{
        random =rand.nextInt(10);
        flag=false;
        for(int j=0;j<i;j++)
        {
            if(ar[j]==random)
            flag=true;
        }
        if(!flag)
        {
            ar[i]=random;
            break;
        }
     }
     while(true) ;
}
Random rand=new Random();
int[]ar;
ar=新整数[5];
内特拉