Hello, does anyone know how to generate random numbers?(pseudocode). I need to generate 5000 of them and store in an array to then use insertion sort to sort them. but I just need the random number part of the question
Thanks
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Aug 22, 2011, 11:14 AM
One of the easiest is the Linear Congruential Generator (or LCG) where the random numbers form a sequence given by the equation:
x[n+1] = (a * x[n] + c) mod m
and where a,c and m are unsigned integer constants with a and c both less than m.
See http://en.wikipedia.org/wiki/Linear_congruential_generator.
The choice of the constants is very important here and, in the following C# implementation (producing 20 random numbers) I've used a combination known as MINSTD (see http://roguebasin.roguelikedevelopment.org/index.php/Random_number_generator).
I've seeded the sequence using Environment.TickCount to try and ensure a different set of numbers is generated each time the program is run and scaled the random numbers so that they're in the range 0 to 4999 (may not be necessary).
using System;
class LCG
{
static uint m, a, c;
static ulong prev;
static void Main()
{
uint seed = (uint)Environment.TickCount;
Initialize(2147483647, 16807, 0, seed);
for (int i = 0; i < 20; i++)
{
Console.WriteLine(GetNext());
}
Console.ReadKey();
}
static void Initialize(uint m, uint a, uint c, uint seed)
{
LCG.m = m;
LCG.a = a;
LCG.c = c;
LCG.prev = seed;
}
static uint GetNext()
{
prev = (a * prev + c) % m;
return (uint)prev % 5000;
}
}
I'm not much good at pseudo-code as you know but here's my attempt:
DEFINE 4 unsigned integer variables: m, a, c and seed
DEFINE 1 unsigned long integer variable : prev
DEFINE an array of 5000 unsigned integers : numbers
LET m be 2147483647
LET a be 16087
LET c be zero
LET seed be the number of ticks since the machine was turned on
LET prev be equal to seed
FOR i = 1 TO 5000
CALL GetNext and assign it to array[i]
NEXT i
FUNCTION GetNext() AS unsigned integer
LET prev = (a * prev + c) MODULO m
RETURN prev MODULO 5000 AS unsigned integer
END FUNCTION
Avuya MxoliPosted Aug 23, 2011, 2:45 AM
Avuya MxoliPosted Aug 23, 2011, 2:44 AM
Satyapriya NayakPosted Aug 22, 2011, 4:09 AM
Please refer Our recommended articles section.
Thanks