C++ Builder Tutorials

C++ Builder: Random numbers, strings and words

C++ Builder contains a random number generator, that generates pseudo-random numbers.

Random numbers are often used in games, but also can be very useful for testing purposes.
For example, you could use a generator of random words to populate a database.

random words


Random numbers

The function Random(Range) returns a random integer number within the range 0 <= X < Range.
If Range is not specified, the result is a floatying type random number within the range 0 <= X < 1.

To initialize the random number generator, add a call to Randomize() before making any calls to Random().

Random strings

For a random string, we start from a "seed" string, containing all the possible characters that you want to appear in your random string. Next, we generate a few random numbers N, from 1 to the length of the seed string, and we add character number N:

int i, N;
String SeedString = "abcdefghijklmnopqrstuvwxyz";
String S;
S = "";
for (i = 0; j < 6; j++) {  // strings of 6 characters
  N = Random(SeedString.Length()) + 1;
  S += SeedString[N];
}

Random words

For a random word, we start from a "seed" array of strings, containing all the possible syllables (parts of words) that you want to appear in your random word. Next, we generate a few random numbers N, from 1 to the number of elements of the array, and we add syllable number N:

String Syllabs[8] = {"bin", "cla", "del", "for", "lon", "pre", "sta", "try"};
int i, N;
String Syl, S;
S = "";
for (i = 0; i < 3; i++) {  // words of 3 syllables
  N = Random(8);
  S += Syllabs[N];
}


Code examples

Start by adding 3 buttons and a listbox to your form.

Generate 10 random numbers from 1 to 1000:

void __fastcall TForm1::btnRandNrClick(TObject *Sender)
{
  int i, N;
  Randomize();
  for (i = 0; i < 10; i++) {
	N = Random(1000) + 1;
	ListBox1->Items->Add(IntToStr(N));
  }
}

Generate 10 random strings, each with 6 characters:

void __fastcall TForm1::btnRandStringClick(TObject *Sender)
{
  int i, j, N;
  String SeedString = "abcdefghijklmnopqrstuvwxyz";
  String S;
  Randomize();
  for (i = 0; i < 10; i++) {
    S = "";
    for (j = 0; j < 6; j++) {
      N = Random(SeedString.Length()) + 1;
      S += SeedString[N];
    }
    ListBox1->Items->Add(S);
  }
}

For our random words, we added some extra code that inserts random vowels into the random syllables. For example, "b*n" can become "ban", "ben", "bin", and so on.
Generate 10 random words:

void __fastcall TForm1::btnRandWordClick(TObject *Sender)
{
  String Syllabs[8] = {"b*n", "cl*", "d*l", "f*r", "l*n", "pr*", "st*", "tr*"};
  String Vowels = "aaaeeeiioouy";
  int i, j, P, N;
  String Syl, S;
  Randomize();
  for (i = 0; i < 10; i++) {
S = ""; for (j = 0; j < 3; j++) { N = Random(8); Syl = Syllabs[N]; P = Syl.Pos("*"); Syl[P] = Vowels[Random(12) + 1]; S += Syl; } ListBox1->Items->Add(S); } }