-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPixelQueue.java
More file actions
76 lines (64 loc) · 1.6 KB
/
Copy pathPixelQueue.java
File metadata and controls
76 lines (64 loc) · 1.6 KB
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 com.company;
import java.util.Arrays;
/**
* Created by sky on 5/21/15.
* Priority pixel queue, supports O(1) lookups, addition, and removal.
*/
public class PixelQueue {
// Array of pixels, some can be null
public Pixel[] pixels;
// Number of entries in queue
public int count = 0;
// First unused index (where we can add to)
public int usedUntil;
public PixelQueue() {
pixels = new Pixel[1024];
}
/**
* Add pixel to queue
* @param p
*/
public void add(Pixel p) {
assert(p.queueIndex == -1);
if (usedUntil == pixels.length) {
pixels = Arrays.copyOf(pixels, pixels.length*2);
}
pixels[usedUntil] = p;
p.queueIndex = usedUntil;
usedUntil++;
count++;
}
/**
* Removes a pixel from the queue
* @param p
*/
public void remove(Pixel p){
assert(p.queueIndex > -1);
pixels[p.queueIndex] = null;
p.queueIndex = -1;
count--;
}
/**
* Reads a pixel, while maintaining its associated data.
* Primarily used for restructuring / compressing array.
* @param p
*/
public void readd(Pixel p){
remove(p);
add(p);
}
/**
* Compresses array by moving elements to front.
*/
public void compress() {
if ((double)usedUntil / count < 1.05){
return; // Allow up to 5% of space wasted
}
usedUntil = 0;
for (int i = 0; usedUntil < count; i++){
if (pixels[i] != null){
readd(pixels[i]);
}
}
}
}