I have a graph, each node have 4 child nodes. I wrote a algorithm to generate a random path from a begin node to an end node. At each node, it chooses a random next node. Visited node can be revisited.
the code is like the following:
public List<Node> GetPath(Node begin, Node end)
{
var nodes = new List<Node>();
var node = begin;
while (node != end)
{
nodes.Add(node);
var next = node.Children[new Random().Next(4)];
node = next;
}
nodes.Add(end);
return nodes;
}
But sometimes, the Random does not work as expected. The “new Random().Next(4)” keeps generating 0. So it is always the first child node get chose and a very long repeat sequence like node1->node2->node1->node2… is generated and eventually an out of memory exception happens.
Is there a way to make the Random class works correctly?
The reason is because Random is initialized based on the current time (there is no true random in computers… only psuedo-random). The while loop iterates too quickly, and the system time has not registered a change. So you’re re-initializing a new Random object that starts with the same value.
Try creating one Random object that is reused throughout the method: