1

How to generate an array which contains a group of consecutive numbers but with random order? For example, the consecutive numbers are from 8 to 100 (no duplicates), and what I want is an array containing all of these numbers but the sequence is random.

C. Wang
  • 2,516
  • 5
  • 29
  • 46
  • Sounds almost like shuffling a deck of cards. – jrok Feb 26 '14 at 18:21
  • Use `std::random_shuffle`, take a look at this post: http://stackoverflow.com/questions/21948091/how-to-generate-an-array-of-256-distinct-numbers/21948500#21948500 – asamarin Feb 26 '14 at 18:22
  • 2
    Why don't you guys post your comment as answer, rather than as comment? – m01 Feb 26 '14 at 18:23

2 Answers2

4

I suppose that 8 and 100 are included in the range.

#include <algorithm>
#include <numeric>
#include <iterator>

int main()
{
   const size_t N = 93;
   int a[N];

   std::iota( std::begin( a ), std::end( a ), 8 );
   std::random_shuffle( std::begin( a ), std::end( a ) );
}

If 8 is a typo in your post and you meant 0 then the code will look as

   const size_t N = 101;
   int a[N];

   std::iota( std::begin( a ), std::end( a ), 0 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • What's `std::itoa`? I can't find it in my copy of the standard (and the parameters you pass it don't look like those for the function of this name in older Unices). – James Kanze Feb 26 '14 at 18:47
  • @lisyarus I misread it; I read `itoa` (which was present in all of the early Unices, but didn't make it into any standard). That's also what I searched for in the standard. – James Kanze Feb 26 '14 at 19:01
0

I am assuming that you are student and new to programming therefore some basics should be told.

rand() generates random number.

If you want the number to be in a particular range then take its mod e.g.

rand()%93;    // generate random numbers from 0-92

Similarly, (rand()%93)+8 // will generate number between 8-100

Moreover, for checking duplicates you can compare the number with those which already stored in the array.

Haseeb Jadoon
  • 450
  • 6
  • 20
  • Comparing to already generated numbers can be extremely slow and it's time cost highly depends on used pseudo-random numbers generation algorithm. Generating a sequence and then shuffling it is a much better idea, since it' time cost is linear. – lisyarus Feb 26 '14 at 18:54
  • What if a number (lets say 0) is generated after an infinite amount of time ? –  Feb 26 '14 at 19:04