生成随机数而无需连续重复 [英] generating random numbers without consecutive repetition

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

问题描述

如何以不连续产生两次相同的数字的方式从0-4产生随机整数?例如,如果3是第一次生成的数字,则0、1、2、4将是第二次随机生成的可能数字.如果第二次生成2,则0、1、3、4将是第三次随机生成的可能数字,依此类推.

How can I generate random integers from 0 - 4 in such a way that the same number is not generated twice consecutively? For example, if 3 is the number that is generated the first time then 0,1,2,4 will be the possible numbers for random generation the second time. If 2 is generated the second time then 0,1,3,4 will be the possible numbers for random generation the third time and so on.

推荐答案

int oldrand = <prior random number>;
int adder = randomNumberGenerator() % 4;
int newrand = (oldrand + adder + 1) % 5;

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

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