Oolite
Loading...
Searching...
No Matches
OOPriorityQueue.m
Go to the documentation of this file.
1/*
2
3OOPriorityQueue.m
4
5
6Copyright (C) 2007-2013 Jens Ayton
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the "Software"), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all
16copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25
26*/
27
28#include <assert.h>
29
31#import "OOPriorityQueue.h"
32
33/* Capacity grows by 50% each time. kMinCapacity must be at least 2 or Bad
34 Things will happen. Some examples of growth patterns based on kMinCapacity:
35 2: 2 3 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066...
36 4: 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599...
37 8: 8 12 18 27 40 60 90 135 202 303 454 681 1021 1531 2296...
38 16: 16 24 36 54 81 121 181 271 406 609 913 1369 2053 3079...
39 32: 32 48 72 108 162 243 364 546 819 1228 1842 2763 4144...
40
41 Special cases: when an OOPriorityQueue is copied, the copy's capacity is
42 set to the same as its count, which may be less than kMinCapacity. However,
43 when it is grown, it will be set to at least kMinCapacity (except in the
44 case of a reallocation failure, in which case an attempt will be made to
45 grow capacity by one element).
46*/
47enum {
49};
50
51/* Functions to navigate the binary heap.
52 Using one-based indices, the following hold:
53 * The left child of a node, L(n), is 2n.
54 * The right child of a node, R(n), is 2n + 1.
55 * The parent of a node, P(n), is n/2 for n > 1.
56
57 Using zero-based indices, we must convert to and from one-based indices to
58 perform these calculations, giving:
59 * Lz(n) = L(n+1)-1 = (2(n+1))-1 = 2n+1
60 * Rz(n) = R(n+1)-1 = (2(n+1)+1)-1 = 2n+2
61 * Pz(n) = P(n+1)-1 = ((n+1)/2)-1
62*/
63
64OOINLINE NSUInteger PQLeftChild(NSUInteger n) INLINE_CONST_FUNC;
65OOINLINE NSUInteger PQRightChild(NSUInteger n) INLINE_CONST_FUNC;
66OOINLINE NSUInteger PQParent(NSUInteger n) INLINE_CONST_FUNC;
67
68OOINLINE NSUInteger PQLeftChild(NSUInteger n)
69{
70 return (n << 1) + 1;
71}
72
73OOINLINE NSUInteger PQRightChild(NSUInteger n)
74{
75 return (n << 1) + 2;
76}
77
78OOINLINE NSUInteger PQParent(NSUInteger n)
79{
80 return ((n + 1) >> 1) - 1;
81}
82
83typedef NSComparisonResult (*CompareIMP)(id self, SEL _cmd, id other);
84
85OOINLINE NSComparisonResult PQCompare(id a, id b, SEL comparator)
86{
87 CompareIMP compare = NULL;
88 NSComparisonResult result;
89
90 // This is equivalent to [a performSelector:comparator withObject:b], except the resulting value isn't an object.
91 compare = (CompareIMP)[a methodForSelector:comparator];
92 result = compare(a, comparator, b);
93 return result;
94}
95
96// Private priority queue methods.
97@interface OOPriorityQueue (Private)
98
99- (void)makeObjectsPerformSelector:(SEL)selector;
100
101- (void)bubbleUpFrom:(NSUInteger)i;
102- (void)bubbleDownFrom:(NSUInteger)i;
103
104- (void)growBuffer;
105- (void)shrinkBuffer;
106
107- (void)removeObjectAtIndex:(NSUInteger)i;
108
109#if OO_DEBUG
110- (void)appendDebugDataToString:(NSMutableString*)string index:(NSUInteger)i depth:(NSUInteger)depth;
111#endif
112
113@end
114
115// NSEnumerator subclass to pull objects from queue.
116@interface OOPriorityQueueEnumerator : NSEnumerator {
117@private
119}
120
121- (id)initWithPriorityQueue:(OOPriorityQueue*)queue;
122
123@end
124
125@implementation OOPriorityQueue
126
127+ (instancetype)queueWithComparator:(SEL)comparator
128{
129 return [[[self alloc] initWithComparator:comparator] autorelease];
130}
131
132- (id)initWithComparator:(SEL)comparator
133{
134 if (comparator == NULL) {
135 [self release];
136 return nil;
137 }
138
139 self = [super init];
140 if (self != nil) {
141 _comparator = comparator;
142 }
143
144 return self;
145}
146
147- (id)init
148{
149 return [self initWithComparator:@selector(compare:)];
150}
151
152- (void)dealloc
153{
154 [self makeObjectsPerformSelector:@selector(release)];
155 free(_heap);
156
157 [super dealloc];
158}
159
160- (NSString*)description
161{
162 return [NSString stringWithFormat:@"<%@ %p>{count=%zu, capacity=%zu}", [self class], self, _count, _capacity];
163}
164
165#if OO_DEBUG
166- (NSString*)debugDescription
167{
168 NSMutableString* result = nil;
169
170 result = [NSMutableString string];
171 [result appendFormat:@"<%@ %p> (count=%zu, capacity=%zu, comparator=%@)", [self class], self, _count, _capacity, NSStringFromSelector(_comparator)];
172
173 if (_count != 0) {
174 [result appendString:@"\n{\n"];
175 [self appendDebugDataToString:result index:0 depth:0];
176 [result appendString:@"}"];
177 } else {
178 [result appendString:@" {}"];
179 }
180 return result;
181}
182#endif
183
184- (BOOL)isEqual:(id)object
185{
186 NSUInteger i;
187 OOPriorityQueue *selfCopy = nil, *otherCopy = nil;
188 BOOL identical = YES;
189
190 if (object == self)
191 return YES;
192 if (![object isKindOfClass:[self class]])
193 return NO;
194
195 if (_count != [object count])
196 return NO;
197 if (_count == 0)
198 return YES;
199
200 selfCopy = [self copy];
201 otherCopy = [object copy];
202 i = _count;
203 while (i--) {
204 if (![[selfCopy nextObject] isEqual:[otherCopy nextObject]]) {
205 identical = NO;
206 break;
207 }
208 }
209 [selfCopy release];
210 [otherCopy release];
211
212 return identical;
213}
214
215- (NSUInteger)hash
216{
217 if (_count == 0)
218 return NSNotFound;
219 return _count ^ [_heap[0] hash];
220}
221
222- (id)copyWithZone:(NSZone*)zone
223{
224 OOPriorityQueue* copy = nil;
225
226 copy = [[self class] allocWithZone:zone];
227 if (copy != nil) {
228 copy->_comparator = _comparator;
229 copy->_count = _count;
230 copy->_capacity = _count;
231
232 copy->_heap = malloc(_count * sizeof(id));
233 if (copy->_heap != NULL) {
234 memcpy(copy->_heap, _heap, _count * sizeof(id));
235 [copy makeObjectsPerformSelector:@selector(retain)];
236 } else if (_count != 0) {
237 [copy release];
238 copy = nil;
239 }
240 }
241
242 return copy;
243}
244
245- (void)addObject:(id)object
246{
247 NSUInteger i;
248
249 // Validate object
250 if (object == nil) {
251 [NSException raise:NSInvalidArgumentException
252 format:@"Attempt to insert nil into OOPriorityQueue."];
253 }
254
255 if (![object respondsToSelector:_comparator]) {
256 [NSException raise:NSInvalidArgumentException
257 format:@"Attempt to insert object (%@) which does not support comparator %@ into OOPriorityQueue.",
258 object, NSStringFromSelector(_comparator)];
259 }
260
261 // Ensure there is sufficent space.
262 if (_count == _capacity)
263 [self growBuffer];
264
265 // insert object at end of buffer.
266 i = _count++;
267 _heap[i] = object;
268
269 [self bubbleUpFrom:i];
270 [object retain];
271}
272
273- (void)removeObject:(id)object
274{
275 NSUInteger i;
276
277 /* Perform linear search for object (using comparator). A depth-first
278 search could skip leaves of lower priority, but I don't expect this to
279 be called very often.
280 */
281
282 if (object == nil)
283 return;
284
285 for (i = 0; i < _count; ++i) {
286 if (PQCompare(object, _heap[i], _comparator) == 0) {
287 [self removeObjectAtIndex:i];
288 }
289 }
290}
291
292- (void)removeExactObject:(id)object
293{
294 NSUInteger i;
295
296 if (object == nil)
297 return;
298
299 for (i = 0; i < _count; ++i) {
300 if (object == _heap[i]) {
301 [self removeObjectAtIndex:i];
302 }
303 }
304}
305
306- (NSUInteger)count
307{
308 return _count;
309}
310
312{
313 id result = [self peekAtNextObject];
314 [self removeNextObject];
315 return result;
316}
317
319{
320 if (_count == 0)
321 return nil;
322 // return [[_heap[0] retain] autorelease];
323 return _heap[0];
324}
325
327{
328 [self removeObjectAtIndex:0];
329}
330
331- (void)addObjects:(id)collection
332{
333 id value = nil;
334
335 if ([collection respondsToSelector:@selector(objectEnumerator)])
336 collection = [collection objectEnumerator];
337 if (![collection respondsToSelector:@selector(nextObject)])
338 return;
339
340 while ((value = [collection nextObject]))
341 [self addObject:value];
342}
343
344- (NSArray*)sortedObjects
345{
346 return [[self objectEnumerator] allObjects];
347}
348
349- (NSEnumerator*)objectEnumerator
350{
351 return [[[OOPriorityQueueEnumerator alloc] initWithPriorityQueue:self] autorelease];
352}
353
354@end
355
356@implementation OOPriorityQueue (Private)
357
358- (void)makeObjectsPerformSelector:(SEL)selector
359{
360 NSUInteger i;
361
362 if (selector == NULL)
363 return;
364
365 for (i = 0; i != _count; ++i) {
366 [_heap[i] performSelector:selector];
367 }
368}
369
370- (void)bubbleUpFrom:(NSUInteger)i
371{
372 NSUInteger pi;
373 id obj = nil, par = nil;
374
375 while (0 < i) {
376 pi = PQParent(i);
377 obj = _heap[i];
378 par = _heap[pi];
379
380 if (PQCompare(obj, par, _comparator) < 0) {
381 _heap[i] = par;
382 _heap[pi] = obj;
383 i = pi;
384 } else
385 break;
386 }
387}
388
389- (void)bubbleDownFrom:(NSUInteger)i
390{
391 NSUInteger end = _count - 1;
392 NSUInteger li, ri, next;
393 id obj = nil;
394
395 obj = _heap[i];
396 while (PQLeftChild(i) <= end) {
397 li = PQLeftChild(i);
398 ri = PQRightChild(i);
399
400 // If left child has lower priority than right child, or there is only one child...
401 if (li == end || PQCompare(_heap[li], _heap[ri], _comparator) < 0) {
402 next = li;
403 } else {
404 next = ri;
405 }
406
407 if (PQCompare(_heap[next], obj, _comparator) < 0) {
408 // Exchange parent with lowest-priority child
409 _heap[i] = _heap[next];
410 _heap[next] = obj;
411 i = next;
412 } else
413 break;
414 }
415}
416
418{
419 id* newBuffer = NULL;
420 NSUInteger newCapacity;
421
422 newCapacity = _capacity * 3 / 2;
423 if (newCapacity < kMinCapacity)
424 newCapacity = kMinCapacity;
425
426 // Note: realloc(NULL, size) with non-zero size is equivalent to malloc(size), so this is OK starting from a NULL buffer.
427 newBuffer = realloc(_heap, newCapacity * sizeof(id));
428 if (newBuffer == NULL) {
429 // Attempt to grow by just one waffer-thin slot.
430 newCapacity = _capacity + 1;
431 newBuffer = realloc(_heap, newCapacity * sizeof(id));
432
433 if (newBuffer == NULL) {
434 // Failed to grow.
435 [NSException raise:NSMallocException
436 format:@"Could not expand capacity of OOPriorityQueue."];
437 }
438 }
439
440 _heap = newBuffer;
441 _capacity = newCapacity;
442
443 assert(_count < _capacity);
444}
445
447{
448 NSUInteger amountToRemove;
449 id* newBuffer = NULL;
450 NSUInteger newCapacity;
451
452 if (kMinCapacity < _capacity) {
453 // Remove two thirds of free space, if at least three slots are free.
454 amountToRemove = (_capacity - _count) * 2 / 3;
455 if (2 < amountToRemove) {
456 newCapacity = _capacity - amountToRemove;
457 newBuffer = realloc(_heap, newCapacity * sizeof(id));
458 if (newBuffer != NULL) {
459 _heap = newBuffer;
460 _capacity = newCapacity;
461 }
462 }
463 }
464}
465
466- (void)removeObjectAtIndex:(NSUInteger)i
467{
468 id object = nil;
469
470 if (_count <= i)
471 return;
472
473 object = _heap[i];
474 if (i < --_count) {
475 // Overwrite object with last object in array
476 _heap[i] = _heap[_count];
477
478 // Push previously-last object down until tree is partially ordered.
479 [self bubbleDownFrom:i];
480 } else {
481 // Special case: removing last (or only) object. No bubbling needed.
482 }
483
484 [object autorelease];
485 if ((_count * 2) <= _capacity)
486 [self shrinkBuffer];
487}
488
489#if OO_DEBUG
490- (void)appendDebugDataToString:(NSMutableString*)string index:(NSUInteger)i depth:(NSUInteger)depth
491{
492 NSUInteger spaces;
493
494 if (_count <= i)
495 return;
496
497 spaces = 2 + depth;
498 while (spaces--)
499 [string appendString:@" "];
500 [string appendString:[_heap[i] description]];
501 [string appendString:@"\n"];
502
503 [self appendDebugDataToString:string index:PQLeftChild(i) depth:depth + 1];
504 [self appendDebugDataToString:string index:PQRightChild(i) depth:depth + 1];
505}
506#endif
507
508@end
509
510@implementation OOPriorityQueueEnumerator
511
512- (id)initWithPriorityQueue:(OOPriorityQueue*)queue
513{
514 if (queue == nil) {
515 [self release];
516 return nil;
517 }
518
519 self = [super init];
520 if (self != nil) {
521 _queue = [queue retain];
522 }
523 return self;
524}
525
526- (void)dealloc
527{
528 [_queue release];
529
530 [super dealloc];
531}
532
534{
535 id value = [_queue nextObject];
536 if (value == nil) {
537 // Maintain enumerator semantics by ensuring we don't start returning new values after returning nil.
538 [_queue release];
539 _queue = nil;
540 }
541 return value;
542}
543
544@end
545
546#if DEBUG_GRAPHVIZ
547@implementation OOPriorityQueue (DebugGraphViz)
548
549static NSString* EscapedString(NSString* string)
550{
551 NSString* srcStrings[] = {
552 // Note: backslash must be first.
553 @"\\", @"\"", @"\'", @"\r", @"\n", @"\t", nil
554 };
555 NSString* subStrings[] = {
556 // Note: must be same order.
557 @"\\\\", @"\\\"", @"\\\'", @"\\r", @"\\n", @"\\t", nil
558 };
559
560 NSString **src = srcStrings, **sub = subStrings;
561 NSMutableString* mutable = nil;
562 NSString* result = nil;
563
564 mutable = [string mutableCopy];
565 while (*src != nil) {
566 [mutable replaceOccurrencesOfString:*src++
567 withString:*sub++
568 options:0
569 range:NSMakeRange(0, [mutable length])];
570 }
571
572 if ([mutable length] == [string length]) {
573 result = string;
574 } else {
575 result = [[mutable copy] autorelease];
576 }
577 [mutable release];
578 return result;
579}
580
581- (NSString*)generateGraphViz
582{
583 NSMutableString* result = nil;
584 NSUInteger i;
585 id node = nil;
586 NSString* desc = nil;
587
588 result = [NSMutableString string];
589
590 // Header
591 [result appendString:
592 @"// OOPriorityQueue partially ordered tree dump\n\n"
593 "digraph heap\n"
594 "{\n"
595 "\tgraph [charset=\"UTF-8\", label=\"OOPriorityQueue heap dump\", labelloc=t, labeljust=l];\n"
596 "\tnode [shape=record];\n\t\n\t"];
597
598 // Nodes
599 for (i = 0; i < _count; ++i) {
600 node = _heap[i];
601 desc = [node description];
602 if ([desc length] > 70) {
603 desc = [[desc substringToIndex:64] stringByAppendingString:@"..."];
604 }
605
606 [result appendFormat:@"\tnode_%zu [label=\"<f0> | <f1> %@ | <f2>\"];\n", i, EscapedString(desc)];
607 }
608
609 // Arcs
610 for (i = 0; PQLeftChild(i) < _count; ++i) {
611 [result appendFormat:@"\tnode_%zu:f0 -> node_%zu:f1;\n", i, PQLeftChild(i)];
612 if (PQRightChild(i) < _count)
613 [result appendFormat:@"\tnode_%zu:f2 -> node_%zu:f1;\n", i, PQRightChild(i)];
614 }
615
616 [result appendString:@"}\n"];
617
618 return result;
619}
620
621- (void)writeGraphVizToURL:(NSURL*)url
622{
623 NSString* graphViz = nil;
624 NSData* data = nil;
625
626 graphViz = [self generateGraphViz];
627 data = [graphViz dataUsingEncoding:NSUTF8StringEncoding];
628
629 if (data != nil) {
630 [data writeToURL:url atomically:YES];
631 }
632}
633
634- (void)writeGraphVizToPath:(NSString*)path
635{
636 [self writeGraphVizToURL:[NSURL fileURLWithPath:path]];
637}
638
639@end
640#endif
#define INLINE_CONST_FUNC
#define OOINLINE
OOINLINE NSComparisonResult PQCompare(id a, id b, SEL comparator)
OOINLINE NSUInteger PQLeftChild(NSUInteger n) INLINE_CONST_FUNC
OOINLINE NSUInteger PQRightChild(NSUInteger n) INLINE_CONST_FUNC
OOINLINE NSUInteger PQParent(NSUInteger n) INLINE_CONST_FUNC
NSComparisonResult(* CompareIMP)(id self, SEL _cmd, id other)
@ kMinCapacity
return nil
void addObject:(id object)
OO_PQ_STRONG id * _heap
void removeObjectAtIndex:(NSUInteger i)
void makeObjectsPerformSelector:(SEL selector)
id initWithComparator:(SEL comparator)
NSUInteger _capacity
NSArray * sortedObjects()
void bubbleUpFrom:(NSUInteger i)
NSString * description()
NSEnumerator * objectEnumerator()
void bubbleDownFrom:(NSUInteger i)