Skip to content

Instantly share code, notes, and snippets.

@YuriyGuts
Created February 1, 2013 11:16
Show Gist options
  • Save YuriyGuts/4690725 to your computer and use it in GitHub Desktop.
Save YuriyGuts/4690725 to your computer and use it in GitHub Desktop.
Recursively generates a random tree with the specified max depth and sibling count.
private static void PopulateNodeWithRandomSubtree(TreeNode nodeToPopulate, int currentLevel)
{
// These can be the arguments of the function if necessary.
const int maxTreeDepth = 5;
const int maxSiblingCount = 4;
// Generate children for this node if a fair coin toss yields 0 at least QUOTA times,
// where QUOTA increases after each level. That way the deeper it gets, the less will
// be the probability of generating more children.
var quota = currentLevel * currentLevel * 1.0 / maxTreeDepth;
var actual = Enumerable.Range(1, currentLevel)
.Select(i => randomGenerator.Next(0, 2))
.Count(i => i == 0);
bool shouldGenerateChildren = actual >= quota;
if (shouldGenerateChildren)
{
var nodeCount = randomGenerator.Next(1, maxSiblingCount + 1);
for (int i = 0; i < nodeCount; i++)
{
var newChild = new TreeNode { Value = GetRandomValue() };
nodeToPopulate.Nodes.Add(newChild);
PopulateNodeWithRandomSubtree(newChild, currentLevel + 1);
}
}
}
/*
How to use:
var root = new TreeNode { Value = GetRandomValue() };
PopulateNodeWithRandomSubtree(root, 1);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment