有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在将重复项添加到数组之前识别重复项

我正在尝试编写一个程序,它由一个数组组成,数组中填充了50个随机数,数值介于1-999之间。但是,在向数组中添加随机数之前,我必须检查该数字是否重复,并且是否已经在数组中

我似乎非常接近正确的输出,但是出于某种原因,我反复将数字0作为数组中的第一个元素,它也是唯一被复制的数字。有人知道这是为什么吗?如果有,能提供一个合适的解决方案吗

一旦发现重复项,就需要将其打印到输出中,并替换为一个新的唯一随机数

提前谢谢

import java.util.*;
public class Random50 {
public static void main (String[] args)
{
    final int MAX_SIZE = 50;
    int[] r50 = new int[MAX_SIZE];
    boolean duplicates = false;

    Random rand = new Random();

    for (int i=0; i<r50.length; i++)
    {   
        for (int j=i+1;j<r50.length;j++)
        {
            r50[i] = rand.nextInt(1000);

            if (j!=i && r50[i] == r50[j])
            {
                duplicates = true;
                System.out.println("DUPE: " + r50[i]);
                r50[i] = rand.nextInt(1000);
            }

        }
    }

    System.out.println(Arrays.toString(r50));
}

}


共 (2) 个答案

  1. # 1 楼答案

    j总是大于i,因为将j初始化为i+1。这意味着被j引用的r50的值总是0,所以这些值总是重复的

    例如,如果i=20,在第二个循环中,j将从21开始。r50[21],r50[22]等。。。都是0,因为还没有设置它们,所以r50[i]和r50[j]唯一可能的副本是0

    编辑:如果j的点是遍历数组中所有前面的元素,那么您需要

       for (int i=0; i<r50.length; i++)
        {   
            r50[i] = rand.nextInt(1000); //Set it before the j loop
            for (int j = 0; j < i; j++)
            {
                while (r50[i] == r50[j]) //while loop, in case of multiple duplicates
                {
                    duplicates = true;  //Still not sure why you want this boolean
                    System.out.println("DUPE: " + r50[i]);
                    r50[i] = rand.nextInt(1000);
                }
        }
    }
    

    尽管这仍然不能完美地工作,因为您可能会在检查后将r50设置为更早的值。例如,如果确保r50[20]不等于j到10的任何值,然后它等于r50[11](当j=11时),则可能会意外地将其更改回小于该值的j值(例如,r50[5])

    我认为最整洁的方式是,就像邓肯和拉吉夫一样

    HashSet numbers = new HashSet();
    Random rand = new Random();
    
    while(numbers.size() < MAX_SIZE) {
        numbers.add(rand.nextInt(1000));
    }
    
  2. # 2 楼答案

    就性能而言,这并不是一个好方法,因为每次都要将一个值与数组的下一个位置进行比较。您应该使用散列算法,通过该算法,您可以根据对象的唯一散列码知道对象可能位于哪一点,然后进入图片HashSet,对于大多数操作,该图片具有O(1),这在Integer类对象中发生散列码冲突的可能性非常小

    public static void main (String[] args)
    {
        final int MAX_SIZE = 50;
    
        HashSet<Integer> hs = new HashSet<Integer>(50);
    
         while(hs.size()<50){
    
            Random rand = new Random();
            int randomVal = rand.nextInt(1000);
            hs.add(randomVal);
        }
       Integer[] r50 = hs.toArray();
    }