코딩하는 나귀



PriorityQueue.cs


A* 로 길찿기를 구현하던중 우선순위큐가 필요해서 리스트를 감싸서 추상화해서 만들어 봤습니다. 내부는 힙정렬로 동작합니다. 오름차순, 내림차순 지원하고 아래는 테스트 코드 입니다.


[수정사항]

2015.7.27 - IComparable을 사용하도록 변경


[코드]


public class TestItem : IComparable {

    public int Weight { get; private set; }

    public TestItem (int weight) {

        Weight = weight;

    }


    public int CompareTo (object other) {

        if ((other is TestItem) == false) return 0;

        return Weight.CompareTo((other as TestItem).Weight);

    }

}

.

.

.

PriorityQueue<TestItem> priorityQueue = new PriorityQueue<TestItem>();

priorityQueue.Add(new TestItem(5));

priorityQueue.Add(new TestItem(3));

priorityQueue.Add(new TestItem(7));

priorityQueue.Add(new TestItem(2));

priorityQueue.Add(new TestItem(6));

priorityQueue.Add(new TestItem(9));

priorityQueue.Add(new TestItem(1));

priorityQueue.Add(new TestItem(4));

priorityQueue.Add(new TestItem(8));

while (priorityQueue.Count > 0) Debug.Log(priorityQueue.Pop().Weight);


[결과]

1

2

3

4

5

6

7

8

9



'Unity' 카테고리의 다른 글

그라데이션 배경 (Gradient Shader 활용)  (0) 2015.11.19
[Shader] 그라데이션 (Gradient)  (0) 2015.11.19
[Struct] Point  (0) 2015.11.07
[Struct] Size  (0) 2015.11.07
[Shader] 텍스처 회전 (Texture Rotation)  (0) 2015.09.08
리플렉션 응용 (C# Reflection)  (0) 2015.07.01
MonoBehaviour Lifecycle  (0) 2014.06.30
Android Local Notification Plugin  (0) 2013.04.23
포물선 공식  (0) 2013.01.21
케릭터 점프 코드  (0) 2013.01.15