C# Challenge:
Main Method:
using System;
namespace DailyProgrammer_NodeGraph
{
/* https://www.reddit.com/r/dailyprogrammer/comments/4ijtrt/20160509_challenge_266_easy_basic_graph/ */
public class Program
{
static void Main(string[] args)
{
var test = new NodeGraph();
Console.WriteLine("Press enter to exit..." + Console.ReadLine());
}
}
}
node graph class:
using System.Collections.Generic;
using System.IO;
namespace DailyProgrammer_NodeGraph
{
public class NodeGraph
{
private List<Node> Graph = new List<Node>();
public NodeGraph()
{
GetInput();
PrintAll();
}
public void AddEdgeToGraph(int edgeID, int nodeID)
{
var edge = Graph.Find(e => e.Equals(edgeID));
if (edge != null)
{
Graph.Find(q => q.Equals(nodeID)).AddEdge(edge);
}
}
private void GetInput()
{
var directory = Directory.GetCurrentDirectory();
var r = new StreamReader(directory + @"\input.txt");
var max = int.Parse(r.ReadLine());
InitNodes(max);
var split = r.ReadLine();
while (split != null)
{
var text = split.Split(' ');
var id1 = int.Parse(text[0]);
var id2 = int.Parse(text[1]);
AddEdgeToGraph(id2, id1);
split = r.ReadLine();
}
}
private void InitNodes(int numNodes)
{
for (var i = 1; i <= numNodes; i++)
{
var n = new Node(i);
Graph.Add(n);
}
}
private void PrintAll()
{
foreach (var n in Graph)
{
n.PrintAll();
}
}
}
}
Node Class:
using System;
using System.Collections.Generic;
namespace DailyProgrammer_NodeGraph
{
public class Node
{
private List<Node> _edges = new List<Node>();
public int degree { get; set; }
private int NodeId { get; set; }
public Node(int nodeId)
{
NodeId = nodeId;
}
public int GetCountOfEdges()
{
return _edges.Count;
}
public bool Equals(int id)
{
return NodeId == id;
}
public void AddEdge(Node n)
{
n.degree += 1;
degree += 1;
_edges.Add(n);
}
public void PrintAll()
{
Console.WriteLine("Node: {0} has a degree of {1}.", NodeId, degree);
}
}
}
Output:
Node: 1 has a degree of 8.
Node: 2 has a degree of 8.
Node: 3 has a degree of 6.
Node: 4 has a degree of 3.
Node: 5 has a degree of 7.
Node: 6 has a degree of 10.
Node: 7 has a degree of 7.
Node: 8 has a degree of 7.
Node: 9 has a degree of 7.
Node: 10 has a degree of 5.
Node: 11 has a degree of 9.
Node: 12 has a degree of 8.
Node: 13 has a degree of 8.
Node: 14 has a degree of 5.
Node: 15 has a degree of 9.
Node: 16 has a degree of 9.
Press enter to exit...