如何从一个整数数组中随机选择一个元素,并移除所选元素

4

我想从一个数组中随机选择一个元素进行打印,然后将其从数组中删除,以避免重复打印相同的数字。由于我是Java的新手,所以想知道是否有人能指出我的错误所在。

public static void main(String[] args) {
    int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
    Random rand = new Random();

    for (int i = 0; i < 5; i++)
        System.out.println(" " + colm[rand.nextInt(colm.length)]);

}

thanks


你不想打印两次相同的数字,因此每次你都需要减少创建的随机数的范围。 - Kraken
此外,在你选择数字后,你没有从数组中删除它。你只是在控制台上打印它。 - Kraken
既然我们不住在洞穴里,也不穿人类的皮,所以请不要使用Array。祝好! - Kraken
5个回答

5

随机数并不能保证唯一性。你可以使用以下方法代替。

public static void main(String[] args) {
    int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
    List l = new ArrayList();
    for(int i: colm)
        l.add(i);

    Collections.shuffle(l);

    for (int i = 0; i < 5; i++)
        System.out.println(l.get(i));

}

1
比其他的更优雅,但你没有删除元素。我说得对吗? - Gabrer
1
@Gabrer。是的,我没有删除它。因为尽管标题要求从数组中删除,但 OP 的主要目标是避免打印重复条目。 - stinepike
1
好的!我明白了。但实际上,我选择了谷歌上的这个答案,因为标题中有“remove”字眼。如果您愿意改进答案,那就由您决定(不过,它只需要调用“remove()”方法即可)。 - Gabrer

3
您缺少删除部分。尝试以下代码:

您需要添加删除部分。请尝试以下代码:

public static void main(String[] args)
{
    Integer [] colm = {1,2,3,4,5,67,87};
    final List<Integer> ints = new ArrayList<Integer>(Arrays.asList(colm));
    Random rand =  new Random();

    for(int i = 0; (i<5) && (ints.size() > 0); i ++) {
        final int randomIndex = rand.nextInt(ints.size());
        System.out.println(" " +  ints.get(randomIndex));
        ints.remove(randomIndex);
    }
}

如果您将列表用作最终变量,它将抛出异常。 - Arjit
异常不是由于final引起的,Arrays.asList(colm)创建了固定大小的列表,不支持删除,已经修复 :) - enterbios

0
你最好使用Set或Map来保存数据,然后创建属于集合/映射长度的随机数,并使用该(随机)索引进行删除。

1
集合和映射没有索引。使用列表更为恰当。 - JB Nizet
也许楼主是为了练习而这样做,因此为他的代码提供答案会很好。 - Lukas Warsitz

0
public static void removeElements(int[] arr) {
        Random random = new Random();

        List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

        int length = arr.length;
        while (length > 0) {

            System.out.println("Size: " + list.size());
            if (list.size() == 1) {
                int randomIndex = random.nextInt(list.size());
                list.remove(randomIndex);
                System.out.println("Size:--> " + list.size());
                break;
            }else {
                int randomIndex = random.nextInt(list.size() - 1);
                if (arr == null || randomIndex > arr.length) {
                    System.out.println("No Elements to be deleted");
                }
                list.remove(randomIndex);
                System.out.println("Removed Element: " + list.get(randomIndex));
                length--;

                if (length == 0)
                    break;

            }
        }

    }

0
public static void main(String[] args) {
int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
List l = new ArrayList();
for(int i: colm)
    l.add(i);

Collections.shuffle(l);

for (int i = 0; i < 5; i++)
    System.out.println(l.get(i));

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接