This class contains the logic for the random text generator. It has an AddContentParagraphs method. And we can fetch the resulting string from the Content property.
using System;
using System.Text;
class RandomText
{
static Random _random = new Random();
StringBuilder _builder;
string[] _words;
// Part 1: the constructor.
public RandomText(string[] words)
{
_builder = new StringBuilder();
_words = words;
}
public void AddContentParagraphs(int numberParagraphs, int minSentences,
int maxSentences, int minWords, int maxWords)
{
// Part 2: call Next() on random number generator for each paragraph.
for (int i = 0; i < numberParagraphs; i++)
{
AddParagraph(_random.Next(minSentences, maxSentences + 1),
minWords, maxWords);
_builder.Append(
"\n\n");
}
}
void AddParagraph(int numberSentences, int minWords, int maxWords)
{
// Part 3: call AddSentence repeatedly in AddParagraph.
for (int i = 0; i < numberSentences; i++)
{
int count = _random.Next(minWords, maxWords + 1);
AddSentence(count);
}
}
void AddSentence(int numberWords)
{
// Part 4: generate a single sentence.
StringBuilder b = new StringBuilder();
// Add n words together.
for (int i = 0; i < numberWords; i++)
// Number of words
{
b.Append(_words[_random.Next(_words.Length)]);
b.Append(' ');
}
string sentence = b.ToString().Trim() +
". ";
// Uppercase sentence.
sentence = char.ToUpper(sentence[0]) + sentence.Substring(1);
// Add this sentence to the class.
_builder.Append(sentence);
}
public string Content
{
get
{
return _builder.ToString();
}
}
}
class Program
{
static void Main()
{
// Part 5: create a RandomText instance and generate text with it.
string[] words = {
"cat",
"house",
"man",
"the",
"for",
"and",
"a",
"with",
"bird",
"fox" };
RandomText text = new RandomText(words);
text.AddContentParagraphs(2, 2, 4, 5, 12);
string content = text.Content;
Console.WriteLine(content);
}
}
For bird house a house fox cat. House the the man a a bird cat a man for cat.
Bird fox for for the a with a cat man. A with the fox cat with bird house.