java random generator without repeat

好久不见. 提交于 2019-12-12 03:56:05

问题


Im trying to generate a 2d array using a random generator. basically, each column should contain a random value between 1-50 that is not repeated but the problem is, I can't get a repeat value on the same row, or any other row or column in the program. In other words, each I integer should only display once. My objects were created via linked list and I will probably integrate the algorthim in there once I figure it out but for now, heres what I did.

int[] array = new int[50];



        for(int i=1;i<=9;i++)
        {

        int[] grades = new int[5];
            for(int j=0;j<=4;j++)
            {

            int unique = gen.nextInt(50)+1;


            grades[j] = unique; 
            }
            list.add(new Student(i, grades));

        }

        System.out.println(list);

My output:

Student1: 20 49 45 16 13 
Student2: 28 10 11 30 6 
Student3: 13 25 37 31 49 
Student4: 8 23 8 12 32 
Student5: 22 18 35 2 7 
Student6: 35 8 16 23 36 
Student7: 35 3 15 42 2 
Student8: 43 12 44 2 35 
Student9: 12 21 36 23 12 

So my issue is this. How can I implement the random gen without repeating values. Normally I would try a collection list by now, but I'm trying to do this using java.util.Random Personally, I would do this a different way but I'm instructed. Thank you


回答1:


Here's what I would do:

Take an ArrayList of numbers 1-50, then use Collections.shuffle on the list.




回答2:


You could check if the number is unique before accepting it. For example you could try something like the following:

int count=0;
List<Integer> list=new ArrayList<Integer>();
    while(count<50){
        int num=random.nextInt(50);
            if(!list.contains(num)){
                list.add(num);
                ++count;  
            }                    
    }


来源:https://stackoverflow.com/questions/16284894/java-random-generator-without-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!