Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DO NOT MERGE] added SimpleMinHeap #316

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions exercises/simple-min-heap/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
5 changes: 5 additions & 0 deletions exercises/simple-min-heap/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import PackageDescription

let package = Package(
name: "SimpleMinHeap"
)
109 changes: 109 additions & 0 deletions exercises/simple-min-heap/Sources/SimpleMinHeap/SimpleMinHeap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#if swift(>=4.0)
// Compatability for Swift < 4
#else
private extension Array {
mutating func swapAt(_ i: Index, _ j: Index) {
guard i != j else { return }
let tmp = self[i]
self[i] = self[j]
self[j] = tmp
}
}
#endif

extension SimpleMinHeap: CustomStringConvertible {
public var description: String {
return arrayView().description
}
}

public struct SimpleMinHeap<T> where T: Comparable {

private var array = [T]()

// View into the array represenation of the heap
func arrayView() -> [T] { return array }

// This adds a element to the end and moves it to the correct spot
mutating func push(_ item: T) {
array.append(item)
// Moves the element to the correct location
siftUp()
}

// Removes the root and return it
mutating func pop() -> T? {

// If the array is empty then return nil
guard let root = array.first else { return nil }

// Making sure there are a least two items, otherwise return the single root
guard array.count > 1 else { return root }

// Swaping values so root can be removed once at the end of array
array.swapAt(0, array.count - 1)

// Removing last items which should be the same as root
guard array.popLast() == root else { fatalError("Expected root value to be the same when moved to end of array") }

// Move the new root to the correct location
siftDown()

// Returning the old root capture before the sifting down.
return root
}

// Takes the root element and sifts it down into the correct location
// Assuming that the root has a least one child (at least 2 elements present).
private mutating func siftDown() {
var index = 0
while(index < array.count) {
let leftChildIndex = (2 * index) + 1
guard leftChildIndex < array.count, index != array.count - 1
else { break } // No more children or current item is the last in the array
let rightChildIndex = leftChildIndex + 1

// There is a right child with the name parent node
if(rightChildIndex < array.count && ((rightChildIndex - 1)/2) == index ) {
let left = array[leftChildIndex]
let right = array[rightChildIndex]
let minChildIndex = left < right ? leftChildIndex : rightChildIndex
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If left == right, which side should I choose? Does it matter? This impl chooses right side.

if (array[minChildIndex] < array[index]) {
array.swapAt(minChildIndex, index)
index = minChildIndex
} else { break }
} else if (array[leftChildIndex] < array[index] ) {
array.swapAt(leftChildIndex, index)
index = leftChildIndex
} else { break }
}

}

// Takes the last element inserted and sift it up to the correct location
// We assume that array is not empty here
private mutating func siftUp() {
guard !array.isEmpty
else { fatalError("Array is empty") }

guard array.count > 0 else { return }

var elementIndex = array.count - 1
var parentIndex = (elementIndex - 1 ) / 2

while (array[parentIndex] > array[elementIndex]) {
array.swapAt(elementIndex, parentIndex)
elementIndex = parentIndex
parentIndex = (elementIndex - 1 ) / 2
if (elementIndex == 0) {
break // We reached the root node
}
}
}
// Convinience function that takes in a array converts it into a heap
mutating func heapify(_ input: [T]) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for each in input {
push(each)
}
}
}
6 changes: 6 additions & 0 deletions exercises/simple-min-heap/Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import XCTest
@testable import SimpleMinHeapTests

XCTMain([
testCase(SimpleMinHeapTests.allTests),
])
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import XCTest
@testable import SimpleMinHeap

class SimpleMinHeapTests: XCTestCase {
func testSingleRoot() {
var heap = SimpleMinHeap<Int>()
heap.push(4)
XCTAssertEqual(4, heap.pop())
}

func testMultiplePush() {
var heap = SimpleMinHeap<Int>()
heap.push(4)
heap.push(1)
heap.push(7)
heap.push(9)
heap.push(2)
XCTAssertEqual(heap.arrayView(), [1, 2, 7, 9, 4])
}

func testMultiplePushAndPop() {
var heap = SimpleMinHeap<Int>()
heap.push(4)
heap.push(1)
heap.push(7)
heap.push(9)
heap.push(2)
XCTAssertEqual(heap.arrayView(), [1, 2, 7, 9, 4])
XCTAssertEqual(1, heap.pop())
XCTAssertEqual(heap.arrayView(), [2, 4, 7, 9])
XCTAssertEqual(2, heap.pop())
XCTAssertEqual(heap.arrayView(), [4, 9, 7])
}

func testMultipleValues() {
var heap = SimpleMinHeap<Int>()
heap.push(4)
heap.push(1)
heap.push(20)
heap.push(7)
heap.push(9)
heap.push(2)
XCTAssertEqual(1, heap.pop())
XCTAssertEqual(2, heap.pop())
XCTAssertEqual(4, heap.pop())
XCTAssertEqual(7, heap.pop())
XCTAssertEqual(9, heap.pop())
XCTAssertEqual(20, heap.pop())
}

func testMultipleStringValues() {
var heap = SimpleMinHeap<String>()
heap.push("Z")
heap.push("C")
heap.push("M")
heap.push("A")
heap.push("B")
heap.push("D")

XCTAssertEqual("A", heap.pop())
XCTAssertEqual("B", heap.pop())
XCTAssertEqual("C", heap.pop())
XCTAssertEqual("D", heap.pop())
XCTAssertEqual("M", heap.pop())
XCTAssertEqual("Z", heap.pop())
}

func testHeapify() {
var heap = SimpleMinHeap<String>()
heap.heapify(["Z", "C", "M", "A", "B", "D"])
XCTAssertEqual("A", heap.pop())
XCTAssertEqual("B", heap.pop())
XCTAssertEqual("C", heap.pop())
XCTAssertEqual("D", heap.pop())
XCTAssertEqual("M", heap.pop())
XCTAssertEqual("Z", heap.pop())
}

static var allTests = [
("testEmpty", testSingleRoot),
("testMultiplePush", testMultiplePush),
("testMultipleValues", testMultipleValues),
("testMultiplePushAndPop", testMultiplePushAndPop),
("testMultipleStringValues", testMultipleStringValues),
("testHeapify", testHeapify)
]
}