C++ Builder: Random numbers, strings and wordsC++ 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. Random numbersThe function Random(Range) returns a random integer number within the
range 0 <= X < Range. To initialize the random number generator, add a call to Randomize() before making any calls to Random(). Random stringsFor 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:
Random wordsFor 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:
Code examplesStart 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. 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++) { |