检查随机生成的数组位置是否相同

Check if Array Positions produced by random are the same

我做了一个命令,selects 来自二维数组的随机位置

int[][] nums= {{1,2,3},
            {2,3,4},
            {5,6,7}};

for(int i = 0; i < 5; i++) {
        int num = nums[rand.nextInt(4)][rand.nextInt(4)];
        System.out.println(num);
    }

我怎样才能确保当 int num selects 第一次出现时, 它再也无法 select 了吗? 使5个随机数互不相同

如果您需要它从您的 2d table 中选择每个数字一次,这将起作用。 我创建了另一个列表,它描述了 table 中的可用位置。然后在我们使用它们时,将它们从可用位置列表中删除。因为您使用的是二维数组,所以我使用的是点 class.

需要进口

import java.util.*;
import java.awt.*;
        Random rand = new Random();
        int[][] nums= {{1,2,3},
                    {4,5,6},
                    {7,8,9},
                    {10,11,12}};
        
        ArrayList<Point> availableLocations = new ArrayList<Point>();
        for(int i = 0;i<nums.length*nums[0].length ;i++) availableLocations.add( new Point(i%nums[0].length,i/nums[0].length ));
        
        for(int i = 0; i < 12; i++) {
            int randomIndex = rand.nextInt(availableLocations.size());
            Point location = availableLocations.get(randomIndex);
            
            int num = nums[location.y][location.x];
            System.out.println(num);
            
            availableLocations.remove(randomIndex);
        }