产生一个随机数,如果数字与之前相匹配 [英] Generate a random number if the number matched with the previous

查看:239
本文介绍了产生一个随机数,如果数字与之前相匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个在它前面文字的随机数,而我不希望显示数量的两倍系统。所以,这是我做的方式:

I want to create a random number with a text in front of it, and I don't want the system displaying a number twice. So, this is that the way that I did it:

Random _rand = new Random();

private void RandomNumberGenerator()
        {
            int random = _rand.Next(10000);
            string text = "TP0" + random;

            if (random.Equals(random))
            {
                _rand.Next();
            }

            else
            {
                random = _rand.Next(10000);
            }

            MessageBox.Show(text);
        }



我没有得到任何显示数量的两倍(但我也不太清楚,因为我刚关闭程序,直到它显示的号码5次(这一切都不相同数量)。

I am not getting any displayed number twice (but I am not too sure, because I just close the program until it displayed the number 5 times (all of it are not the same number).

是否有可能从上面的代码来显示一个数与任何机会,两次?

Is it possible from the above code to displaying a number twice with any chance?

感谢您。

推荐答案

编辑以。摆脱幻数,并确保理智

EDITED to get rid of magic numbers and ensure sanity.

  Random _rand = new Random();
  HashSet<int> _taken = new HashSet<int>();
  object _syncRoot = new object();

  private int RandomNumberGenerator() {
    lock (_syncRoot) {
      const int MAX_NUMBER = 10000;
      if (_taken.Count == MAX_NUMBER) {
        throw new Exception("All possible numbers are already generated.");
      }

      int random = _rand.Next(MAX_NUMBER);
      while (_taken.Contains(random)) {
        random = (random + 1) % MAX_NUMBER;
      }
      _taken.Add(random);
      return random;
    }
  }

这篇关于产生一个随机数,如果数字与之前相匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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