-1

Whats the quickest way to generate a list of consecutive numbers in a random order?

i.e. generate a list of numbers from 1 to 100, the list must contain each number once only. The order of the list should be random.

java or c# please.

my pseudocode looks like this, very inefficient.

 var list = new list<int>();
 for (int i = 1; i <= 100; ++i) {
     int x;
     repeat {
         x = random(1, 100);
     until (list.contains(x) == false);
     list.add(x);
 }
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
mfc
  • 3,018
  • 5
  • 31
  • 43

1 Answers1

3

Yes, it's teribly inefficient and it's not even bounded in time.

The usual solution is

  1. generate an ordered array
  2. shuffle it (I'd recommend the Fisher–Yates shuffle, it's simple, fast, unbiased and you'll find an implementation in any language)
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758