Friday, April 29, 2016

Stack Class in C#

So this week there is no more homework for my C# class since the semester is coming to an end and we have a final exam next week.

Since I was bored at work, I started thinking that we never created a stack for one of the class assignments. So I decided to create my own, which wasn't that hard since its essentially just a wrapper around an array.

I started to work on it yesterday for a couple hours and finished it this morning.

Here is my code:

using System;
using System.Collections;
using System.Collections.Generic;
class myStack<T> : IEnumerable<T>, ICollection, IEnumerable where T : IComparable<T>
{
private int ElementCount = 0;
private T[] UnderlyingArray;
public myStack(int starting_size)
{
if (starting_size > 5)
UnderlyingArray = new T[starting_size];
else
UnderlyingArray = new T[5];
}
public myStack()
{
UnderlyingArray = new T[5];
}
public myStack(ICollection<T> colletion)
{
UnderlyingArray = new T[colletion.Count];
foreach (T item in colletion)
Push(item);
}
public int Count
{
get
{
return ElementCount;
}
}
public void Push(T item)
{
if (ElementCount == UnderlyingArray.Length)
SizeUp();
UnderlyingArray[ElementCount] = item;
ElementCount++;
}
public T Peek()
{
return UnderlyingArray[ElementCount - 1];
}
public T Pop()
{
ElementCount--;
T last_item = UnderlyingArray[ElementCount];
UnderlyingArray[ElementCount] = default(T);
return last_item;
}
public void Clear()
{
UnderlyingArray = new T[UnderlyingArray.Length];
}
public void TrimExcess()
{
if (GetRatio() < .9)
SizeDown();
}
public bool Contains(T item)
{
foreach (T existing_item in UnderlyingArray)
if (item.CompareTo(existing_item) == 0)
return true;
return false;
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return this;
}
}
public void CopyTo(Array array, int index)
{
int start = index;
for (int i = 0; i < ElementCount; i++)
{
array.SetValue(UnderlyingArray[i], start);
start++;
}
}
public T[] ToArray()
{
int count = ElementCount;
T[] output = new T[count];
for (int index = 0; index < count; index++)
output[index] = Pop();
return output;
}
public IEnumerator<T> GetEnumerator()
{
for (int index = ElementCount - 1; index >= 0; index--)
yield return UnderlyingArray[index];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void SizeUp()
{
T[] new_array = new T[UnderlyingArray.Length * 2];
for (int index = 0; index < ElementCount; index++)
new_array[index] = UnderlyingArray[index];
UnderlyingArray = new_array;
}
private void SizeDown()
{
T[] new_array = new T[ElementCount];
for (int index = 0; index < ElementCount; index++)
new_array[index] = UnderlyingArray[index];
UnderlyingArray = new_array;
}
private double GetRatio()
{
return ElementCount / UnderlyingArray.Length;
}
}
view raw myStack.cs hosted with ❤ by GitHub

Thanks for reading!

Wednesday, April 27, 2016

CS 2420 - Assignment 9 - Max Heap

This week's assignment is not as hard as the last one, we just have to create a heap data structure. We had the choice of either creating a min heap or max heap, so I went with Max since it made the most sense to me.

While the assignment its self wasn't too hard, it took me a while to do all the conditional logic behind the Sink() function.

Here is my code:

using System;
using System.Collections;
using System.Collections.Generic;

namespace Assignment9
{
    class MaxHeap<T> : IEnumerable<T> where T : IComparable
    {
        private T[] UnderlyingArray;
        private int ElementCount = 0;
        private int OldCount = 0;
        private bool IsHeap = true;

        public MaxHeap(int starting_size)
        {
            UnderlyingArray = new T[starting_size];
        }

        public MaxHeap()
        {
            UnderlyingArray = new T[5];
        }

        public int Count
        {
            get
            {
                return ElementCount;
            }
        }

        public void Clear()
        {
            UnderlyingArray = new T[UnderlyingArray.Length];
        }

        public T this[int index]
        {
            get
            {
                return UnderlyingArray[index];
            }
        }

        public void Add(T new_value)
        {
            if (!IsHeap)
                BuildHeap();

            if (ElementCount == UnderlyingArray.Length)
                Resize();

            UnderlyingArray[ElementCount] = new_value;
            Swim();
            ElementCount++;
        }

        public T PopTop()
        {
            if (!IsHeap)
                BuildHeap();

            T max = UnderlyingArray[0];

            Swap(0, ElementCount - 1);
            UnderlyingArray[ElementCount - 1] = default(T);
            ElementCount--;
            Sink();
            
            return max;
        }

        public void Sort()
        {
            if (!IsHeap)
                BuildHeap();

            OldCount = ElementCount;

            for (int i = 0; i < OldCount; i++)
            {
                Swap(0, ElementCount - 1);
                ElementCount--;
                Sink();
            }

            IsHeap = false;
            ElementCount = OldCount;
        }

        public void BuildHeap()
        {
            if (IsHeap)
                return;

            int last_item = OldCount - 1;

            for (int index = 0; index < OldCount / 2; index++)
            {
                Swap(index, last_item);
                last_item--;
            }

            ElementCount = OldCount;
            IsHeap = true;
        }

        private void Swim()
        {
            int current_index = ElementCount;

            while (current_index != 0)
            {
                int parent_index = FindParent(current_index);

                if (UnderlyingArray[current_index].CompareTo(UnderlyingArray[parent_index]) == 0)
                    break;

                else if (UnderlyingArray[current_index].CompareTo(UnderlyingArray[parent_index]) > 0)
                    Swap(current_index, parent_index);

                current_index = parent_index;
            }
        }

        private void Swap(int first, int second)
        {
            T temp = UnderlyingArray[first];
            UnderlyingArray[first] = UnderlyingArray[second];
            UnderlyingArray[second] = temp;
        }

        private void Sink()
        {
            int current_index = 0;

            while (current_index < ElementCount)
            {
                int max_child_index = current_index;
                int left_child_index = FindLeft(current_index);
                int right_child_index = FindRight(current_index);

                if (left_child_index >= ElementCount)
                    break;

                if (right_child_index >= ElementCount)
                    max_child_index = left_child_index;

                if (right_child_index < ElementCount &&
                    UnderlyingArray[left_child_index].CompareTo(UnderlyingArray[right_child_index]) == 0)
                    max_child_index = left_child_index;

                if (right_child_index < ElementCount && 
                    UnderlyingArray[left_child_index].CompareTo(UnderlyingArray[right_child_index]) > 0)
                    max_child_index = left_child_index;

                if (right_child_index < ElementCount && 
                    UnderlyingArray[left_child_index].CompareTo(UnderlyingArray[right_child_index]) < 0)
                    max_child_index = right_child_index;

                if (UnderlyingArray[max_child_index].CompareTo(UnderlyingArray[current_index]) == 0)
                    break;

                if (UnderlyingArray[max_child_index].CompareTo(UnderlyingArray[current_index]) > 0)
                    Swap(current_index, max_child_index);

                current_index = max_child_index;
            }
        }

        private int FindParent(int current_index)
        {
            return (current_index - 1) / 2;
        }

        private int FindLeft(int current_index)
        {
            return (current_index * 2) + 1;
        }

        private int FindRight(int current_index)
        {
            return (current_index * 2) + 2;
        }

        private void Resize()
        {
            T[] new_array = new T[UnderlyingArray.Length * 2];

            for (int index = 0; index < UnderlyingArray.Length; index++)
                new_array[index] = UnderlyingArray[index];

            UnderlyingArray = new_array;
        }

        public IEnumerator<T> GetEnumerator()
        {
            for (int index = 0; index < ElementCount; index++)
            {
                T temp = UnderlyingArray[index];
                //Console.WriteLine("Current Value: {0}", temp);
                yield return temp;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

That's all for now, thanks for reading!

Wednesday, April 20, 2016

CS 2420 - Assignment 8 - Components

This week's assignment is a bit more fun that usual since we are got to build a "game."

The point of this week's assignment to learn how to use components to build a game, instead of hard coding everything like we usually do. We also had a chance to review inheritance and understand how it works.

This time around there is too much code involved for me to put it here like I usually do, but if you are interested in looking at the code you can look here:

https://github.com/fushinoryuu/EAE2420/tree/master/DataStructuresAndSorts/Assignment8

I created these main class files: Component, Entity, Grid, Point, and Power Up.

The Grid was essentially a 2D array and everything ran through this file, it represented the map the player was going to play on. It also updated itself on the position of each enemy and the player and then displayed itself on the console.

The player and the enemies in the game all inherited from the Entity class and used a bunch of components to make each unique. For example, enemies had a component that allowed them to wrap around the Grid but the player was bound and couldn't go past the edges of the grid. To do this there was two components and I just had to make sure to give one to the player and the other to the enemies.

Power Ups are a type of component, but they don't inherit from the component class. I made it so they would modify the player's action. For example I had a Teleport Power Up. When they stepped on it, they would get randomly taken to an empty spot in the map.

I had a lot of fun with this assignment, but it took a little longer than I anticipated.

Anyways, that's all for now. Thanks for reading!

Tuesday, April 12, 2016

CS 2420 - Assignment 7 - Hash Table

This week we had to write a hash table, also known as a dictionary. Hash tables are really nice because you can index with more than just integers, and they are faster running times than a regular array or a linked list.

Here is my code:

namespace Assignment7
{
class Hero
{
public string Name { get; set; }
public int Attack { get; set; }
public override int GetHashCode()
{
return (Name.GetHashCode() ^ Attack.GetHashCode());
}
public override bool Equals(object obj)
{
Hero other = (Hero)obj;
return Name == other.Name && Attack == other.Attack;
}
}
}
view raw Hero.cs hosted with ❤ by GitHub
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Assignment7
{
class MainClass
{
public static void Main()
{
NumberTable();
HeroTable();
}
public static void NumberTable()
{
MyHashTable<int, int> number_table = new MyHashTable<int, int>();
int[] first_list = new int[] { 5, 8, 19, 39, 13, 99, 40, 38, 84, 66, 75, 1, 45, 92 };
int[] second_list = new int[] { 6, 9, 20, 43, 14, 100, 41, 37, 85, 67, 76, 2, 46, 3 };
foreach (int number in first_list)
number_table.Add(new KeyValuePair<int, int>(number, number));
foreach (int number in second_list)
number_table.Add(number, number);
number_table[55] = 4;
Console.WriteLine("Values in the Interger Hashtable: {0}\n", string.Join(", ", number_table));
Console.WriteLine("Keys in the Integer Hashtable: {0}\n", string.Join(", ", number_table.Keys));
Console.WriteLine("Values in the Integer Hashtable: {0}\n", string.Join(", ", number_table.Values));
Console.WriteLine("Does the Hashtable contain the Key 101: {0}\n", number_table.ContainsKey(101));
TestCount(29, number_table.Count, "Element count doesn't match!");
Console.WriteLine("Elements in the Hashtable: {0}\n", number_table.Count);
Console.WriteLine("---------------------------------------------------------\n");
}
public static void HeroTable()
{
MyHashTable<string, int> hero_table = new MyHashTable<string, int>();
List<Hero> adc_list = new List<Hero>();
adc_list.Add(new Hero { Name = "Ashe", Attack = 57 });
adc_list.Add(new Hero { Name = "Jinx", Attack = 58 });
adc_list.Add(new Hero { Name = "Varus", Attack = 55 });
adc_list.Add(new Hero { Name = "Vayne", Attack = 56 });
adc_list.Add(new Hero { Name = "Kalista", Attack = 63 });
adc_list.Add(new Hero { Name = "Jhin", Attack = 53 });
adc_list.Add(new Hero { Name = "Caitlyn", Attack = 54 });
adc_list.Add(new Hero { Name = "Draven", Attack = 56 });
adc_list.Add(new Hero { Name = "Graves", Attack = 61 });
adc_list.Add(new Hero { Name = "Lucian", Attack = 57 });
List<Hero> bruiser_list = new List<Hero>();
bruiser_list.Add(new Hero { Name = "Garen", Attack = 58 });
bruiser_list.Add(new Hero { Name = "Fiora", Attack = 60 });
bruiser_list.Add(new Hero { Name = "Darius", Attack = 56 });
bruiser_list.Add(new Hero { Name = "Vi", Attack = 56 });
bruiser_list.Add(new Hero { Name = "Wukong", Attack = 60 });
bruiser_list.Add(new Hero { Name = "Shyvana", Attack = 61 });
bruiser_list.Add(new Hero { Name = "Olaf", Attack = 60 });
bruiser_list.Add(new Hero { Name = "Pantheon", Attack = 56 });
bruiser_list.Add(new Hero { Name = "Riven", Attack = 56 });
bruiser_list.Add(new Hero { Name = "Illaoi", Attack = 60 });
foreach (Hero adc in adc_list)
{
hero_table.Add(new KeyValuePair<string, int>(adc.Name, adc.Attack));
}
foreach (Hero bruiser in bruiser_list)
{
hero_table.Add(bruiser.Name, bruiser.Attack);
}
hero_table["Irelia"] = 62;
Console.WriteLine("Values in the Hero Hashtable: {0}\n", string.Join(", ", hero_table));
Console.WriteLine("Keys in the Hero Hashtable: {0}\n", string.Join(", ", hero_table.Keys));
Console.WriteLine("Values in the Hero Hashtable: {0}\n", string.Join(", ", hero_table.Values));
Console.WriteLine("Does the Hashtable contain the Key 'Ahri': {0}\n", hero_table.ContainsKey("Ahri"));
TestCount(21, hero_table.Count, "Element count doesn't match!");
Console.WriteLine("Elements in the Hashtable: {0}\n", hero_table.Count);
}
private static void TestCount(int expect, int actual, string error)
{
Debug.Assert(expect == actual, error);
}
}
}
view raw MainClass.cs hosted with ❤ by GitHub
using System;
using System.Collections;
using System.Collections.Generic;
namespace Assignment7
{
class MyHashTable<TKey, TValue> : IDictionary<TKey, TValue>
{
LinkedList<KeyValuePair<TKey, TValue>>[] BaseArray;
private int ElementCount = 0;
public MyHashTable()
{
BaseArray = new LinkedList<KeyValuePair<TKey, TValue>>[5];
}
public TValue this[TKey key]
{
get
{
int bucket = GetHash(key);
if (BaseArray[bucket] == null)
throw new KeyNotFoundException();
foreach (KeyValuePair<TKey, TValue> pair in BaseArray[bucket])
if (pair.Key.Equals(key))
return pair.Value;
throw new KeyNotFoundException();
}
set
{
Insert(key, value, false);
}
}
public int Count
{
get
{
return ElementCount;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public ICollection<TKey> Keys
{
get
{
List<TKey> list = new List<TKey>(Count);
for (int bucket = 0; bucket < BaseArray.Length; bucket++)
if (BaseArray[bucket] != null)
foreach (KeyValuePair<TKey, TValue> pair in BaseArray[bucket])
list.Add(pair.Key);
return list;
}
}
public ICollection<TValue> Values
{
get
{
List<TValue> list = new List<TValue>(Count);
for (int bucket = 0; bucket < BaseArray.Length; bucket++)
if (BaseArray[bucket] != null)
foreach (KeyValuePair<TKey, TValue> pair in BaseArray[bucket])
list.Add(pair.Value);
return list;
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
Insert(item.Key, item.Value, true);
}
public void Add(TKey key, TValue value)
{
Insert(key, value, true);
}
private void Insert(TKey key, TValue value, bool add)
{
if (GetRatio() > .75)
Resize();
int bucket = GetHash(key);
if (BaseArray[bucket] == null)
{
BaseArray[bucket] = new LinkedList<KeyValuePair<TKey, TValue>>();
BaseArray[bucket].AddFirst(new KeyValuePair<TKey, TValue>(key, value));
ElementCount++;
return;
}
LinkedList<KeyValuePair<TKey, TValue>> list = BaseArray[bucket];
for (LinkedListNode<KeyValuePair<TKey, TValue>> pair = list.First; pair != null; pair = pair.Next)
{
if (pair.Value.Key.Equals(key) && add)
{
throw new ArgumentException("An item with the same key has already been added.");
}
else if (pair.Value.Key.Equals(key) && !add)
{
list.Remove(pair);
list.AddLast(new KeyValuePair<TKey, TValue>(key, value));
return;
}
}
BaseArray[bucket].AddLast(new KeyValuePair<TKey, TValue>(key, value));
ElementCount++;
}
public int GetNextPrime()
{
bool skipped = false;
for (int i = BaseArray.Length + 2; i < 1000; i += 2)
{
bool prime = IsPrime(i);
if (prime == true && skipped == true)
return i;
else if (prime && !skipped)
skipped = true;
}
return (2 * BaseArray.Length) + 1;
}
public bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
if (candidate == 2)
return true;
else
return false;
for (int i = 3; (i * i) <= candidate; i += 2)
if ((candidate % i) == 0)
return false;
return candidate != 1;
}
private void Resize()
{
LinkedList<KeyValuePair<TKey, TValue>>[] old_array = BaseArray;
LinkedList<KeyValuePair<TKey, TValue>>[] new_array = new LinkedList<KeyValuePair<TKey, TValue>>[GetNextPrime()];
BaseArray = new_array;
ElementCount = 0;
for (int index = 0; index < old_array.Length; index++)
if (old_array[index] != null)
foreach (KeyValuePair<TKey, TValue> pair in old_array[index])
Add(pair);
}
public void Clear()
{
BaseArray = new LinkedList<KeyValuePair<TKey, TValue>>[5];
ElementCount = 0;
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
for (int index = 0; index < BaseArray.Length; index++)
if (BaseArray[index] != null)
{
LinkedList<KeyValuePair<TKey, TValue>> list = BaseArray[index];
foreach (KeyValuePair<TKey, TValue> pair in list)
if (pair.Key.Equals(item.Key) && pair.Value.Equals(item.Value))
return true;
}
return false;
}
public bool ContainsKey(TKey key)
{
var temp = Keys;
foreach (TKey entry in temp)
if (entry.Equals(key))
return true;
return false;
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
// Not needed.
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
for (int index = 0; index < BaseArray.Length; index++)
if (BaseArray[index] != null)
{
LinkedList<KeyValuePair<TKey, TValue>> list = BaseArray[index];
foreach (KeyValuePair<TKey, TValue> pair in list)
yield return pair;
}
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
for (int index = 0; index < BaseArray.Length; index++)
foreach (KeyValuePair<TKey, TValue> pair in BaseArray[index])
if (pair.Equals(item)) //(pair.Value.Equals(item))
{
BaseArray[index].Remove(item);
return true;
}
return false;
}
public bool Remove(TKey key)
{
int index = GetHash(key);
if (BaseArray[index] == null)
return false;
foreach (KeyValuePair<TKey, TValue> pair in BaseArray[index])
if (pair.Key.Equals(key))
{
BaseArray[index].Remove(pair);
return true;
}
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
int bucket = GetHash(key);
if (BaseArray[bucket] == null)
{
value = default(TValue);
return false;
}
foreach (KeyValuePair<TKey, TValue> pair in BaseArray[bucket])
if (pair.Key.Equals(key))
{
value = pair.Value;
return true;
}
value = default(TValue);
return false;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private bool InList(LinkedList<KeyValuePair<TKey, TValue>> list, TKey key)
{
foreach (KeyValuePair<TKey, TValue> pair in list)
if (pair.Key.Equals(key))
return true;
return false;
}
private int GetHash(TKey key)
{
int hash = Math.Abs(key.GetHashCode());
return hash % BaseArray.Length;
}
private double GetRatio()
{
double ratio = (double)ElementCount / (double)BaseArray.Length;
return ratio;
}
}
}
view raw MyHashTable.cs hosted with ❤ by GitHub

That's all for now, thanks for reading!

Wednesday, April 6, 2016

CS 2420 - Assignment 6 - A Star

So this week we had to create a node graph and write our version of the A* (A Star) algorithm to find the shortest path. Here is the map we were given:



The map is not to scale, here are the coordinates of each node: 

A: -19, 11        B: -13, 13      C: 4, 14          D: -4, 12      E: -8, 3           F: -18, 1
G: -12, -8        H: 12, -9         I: -18, -11       J: -4, -11     K: -12, -14     L: 2, -18
M: 18, -13       N: 4, -9          O: 22, 11        P: 18, 3

I have seen multiple implementations of A* around the web, but they all use a matrix and it can get really complicated really quickly. I like this implementation better because its simple, but it works.

Here is my code:

using System;
using System.Collections.Generic;
namespace Assignment6
{
class AStar
{
private GraphNode NodeA, NodeB, NodeC, NodeD, NodeE, NodeF, NodeG, NodeH, NodeI, NodeJ,
NodeK, NodeL, NodeM, NodeN, NodeO, NodeP, Goal, Start;
private List<GraphNode> OpenList = new List<GraphNode>();
private List<GraphNode> CloseList = new List<GraphNode>();
private List<string> SolutionList = new List<string>();
public AStar(string input_start, string input_end)
{
Initialize(input_start, input_end);
}
private void Initialize(string input_start, string input_end)
{
List<GraphNode> node_list = new List<GraphNode>();
BuildNodes(node_list);
WireConnections();
SetEndpoints(node_list, input_start, input_end);
Start.CostSoFar = 0;
Start.Heuristic = CalculateDistance(Start, Goal);
Start.CameFrom = null;
OpenList.Add(Start);
RunAStar();
}
private void BuildNodes(List<GraphNode> node_list)
{
NodeA = new GraphNode() { Name = "A", X = -19, Y = 11, Connections = new Connection[2] };
NodeB = new GraphNode() { Name = "B", X = -13, Y = 13, Connections = new Connection[2] };
NodeC = new GraphNode() { Name = "C", X = 4, Y = 14, Connections = new Connection[3] };
NodeD = new GraphNode() { Name = "D", X = -4, Y = 12, Connections = new Connection[3] };
NodeE = new GraphNode() { Name = "E", X = -8, Y = 3, Connections = new Connection[7] };
NodeF = new GraphNode() { Name = "F", X = -18, Y = 1, Connections = new Connection[2] };
NodeG = new GraphNode() { Name = "G", X = -12, Y = -8, Connections = new Connection[3] };
NodeH = new GraphNode() { Name = "H", X = 12, Y = -9, Connections = new Connection[3] };
NodeI = new GraphNode() { Name = "I", X = -18, Y = -11, Connections = new Connection[2] };
NodeJ = new GraphNode() { Name = "J", X = -4, Y = -11, Connections = new Connection[5] };
NodeK = new GraphNode() { Name = "K", X = -12, Y = -14, Connections = new Connection[3] };
NodeL = new GraphNode() { Name = "L", X = 2, Y = -18, Connections = new Connection[3] };
NodeM = new GraphNode() { Name = "M", X = 18, Y = -13, Connections = new Connection[3] };
NodeN = new GraphNode() { Name = "N", X = 4, Y = -9, Connections = new Connection[3] };
NodeO = new GraphNode() { Name = "O", X = 22, Y = 11, Connections = new Connection[2] };
NodeP = new GraphNode() { Name = "P", X = 18, Y = 3, Connections = new Connection[4] };
node_list.Add(NodeA);
node_list.Add(NodeB);
node_list.Add(NodeC);
node_list.Add(NodeD);
node_list.Add(NodeE);
node_list.Add(NodeF);
node_list.Add(NodeG);
node_list.Add(NodeH);
node_list.Add(NodeI);
node_list.Add(NodeJ);
node_list.Add(NodeK);
node_list.Add(NodeL);
node_list.Add(NodeM);
node_list.Add(NodeN);
node_list.Add(NodeO);
node_list.Add(NodeP);
}
private void WireConnections()
{
NodeA.Connections[0] = new Connection() { Target = NodeB };
NodeA.Connections[1] = new Connection() { Target = NodeE };
NodeB.Connections[0] = new Connection() { Target = NodeA };
NodeB.Connections[1] = new Connection() { Target = NodeD };
NodeC.Connections[0] = new Connection() { Target = NodeD };
NodeC.Connections[1] = new Connection() { Target = NodeE };
NodeC.Connections[2] = new Connection() { Target = NodeP };
NodeD.Connections[0] = new Connection() { Target = NodeB };
NodeD.Connections[1] = new Connection() { Target = NodeC };
NodeD.Connections[2] = new Connection() { Target = NodeE };
NodeE.Connections[0] = new Connection() { Target = NodeA };
NodeE.Connections[1] = new Connection() { Target = NodeC };
NodeE.Connections[2] = new Connection() { Target = NodeD };
NodeE.Connections[3] = new Connection() { Target = NodeG };
NodeE.Connections[4] = new Connection() { Target = NodeH };
NodeE.Connections[5] = new Connection() { Target = NodeJ };
NodeE.Connections[6] = new Connection() { Target = NodeN };
NodeF.Connections[0] = new Connection() { Target = NodeG };
NodeF.Connections[1] = new Connection() { Target = NodeI };
NodeG.Connections[0] = new Connection() { Target = NodeF };
NodeG.Connections[1] = new Connection() { Target = NodeE };
NodeG.Connections[2] = new Connection() { Target = NodeJ };
NodeH.Connections[0] = new Connection() { Target = NodeN };
NodeH.Connections[1] = new Connection() { Target = NodeE };
NodeH.Connections[2] = new Connection() { Target = NodeP };
NodeI.Connections[0] = new Connection() { Target = NodeF };
NodeI.Connections[1] = new Connection() { Target = NodeK };
NodeJ.Connections[0] = new Connection() { Target = NodeK };
NodeJ.Connections[1] = new Connection() { Target = NodeG };
NodeJ.Connections[2] = new Connection() { Target = NodeE };
NodeJ.Connections[3] = new Connection() { Target = NodeN };
NodeJ.Connections[4] = new Connection() { Target = NodeL };
NodeK.Connections[0] = new Connection() { Target = NodeI };
NodeK.Connections[1] = new Connection() { Target = NodeJ };
NodeK.Connections[2] = new Connection() { Target = NodeL };
NodeL.Connections[0] = new Connection() { Target = NodeK };
NodeL.Connections[1] = new Connection() { Target = NodeJ };
NodeL.Connections[2] = new Connection() { Target = NodeM };
NodeM.Connections[0] = new Connection() { Target = NodeL };
NodeM.Connections[1] = new Connection() { Target = NodeP };
NodeM.Connections[2] = new Connection() { Target = NodeO };
NodeN.Connections[0] = new Connection() { Target = NodeJ };
NodeN.Connections[1] = new Connection() { Target = NodeE };
NodeN.Connections[2] = new Connection() { Target = NodeH };
NodeO.Connections[0] = new Connection() { Target = NodeP };
NodeO.Connections[1] = new Connection() { Target = NodeM };
NodeP.Connections[0] = new Connection() { Target = NodeH };
NodeP.Connections[1] = new Connection() { Target = NodeC };
NodeP.Connections[2] = new Connection() { Target = NodeO };
NodeP.Connections[3] = new Connection() { Target = NodeM };
}
private void SetEndpoints(List<GraphNode> nodeList, string inputStart, string inputEnd)
{
foreach (GraphNode currentNode in nodeList)
{
if (currentNode.Name == inputStart)
Start = currentNode;
if (currentNode.Name == inputEnd)
Goal = currentNode;
}
}
private void RunAStar()
{
GraphNode current;
while (OpenList.Count != 0)
{
current = FindBestNode();
RemoveFromOpenList(current);
ProcessConnections(current);
AddToCloseList(current);
}
}
private void ProcessNode(GraphNode current_node, GraphNode from_node)
{
current_node.CostSoFar += CalculateDistance(Start, current_node);
current_node.Heuristic = CalculateDistance(current_node, Goal);
current_node.CameFrom = from_node;
OpenList.Add(current_node);
}
private GraphNode FindBestNode()
{
GraphNode best_node = OpenList[0];
foreach (GraphNode list_node in OpenList)
if (list_node.TotalEstimatedCost < best_node.TotalEstimatedCost)
best_node = list_node;
return best_node;
}
private void RemoveFromOpenList(GraphNode node)
{
OpenList.Remove(node);
}
private void ProcessConnections(GraphNode current_node)
{
foreach (Connection connection in current_node.Connections)
{
if (InList(connection.Target, OpenList) || InList(connection.Target, CloseList))
{
double temp_csf = connection.Target.CostSoFar + CalculateDistance(current_node, connection.Target);
if (temp_csf < connection.Target.CostSoFar)
{
ProcessNode(connection.Target, current_node);
}
}
else
ProcessNode(connection.Target, current_node);
}
}
private void AddToCloseList(GraphNode node)
{
CloseList.Add(node);
}
private bool InList(GraphNode looking_for, List<GraphNode> list)
{
foreach (GraphNode node in list)
if (node == looking_for)
return true;
return false;
}
private double CalculateDistance(GraphNode start, GraphNode target)
{
return Math.Sqrt(Math.Pow(target.X - start.X, 2) + Math.Pow(target.Y - start.Y, 2));
}
public string ReconstructPath()
{
GraphNode runner = Goal;
while (runner != null)
{
SolutionList.Add(runner.Name);
runner = runner.CameFrom;
}
SolutionList.Reverse();
return string.Join(", ", SolutionList);
}
}
}
view raw AStar.cs hosted with ❤ by GitHub
namespace Assignment6
{
class Connection
{
public GraphNode Target { get; set; }
}
}
view raw Connection.cs hosted with ❤ by GitHub
namespace Assignment6
{
class GraphNode
{
public string Name { get; set; }
public Connection[] Connections { get; set; }
public GraphNode CameFrom { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Heuristic { get; set; }
public double CostSoFar { get; set; }
public double TotalEstimatedCost { get { return Heuristic + CostSoFar; } }
}
}
view raw GraphNode.cs hosted with ❤ by GitHub
using System;
namespace Assignment6
{
class MainClass
{
public static void Main()
{
Console.WriteLine("Pick the starting node:");
string inputStart = Console.ReadLine();
inputStart = inputStart.ToUpper();
Console.WriteLine();
Console.WriteLine("Pick the end node:");
string inputEnd = Console.ReadLine();
inputEnd = inputEnd.ToUpper();
Console.WriteLine();
AStar pathfinder = new AStar(inputStart, inputEnd);
string solution = pathfinder.ReconstructPath();
Console.WriteLine("The Path is: {0}\n", solution);
Console.WriteLine("Do you want to find another path? y/n\n");
string again = Console.ReadLine();
again = again.ToUpper();
Console.WriteLine();
if (again == "Y")
Main();
else
Environment.Exit(1);
}
}
}
view raw MainClass.cs hosted with ❤ by GitHub

That's all for now, thanks for reading!