Commit 30954f53 authored by Cody A Burchett's avatar Cody A Burchett

-m Heap for zac

parent 7d25f6be
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class Heap <Tile> where Tile : HeapItem<Tile>{
Tile[] heapTiles;
int itemCount;
//add heapIndex, compareTo to tile class
//compare fCost of node then hCost
public Heap(int maxSize)
{
heapTiles = new Tile[maxSize];
}
public void Add(Tile item)
{
item.heapIndex = itemCount;
heapTiles[itemCount] = item;
SortUp(item);
itemCount++;
}
public Tile RemoveFirst()
{
Tile first = heapTiles[0];
itemCount--;
heapTiles[0] = heapTiles[itemCount];
heapTiles[0].heapIndex = 0;
SortDown(heapTiles[0]);
return first;
}
public void UpdateItem(Tile item)
{
SortUp(item);
}
public int Count
{
get
{
return itemCount;
}
}
public bool Contains(Tile item)
{
return Equals(heapTiles[item.heapIndex], item);
}
void SortDown(Tile item)
{
while (true)
{
int leftChildIndex = item.heapIndex * 2 + 1;
int rightChildIndex = (item.heapIndex * 2) + 2;
int swapIndex = 0;
if (leftChildIndex < itemCount)
{
swapIndex = leftChildIndex;
if (rightChildIndex < itemCount)
{
if (heapTiles[leftChildIndex].CompareTo(heapTiles[rightChildIndex]) < 0)
{
swapIndex = rightChildIndex;
}
}
if (item.CompareTo(heapTiles[swapIndex]) < 0)
{
Swap(item, heapTiles[swapIndex]);
}
else
{
return;
}
}
else
{
return;
}
}
}
void SortUp(Tile item)
{
int indexOfParent = (item.heapIndex - 1) / 2;
while (true)
{
Tile parent = heapTiles[indexOfParent];
if (item.CompareTo(parent) > 0)
{
Swap(item, parent);
}
else
{
break;
}
indexOfParent = (item.heapIndex - 1) / 2;
}
}
void Swap(Tile item1, Tile item2)
{
heapTiles[item1.heapIndex] = item2;
heapTiles[item2.heapIndex] = item1;
int tempIndex = item1.heapIndex;
item1.heapIndex = item2.heapIndex;
item2.heapIndex = tempIndex;
}
}
public interface HeapItem<Tile> : IComparable<Tile>
{
int heapIndex
{
get;
set;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 243bb794b9f808b409bcd50557270e5b
timeCreated: 1477007304
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment