Generate a random number if the number matched wit

2019-03-06 15:59发布

问题:

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

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?

Thank you.

回答1:

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


回答2:

Soner Gonul is correct, random.Equals(random) is always going to be true I think. You could work around it (roughly) by having another int variable which will become whatever the last number generated was, then when the function goes into it's next cycle have it reference the new random number variable against the one stored in your second variable, which is the previous random number. That's one way of doing it, I can try define that a little clearer in a minute if you don't understand



标签: c# random