-2

I want to generate 9 random numbers, but I do not want to generate the same number twice. Is there an easy way to do this?

I want to create numbers between 0 and 10, to get the numbers 1,2,3,4,5,6,7,8,9. I am going to put these numbers in an array, and the code will not work if I get the same number twice, and they all have to be random, different numbers each time you start the program.

  • Do you have a range? What's the minimum accepted value? Or the maximum one? – Andrei V Nov 29 '13 at 09:05
  • i guess make use of timestamp for this kind of suff – Pranay Rana Nov 29 '13 at 09:05
  • 3
    What is so hard about checking previously generated numbers that you are looking for an 'easy way'? – S_F Nov 29 '13 at 09:06
  • http://stackoverflow.com/questions/3627029/smart-way-to-generate-unique-random-number – Trax Nov 29 '13 at 09:07
  • duplicate of http://stackoverflow.com/questions/14473321/generating-random-unique-values-c-sharp – shankar Nov 29 '13 at 09:07
  • @shankar , I do not think it is a duplicate of that question, there the guy wants to generate something like serial numbers. Per the question, here I think the guy just wants to generate 9 numbers at a time but between groups of 9 numbers there could be a repetition, but not among the same group. – NothingsImpossible Nov 29 '13 at 09:13
  • *"create numbers between 0 and 10, to get the numbers 1,2,3,4,5,6,7,8,9"* seems a bit self-contradictory. – hyde Nov 30 '13 at 08:04

9 Answers9

1

Just keep generating new numbers and compare them with the previously generated ones

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
1

Use a shuffle bag.

I find it a cleaner solution than checking your old numbers, that might theoretically loop forever.

Community
  • 1
  • 1
Carra
  • 17,808
  • 7
  • 62
  • 75
  • The link is quite good article. I can't emphasize enough how bad a solution is "keep generating and search for collision", that's a interview "nohire" right there. – Remus Rusanu Nov 29 '13 at 09:24
  • To fix this problem, I came up with the shuffle algorithm myself, only to later find out that it's already invented and named a Fisher-Yates shuffle. – Carra Nov 29 '13 at 10:29
1

As long as the range is much larger than the number of items you need, you should have no trouble simply continuing to generate items while discarding duplicates until you have the required number of items.

Pseudocode:

  • While I have less than N items
    • Generate an item
    • If it's a duplicate, discard it

If the range is small, and the number of items you need is a significant proportion of it (e.g. 9 numbers out of 1-10) you may prefer to use a shuffle bag.

Pseudocode:

  • Enumerate the entire range
  • Shuffle the enumeration into a random order
  • Take the first N items
Iain Galloway
  • 18,669
  • 6
  • 52
  • 73
1

Fisher-Yates Shuffle is another good solution:

Random _random = new Random();

public static void Shuffle<T>(T[] array)
{
    var random = _random;
    for (int i = array.Length; i > 1; i--)
    {
        // Pick random element to swap.
        int j = random.Next(i); // 0 <= j <= i-1
        // Swap.
        T tmp = array[j];
        array[j] = array[i - 1];
        array[i - 1] = tmp;
    }
 }

And call it like this:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Shuffle(array);

This method Shuffles the original array in place, but it can easily modified so that it returns a different object. No comparison of the "previous values" needed. In your case, it just iterates 8 times.

Andrei V
  • 7,306
  • 6
  • 44
  • 64
0
using System;
using System.Linq;

namespace Test {
  class Program {
    static void Main(string[] args) {
      var random = new Random();
      int[] sequence = new int[9];
      do {
        for (var i = 0; i < sequence.Length; i++) {
          sequence[i] = random.Next();
        }
      } while (sequence.Distinct().Count() != sequence.Length);
    }
  }
}
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
0
int[] numbers = (
    from number in Enumerable.Range(0, 10)
    orderby Guid.NewGuid()
    select number)
    .ToArray();
Steven
  • 166,672
  • 24
  • 332
  • 435
0
Random r = new Random();
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> result = new List<int>();
while (numbers.Count() > 0)
{
    int pos = r.Next(0, numbers.Count() - 1);
    result.Add(numbers[pos]);
    numbers.RemoveAt(pos);
}
Mark Homans
  • 637
  • 1
  • 6
  • 12
0

Use loop for 10 numbers and use, int r = arc4random() % numbers; where number is range in which number will generate , store and use those number. I hope it will help you for better idea about your need.

Rajeev Dubey
  • 21
  • 1
  • 3
0

This generates 6 random ints between 0 and 10 (exclusive):

int[] numbers = Enumerable.Range(0, 10)
                .OrderBy(i => Guid.NewGuid())
                .Take(6)
                .ToArray();
Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33