Kaoru
Kaoru

Reputation: 2883

Generate a random number if the number matched with the previous

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.

Upvotes: 0

Views: 110

Answers (2)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

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

Upvotes: 4

WearyWanderer
WearyWanderer

Reputation: 181

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

Upvotes: 1

Related Questions