Project

General

Profile

root / branches / compiler / cSharp / ooasCompiler / src / libs / c5 / UserGuideExamples / DecreaseIncreaseKey.cs @ 3

1
/*
2
 Copyright (c) 2003-2008 Niels Kokholm and Peter Sestoft
3
 Permission is hereby granted, free of charge, to any person obtaining a copy
4
 of this software and associated documentation files (the "Software"), to deal
5
 in the Software without restriction, including without limitation the rights
6
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
 copies of the Software, and to permit persons to whom the Software is
8
 furnished to do so, subject to the following conditions:
9
 
10
 The above copyright notice and this permission notice shall be included in
11
 all copies or substantial portions of the Software.
12
 
13
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
 SOFTWARE.
20
*/
21

    
22
// C5 example: Decrease key and increase key pattern chapter
23

    
24
// Compile with 
25
//   csc /r:C5.dll DecreaseIncreaseKey.cs 
26

    
27
using System;
28
using C5;
29
using SCG = System.Collections.Generic;
30

    
31
class MyTest {
32
  public static void Main(String[] args) {
33
    IPriorityQueue<Prio<String>> pq = new IntervalHeap<Prio<String>>();
34
    IPriorityQueueHandle<Prio<String>> h1, h2, h3;
35
    h1 = h2 = h3 = null;
36
    pq.Add(ref h1, new Prio<String>("surfing", 10));
37
    pq.Add(ref h2, new Prio<String>("shopping", 6));
38
    pq.Add(ref h3, new Prio<String>("cleaning", 4));
39
    // The following is legal because +, - are overloaded on (Prio<D>,int):
40
    pq[h2] -= 5;
41
    pq[h1] += 5;
42
    while (!pq.IsEmpty) 
43
      Console.WriteLine(pq.DeleteMin());
44
  }
45
}
46

    
47
struct Prio<D> : IComparable<Prio<D>> where D : class  {
48
  public readonly D data;
49
  private int priority;
50

    
51
  public Prio(D data, int priority) {
52
    this.data = data; 
53
    this.priority = priority;
54
  }
55
  
56
  public int CompareTo(Prio<D> that) {
57
    return this.priority.CompareTo(that.priority);
58
  }
59

    
60
  public bool Equals(Prio<D> that) {
61
    return this.priority == that.priority;
62
  }
63

    
64
  public static Prio<D> operator+(Prio<D> tp, int delta) {
65
    return new Prio<D>(tp.data, tp.priority + delta);
66
  }
67

    
68
  public static Prio<D> operator-(Prio<D> tp, int delta) {
69
    return new Prio<D>(tp.data, tp.priority - delta);
70
  }
71

    
72
  public override String ToString() {
73
    return String.Format("{0}[{1}]", data, priority);
74
  }
75
}