没有重复的java随机生成器 [英] java random generator without repeat

查看:177
本文介绍了没有重复的java随机生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用随机生成器生成2d数组.基本上,每列都应包含1-50之间的随机值,该值不能重复,但问题是,我无法在同一行或程序中的任何其他行或列上获得重复值.换句话说,每个I整数只能显示一次.我的对象是通过链接列表创建的,一旦我弄清楚了,我可能会在其中整合算法,但是现在,这就是我所做的.

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);

我的输出:

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 

所以我的问题是这个.如何在不重复值的情况下实现随机生成.通常,我现在会尝试收集列表,但是我尝试使用java.util.Random做到这一点.就个人而言,我会以不同的方式进行此操作,但需要指示.谢谢

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-50的ArrayList,然后在列表上使用Collections.shuffle.

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

这篇关于没有重复的java随机生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆