Normand Briere
2019-09-30 3966454055db8e04700e881a091c2d33dcfda232
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//package edu.wlu.cs.levy.CG;
 
import java.util.*;
 
// Bjoern Heckel's solution to the KD-Tree n-nearest-neighbor problem
 
class NearestNeighborList<T> {
 
    static class NeighborEntry<T> implements Comparable<NeighborEntry<T>> {
        final T data;
        final double value;
 
        public NeighborEntry(final T data,
                             final double value) {
            this.data = data;
            this.value = value;
        }
 
        public int compareTo(NeighborEntry<T> t) {
            // note that the positions are reversed!
            return Double.compare(t.value, this.value);
        }
    };
 
    java.util.PriorityQueue<NeighborEntry<T>> m_Queue;
    int m_Capacity = 0;
 
    // constructor
    public NearestNeighborList(int capacity) {
        m_Capacity = capacity;
        m_Queue = new java.util.PriorityQueue<NeighborEntry<T>>(m_Capacity);
    }
 
    public double getMaxPriority() {
        NeighborEntry p = m_Queue.peek();
        return (p == null) ? Double.POSITIVE_INFINITY : p.value ;
    }
 
    public boolean insert(T object, double priority) {
        if (isCapacityReached()) {
            if (priority > getMaxPriority()) {
                // do not insert - all elements in queue have lower priority
                return false;
            }
            m_Queue.add(new NeighborEntry<T>(object, priority));
            // remove object with highest priority
            m_Queue.poll();
        } else {
            m_Queue.add(new NeighborEntry<T>(object, priority));
        }
        return true;
    }
 
    public boolean isCapacityReached() {
        return m_Queue.size()>=m_Capacity;
    }
 
    public T getHighest() {
        NeighborEntry<T> p = m_Queue.peek();
        return (p == null) ?  null : p.data ;
    }
 
    public boolean isEmpty() {
        return m_Queue.size()==0;
    }
 
    public int getSize() {
        return m_Queue.size();
    }
 
    public T removeHighest() {
        // remove object with highest priority
        NeighborEntry<T> p = m_Queue.poll();
        return (p == null) ?  null : p.data ;
    }
}