繁体   English   中英

数组JAVA中的非重复随机数

[英]Non-repeating random numbers inside array JAVA

我想在一个数组内同时生成6个数字,将其进行比较,这样它就不会相同或没有重复数字。 例如,我想以任何顺序生成1-2-3-4-5-6,最重要的是不重复。 所以我想的是逐个比较生成的数组中的当前数组,如果数字重复,它将重新运行该方法并再次随机化一个数字,这样就可以避免重复数字。

这是我的代码:

import javax.swing.*;
public class NonRepeat
{
    public static void main(String args[])
    {
        int Array[] = new int [6];
        int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
        while(login != 0)
        {
            String output="";

            for(int index = 0; index<6; index++)
            {
                Array[index] = numGen();

                for(int loop = 0; loop <6 ; loop++)
                {
                    if(Array[index] == Array[loop])
                    {
                        Array[index] = numGen();
                    }
                }


            }

            for(int index = 0; index<6; index++)
            {
                output += Array[index] + " ";
            }


            JOptionPane.showMessageDialog(null, output);

        }



    }

    public static int numGen()
    {
        int random = (int)(1+Math.random()*6);
        return random;
    }
}

我已经思考了2个小时,仍然无法重复生成6个数字。 希望我的问题能得到解答。

顺便说一句,我是代码的新手,所以我只想使用for循环或while循环以及if else

您可以从1到6生成数字(请参阅下面的另一个解决方案)然后执行Collections.shuffle来重新排列您的数字。

    final List<Integer> l = new ArrayList<Integer>();
    for (int j = 1; j < 7; j++ ) {
        l.add( j );
    }
    Collections.shuffle( l );

通过这样做,你最终得到一个从1到6的数字的随机列表,而没有两倍相同的数字。

如果我们分解解决方案,首先你有这个,这真的只是创建一个包含六个数字的列表:

    final List<Integer> l = new ArrayList<Integer>();
    for (int j = 1; j < 7; j++ ) {
        l.add( j );
    }

因此,在这一点上,您已经有了在问题中提到的列表1-2-3-4-5-6。 您可以确保这些数字不重复。

然后,您只需将每个元素与另一个元素交换至少一次,即可随机整理/随机化该列表。 这就是Collections.shuffle方法的作用。

您建议的解决方案不会非常有效:根据您的数字列表的大小和范围,您可能很有可能重复数字。 在这种情况下,不断重新尝试生成新列表将会很慢。 此外,任何其他建议检查列表是否已包含数字以防止重复或使用集合的解决方案如果你有一个很长的连续数字列表(比如从1到100 000的10万个数字列表)将会变慢:你不断尝试随机生成尚未生成的数字,随着数字列表的增长,你会遇到越来越多的冲突。

如果您不想使用Collections.shuffle (例如用于学习目的),您可能仍然想要使用相同的想法:首先通过确保没有任何重复项来创建数字列表,然后执行for循环随机交换列表中的两个元素。 您可能希望查看Collections.shuffle方法的源代码,该方法以正确的方式进行随机播放。

编辑尚不清楚您的“随机数”的属性是什么。 如果您不希望它们从1递增到6,则可以执行以下操作:

final Random r = new Random();
final List<Integer> l = new ArrayList<Integer>();
for (int j = 0; j < 6; j++ ) {
    final int prev = j == 0 ? 0 : l.get(l.size() - 1);
    l.add( prev + 1 + r.nextInt(42) );
}
Collections.shuffle( l );

请注意,通过将r.nextInt(42)更改为r.nextInt(1)您将有效地获得从1到6的非重复数字。

您必须检查该号码是否已存在,您可以通过将您的号码放入List轻松完成,因此您可以访问该方法contains 如果你坚持使用数组,那么你可以创建一个循环来检查数字是否已经在数组中。

使用ArrayList

ArrayList numbers = new ArrayList();

while(numbers.size() < 6) {
    int random = numGen(); //this is your method to return a random int

    if(!numbers.contains(random))
        numbers.add(random);
}

使用数组:

    int[] numbers = new int[6];

    for (int i = 0; i < numbers.length; i++) {
        int random = 0;

        /*
         * This line executes an empty while until numGen returns a number
         * that is not in the array numbers yet, and assigns it to random
         */
        while (contains(numbers, random = numGen()))
            ;


        numbers[i] = random;
    }

并在上面的代码段中使用此方法添加此方法

private static boolean contains(int[] numbers, int num) {
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] == num) {
            return true;
        }
    }
    return false;
}

使用List而不是array和List#contains来检查数字是否重复。

这是根据您的代码的解决方案-

您只需要更改numGen方法-

public static int numGen(int Array[])
{

    int random = (int)(1+Math.random()*6);

    for(int loop = 0; loop <Array.length ; loop++)
    {
        if(Array[loop] == random)
        {
            return numGen(Array);
        } 
    }


    return random;
}

完整的代码是 -

import javax.swing.*;
public class NonRepeat
{
    public static void main(String args[])
    {

        int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
        while(login != 0)
        {
            int Array[] = new int [6];
            String output="";

            for(int index = 0; index<6; index++)
            {
                Array[index] = numGen(Array);


            }

            for(int index = 0; index<6; index++)
            {
                output += Array[index] + " ";
            }


            JOptionPane.showMessageDialog(null, output);

        }



    }

    public static int numGen(int Array[])
    {

        int random = (int)(1+Math.random()*6);

        for(int loop = 0; loop <Array.length ; loop++)
        {
            if(Array[loop] == random)
            {
                return numGen(Array);
            } 
        }


        return random;
    }
}

您可以在while循环中使用布尔值来标识重复项并重新生成

int[] array = new int[10]; // array of length 10

Random rand = new Random(); 

    for (int i = 0 ; i < array.length ; i ++ ) {

        array[i] = rand.nextInt(20)+1;  // random 1-20

        boolean found = true;

        while (found) { 

        found = false; 
  // if we do not find true throughout the loop it will break (no duplicates)

         int check = array[i]; // check for duplicate 

             for (int j = 0 ; j < i ; j ++) {

                 if ( array[j] == check ) {

                 found = true; // found duplicate                   
                 }
             }          

              if (found) {  
                    array[i] = rand.nextInt(20)+1 ;   // replace    
              }
        }
    }

System.out.println(Arrays.toString(array));

使用List和.contains(Object obj)方法。 因此,您可以验证列表中是否添加了随机数。

更新-根据时间,您可能会陷入随机循环。

    List<Integer> list = new ArrayList<Integer>();
    int x = 1;
    while(x < 7){

                list.add(x);
                x++;
    }
    Collections.shuffle(list);

    for (Integer number : list) {
        System.out.println(number);
    }

http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)

您可以使用java.util.Random 请说明您是否需要任何随机数或仅需1,2,3,4,5,6号。 如果您希望随机数,那么这是一个基本代码:

import java.util.*;
public class randomnumber
{
    public static void main(String[] args)
    {
        Random abc = new Random();
        int[] a = new int[6];
        int limit = 100,c=0;
        int chk = 0;
        boolean y = true;
        for(;c < 6;)
        {
            int x = abc.nextInt(limit+1);
            for(int i = 0;i<a.length;i++)
            {
                if(x==a[i])
                {
                    y=false;
                    break;
                }
            }
            if(y)
            {
                if(c!=0)if(x == (a[c-1]+1))continue;
                a[c]=x;
                c++;
            }
        }

        for (Integer number : a) 
        {
            System.out.println(number);
        }
    }
}

如果您不理解最后一个for循环,请告诉我,我会更新它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM