Created
June 12, 2012 00:34
-
-
Save gabrielgreen/2913668 to your computer and use it in GitHub Desktop.
ladder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var N = 5; | |
Node.Graph.Add(new Node()); | |
bool canExpand = true; | |
while (canExpand) | |
{ | |
Func<int, IEnumerable<Move>> addNodes = steps => from c in Node.Graph | |
where c.IsLeaf && (c.Value + steps) <= N | |
select new Move { Node = c, Steps = steps }; | |
var moves = addNodes(1).Union(addNodes(2)).ToList(); | |
if(moves.Count > 0) | |
{ | |
moves.ForEach(c => c.Node.AddChild(c.Steps)); | |
} | |
else | |
{ | |
canExpand = false; | |
} | |
Console.WriteLine (moves.Count); | |
} | |
foreach (var node in Node.Graph.Where(c => c.IsLeaf)) | |
{ | |
node.GetSolution().Dump("Result"); | |
} | |
} | |
struct Move | |
{ | |
public Node Node { get; set; } | |
public int Steps { get; set; } | |
} | |
struct Solution | |
{ | |
public int[] Steps { get; set; } | |
} | |
class Node | |
{ | |
public Node() | |
{ | |
this.Children = new List<Node>(); | |
this.Id = ++NodeCount; | |
} | |
public Node(Node parent, int steps) | |
: this() | |
{ | |
this.Parent = parent; | |
this.Steps = steps; | |
this.Value = parent.Value + steps; | |
} | |
public void AddChild(int steps) | |
{ | |
var node = new Node(this, steps); | |
this.Children.Add(node); | |
Graph.Add(node); | |
} | |
public Solution GetSolution() | |
{ | |
var list = new LinkedList<int>(); | |
var parent = this; | |
while (parent != null) | |
{ | |
if(parent.Steps > 0) | |
{ | |
list.AddFirst(parent.Steps); | |
} | |
parent = parent.Parent; | |
} | |
return new Solution { Steps = list.ToArray() }; | |
} | |
public int Id { get; set; } | |
public Node Parent { get; set; } | |
public List<Node> Children { get; set; } | |
public int Value { get; set; } | |
public int Steps { get; set; } | |
public bool IsLeaf { get { return Children.Count == 0; } } | |
public static List<Node> Graph = new List<Node>(); | |
public static int NodeCount { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment