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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Aug 22, 2011, 7:14 AM EDT
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
Satyapriya NayakRank #47 · 31.5K reputationPosted Aug 22, 2011, 12:09 AM EDT
Please refer Our recommended articles section.
Thanks
Avuya MxoliRank #7,940 · 231 reputationPosted Aug 22, 2011, 10:44 PM EDT
Avuya MxoliRank #7,940 · 231 reputationPosted Aug 22, 2011, 10:45 PM EDT