source: src/main/java/agents/anac/y2011/TheNegotiator/Queue.java@ 84

Last change on this file since 84 was 1, checked in by Wouter Pasman, 6 years ago

Initial import : Genius 9.0.0

File size: 2.8 KB
Line 
1package agents.anac.y2011.TheNegotiator;
2
3/**
4 * Array-based implementation of the queue.
5 * @author Mark Allen Weiss
6 */
7public class Queue {
8
9 private Double [] theArray;
10 private int currentSize;
11 private int front;
12 private int back;
13
14 private static final int DEFAULT_CAPACITY = 15;
15
16 /**
17 * Construct the queue.
18 */
19 public Queue() {
20 theArray = new Double[DEFAULT_CAPACITY];
21 makeEmpty( );
22 }
23
24
25 /**
26 * Test if the queue is logically empty.
27 * @return true if empty, false otherwise.
28 */
29 public boolean isEmpty() {
30 return currentSize == 0;
31 }
32
33 /**
34 * Make the queue logically empty.
35 */
36 public void makeEmpty() {
37 currentSize = 0;
38 front = 0;
39 back = -1;
40 }
41
42 /**
43 * Return and remove the least recently inserted item
44 * from the queue.
45 * @return the least recently inserted item in the queue.
46 * @throws UnderflowException if the queue is empty.
47 */
48 public Double dequeue( )
49 {
50 currentSize--;
51
52 Double returnValue = theArray[front];
53 front = increment( front );
54 return returnValue;
55 }
56
57 /**
58 * Get the least recently inserted item in the queue.
59 * Does not alter the queue.
60 * @return the least recently inserted item in the queue.
61 * @throws UnderflowException if the queue is empty.
62 */
63 public Double getFront( )
64 {
65 return theArray[ front ];
66 }
67
68 /**
69 * Insert a new item into the queue.
70 * @param x the item to insert.
71 */
72 public void enqueue( Double x )
73 {
74 if( currentSize == theArray.length )
75 doubleQueue( );
76 back = increment( back );
77 theArray[ back ] = x;
78 currentSize++;
79 }
80
81 /**
82 * Internal method to increment with wraparound.
83 * @param x any index in theArray's range.
84 * @return x+1, or 0 if x is at the end of theArray.
85 */
86 private int increment( int x )
87 {
88 if( ++x == theArray.length )
89 x = 0;
90 return x;
91 }
92
93 /**
94 * Internal method to expand theArray.
95 */
96 private void doubleQueue( )
97 {
98 Double [ ] newArray;
99
100 newArray = new Double[ theArray.length * 2 ];
101
102 // Copy elements that are logically in the queue
103 for( int i = 0; i < currentSize; i++, front = increment( front ) )
104 newArray[ i ] = theArray[ front ];
105
106 theArray = newArray;
107 front = 0;
108 back = currentSize - 1;
109 }
110
111 public int size() {
112 return currentSize;
113 }
114
115 /**
116 * @return array of queue (watch out, contains empty cells)
117 */
118 public Double[] toArray() {
119 return theArray;
120 }
121}
122
Note: See TracBrowser for help on using the repository browser.