如何防止重叠的随机数 [英] How can I prevent the overlapping random numbers

查看:170
本文介绍了如何防止重叠的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何防止从随机数中复制数字。
我需要在1到9之间生成5个不同的数字。
我经常会得到像23334这样的数字,我该如何防止?
任何帮助都会很棒!

How would i prevent duplicating numbers from random numbers. I need to generate 5 numbers between 1 and 9 that are each different. I would often get same numbers like 23334, how can i prevent that? Any help would be great!

    int num2 = (int) Math.round((Math.random()*9) +1);
    int num1 = (int) Math.round((Math.random()*9) +1);
    int num5 = (int) Math.round((Math.random()*9) +1);
    int num3 = (int) Math.round((Math.random()*9) +1);
    int num4 = (int) Math.round((Math.random()*9) +1);


推荐答案

一种选择是使用shuffle算法(例如 Fisher-Yates shuffle )随机生成序列从1到9,然后取序列的前5个数字

One option is to use shuffle algorithm (e.g. Fisher-Yates shuffle ) to generate random sequence from 1 to 9, then take first 5 numbers of the sequence

StackOverflow的进一步说明:https://stackoverflow.com/a/196065/950427

Further explanation on StackOverflow: https://stackoverflow.com/a/196065/950427

这篇关于如何防止重叠的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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