Skip to content

Commit 26d4da6

Browse files
authored
Merge pull request kodecocodes#164 from lionel0806/master
Processing index out of bounds
2 parents 912c21d + d67c81f commit 26d4da6

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

Heap/Heap.swift

+4
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,8 @@ public struct Heap<T> {
112112
* larger than the old one; in a min-heap it should be smaller.
113113
*/
114114
public mutating func replace(index i: Int, value: T) {
115+
guard i < elements.count else { return }
116+
115117
assert(isOrderedBefore(value, elements[i]))
116118
elements[i] = value
117119
shiftUp(index: i)
@@ -141,6 +143,8 @@ public struct Heap<T> {
141143
* to know the node's index, which may actually take O(n) steps to find.
142144
*/
143145
public mutating func removeAtIndex(i: Int) -> T? {
146+
guard i < elements.count else { return nil }
147+
144148
let size = elements.count - 1
145149
if i != size {
146150
swap(&elements[i], &elements[size])

Heap/Tests/HeapTests.swift

+11
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,12 @@ class HeapTests: XCTestCase {
196196
XCTAssertTrue(verifyMaxHeap(h))
197197
XCTAssertEqual(h.elements, [100, 50, 70, 10, 20, 60, 65])
198198

199+
//test index out of bounds
200+
let v = h.removeAtIndex(10)
201+
XCTAssertEqual(v, nil)
202+
XCTAssertTrue(verifyMaxHeap(h))
203+
XCTAssertEqual(h.elements, [100, 50, 70, 10, 20, 60, 65])
204+
199205
let v1 = h.removeAtIndex(5)
200206
XCTAssertEqual(v1, 60)
201207
XCTAssertTrue(verifyMaxHeap(h))
@@ -308,5 +314,10 @@ class HeapTests: XCTestCase {
308314
h.replace(index: 5, value: 13)
309315
XCTAssertTrue(verifyMaxHeap(h))
310316
XCTAssertEqual(h.elements, [16, 14, 13, 8, 7, 10, 3, 2, 4, 1])
317+
318+
//test index out of bounds
319+
h.replace(index: 20, value: 2)
320+
XCTAssertTrue(verifyMaxHeap(h))
321+
XCTAssertEqual(h.elements, [16, 14, 13, 8, 7, 10, 3, 2, 4, 1])
311322
}
312323
}

0 commit comments

Comments
 (0)