Solved

# Random number generator in (Linux with g++)

Posted on 2000-02-18

I have just discovered an anamoly in a pece of code I wrote to rearrange a list of 1245 numbers from 1 to 1245 in a random order - even though there is no "0" in the list, the random number generator keeps giving me one. Otherwise it looks alright except that there is also a 1245 and so some number in the middle is being lost. Can anyone see a problem with this code, as I can't. I am a relatively new programmer using g++ under Linux. Thanks in advance.

Heres the code (the header files are from the main program):

#include <iostream>

#include <cmath>

#include <fstream>

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

int seed, a, j, np = 1245, index;

double randomNumber, ordered[1245], ordered_store[1245], random_order[1245];

void random_number_generator()

{

double ran;

srand (seed);

ran = rand();

randomNumber = ran / RAND_MAX;

seed++;

}

void random_sequence()

{

double temp;

for (a = 1; a <= np; a++)

{

ordered[a - 1] = a;

ordered_store[a - 1] = a;

random_order[a - 1] = 0;

}

int range = int(np);

for (a = 0; a < np; a++)

{

random_number_generator();

temp = randomNumber * range;

index = int(temp) + 1;

random_order[a] = ordered[index];

for (j = index; j < np - a; j++)

{

ordered[j] = ordered[j + 1];

}

range--;

}

}

void test_3()

{

fstream fileout ("random_order", ios::out);

for (a = 0; a < np; a++)

{

fileout << " " << random_order[a] << " " << ordered_store[a] << endl;

}

}

main()

{

random_sequence();

test_3();

return 0;

}