如何检查、移除和替换数组列表中的重复值?

huangapple go评论78阅读模式
英文:

How to check, remove and replace duplicate values inside an Array List?

问题

我想生成5个随机数,如果该数字已存在,则移除它并替换为新数字。重复此过程,直到生成的所有数字都是唯一的。然而,我卡住了,因为我的数组中仍然包含重复值。

import java.util.Random;
import java.util.ArrayList;

public class Question2_NEW
{
    public static void main (String[] args)
    {
        System.out.println("生成5个从0到5的随机数...");

        Random rand = new Random();
        int generate = rand.nextInt((5) + 1);
        ArrayList<Integer> randomNumbers = new ArrayList<Integer>();
        
        for (int i = 0; i < 5; i++)
        {
            generate = rand.nextInt((5) + 1);
            randomNumbers.add(generate);

            while (randomNumbers.contains(generate)) 
            {
                randomNumbers.remove(randomNumbers.get(i));
                generate = rand.nextInt((5) + 1);
                randomNumbers.add(generate);
                break;
            }
        }

        for (Integer i : randomNumbers) 
        {
            System.out.println(i);
        }
    }
}
英文:

I would like to generate 5 random numbers and if the number already exists, remove it and replace it with a new one. Repeating the process until all the numbers generated are unique. However, I am stuck as I keep getting duplicate values inside my array.

import java.util.Random;
import java.util.ArrayList;

public class Question2_NEW
{
    public static void main (String[] args)
    {
        System.out.println(&quot;Generating 5 random numbers from 0 to 5...&quot;);

        Random rand = new Random();
        int generate = rand.nextInt((5) + 1);
        ArrayList&lt;Integer&gt; randomNumbers = new ArrayList&lt;Integer&gt;();
        
        for (int i = 0; i &lt; 5; i++)
        {
            generate = rand.nextInt((5) + 1);
            randomNumbers.add(generate);

            while (randomNumbers.contains(generate)) 
            {
                randomNumbers.remove(randomNumbers.get(i));
                generate = rand.nextInt((5) + 1);
                randomNumbers.add(generate);
                break;
            }
        }

        for (Integer i : randomNumbers) 
        {
            System.out.println(i);
        }
    }
}

答案1

得分: 0

这是因为,在while循环内,您没有检查替换的数字是否已经在ArrayList中。它被接受而不受质疑。

更好的解决方案是在添加之前检查数字是否有效:

for (int i = 0; i < 5; i++)
{
    generate = rand.nextInt((5) + 1);
    while (randomNumbers.contains(generate)) 
    {
        generate = rand.nextInt((5) + 1);
    }
    randomNumbers.add(generate);
}

请注意,有更高效的算法可以完成这个任务。首先,使用HashSet进行成员检查速度更快。其次,如果您只想生成1到N的随机排列,那么Fisher-Yates洗牌算法是无可争议的最佳解决方案。对于仅包含5个数字的情况,可能无关紧要。

英文:

This happens because, inside the while loop, you are not checking that the replacement number isn't also already in the ArrayList. It is simply accepted without question.

A better solution is to check whether the number is valid before you add it:

    for (int i = 0; i &lt; 5; i++)
    {
        generate = rand.nextInt((5) + 1);
        while (randomNumbers.contains(generate)) 
        {
            generate = rand.nextInt((5) + 1);
        }
        randomNumbers.add(generate);
    }

Note that there are more efficient algorithms for this task. For one, membership checking is faster with a HashSet. For another, if you just want to generate a random permutation of the numbers 1 through N, a Fisher-Yates shuffle is the undisputed best solution. For something as tiny as 5 numbers, it probably doesn't matter though.

答案2

得分: 0

翻译后的代码如下:

// 在你的代码中编写并调用此方法。
private boolean arrayListIncludes(Integer i, ArrayList<Integer> randomNumbers) {
    for (int x = 0; x < randomNumbers.size(); x++) {
        if (randomNumbers.get(i).intValue() == i.intValue()) {
            return true;
        }
    }
    return false;
}
英文:

Write and call this method in your code.

private boolean arrayListIncludes(Integer i, ArrayList&lt;Integer&gt; randomNumbers) {
    for(int x = 0; x&lt;randomNumbers.size(); x++) {
         if(randomNumbers.get(i).intValue() == i.intValue()) {
               return true;
         }
    }
    return false;
}

答案3

得分: 0

以下是您要翻译的内容:

如果您想使用List,我会建议以下代码:

    public static void main(String[] args) {
        System.out.println("生成 0 到 5 之间的 5 个随机数...");

        Random rand = new Random();
        int generate;
        List<Integer> randomNumbers = new ArrayList<Integer>();

        for (int i = 0; i <= 5; i++) {
            do {
                generate = rand.nextInt(6);
            } while (randomNumbers.contains(generate));

            randomNumbers.add(generate);
        }

        for (Integer i : randomNumbers) {
            System.out.println(i);
        }
    }

如果您还可以使用Set:

    public static void main(String[] args) {
        System.out.println("生成 0 到 5 之间的 5 个随机数...");

        Random rand = new Random();
        Set<Integer> randomNumbers = new HashSet<Integer>();

        while (randomNumbers.size() <= 5) {
            randomNumbers.add(rand.nextInt(6));
        }

        for (Integer i : randomNumbers) {
            System.out.println(i);
        }
    }

编辑:修复了Set/ArrayList长度的问题。

英文:

If you want to use List I would the following:

    public static void main(String[] args) {
        System.out.println(&quot;Generating 5 random numbers from 0 to 5...&quot;);

        Random rand = new Random();
        int generate;
        List&lt;Integer&gt; randomNumbers = new ArrayList&lt;Integer&gt;();

        for (int i = 0; i &lt;= 5; i++) {
            do {
                generate = rand.nextInt((5) + 1);
            } while (randomNumbers.contains(generate));

            randomNumbers.add(generate);
        }

        for (Integer i : randomNumbers) {
            System.out.println(i);
        }
    }

If you can also use sets:

    public static void main(String[] args) {
        System.out.println(&quot;Generating 5 random numbers from 0 to 5...&quot;);

        Random rand = new Random();
        Set&lt;Integer&gt; randomNumbers = new HashSet&lt;Integer&gt;();

        while (randomNumbers.size() &lt;= 5) {
            randomNumbers.add(rand.nextInt((5) + 1));
        }

        for (Integer i : randomNumbers) {
            System.out.println(i);
        }
    }

Edit: fixed issue with length of Set/ArrayList

huangapple
  • 本文由 发表于 2020年8月6日 01:31:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63270540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定