Skip to content

Instantly share code, notes, and snippets.

View chriswebb09's full-sized avatar

Christopher Webb chriswebb09

View GitHub Profile
struct HashTable<Key: Hashable, Value> {
// Hash table setup
func index(for key: Key) -> Int {
var divisor: Int = 0
for key in String(describing: key).unicodeScalars {
divisor += abs(Int(key.value.hashValue))
}
return abs(divisor) % buckets.count
}
}
struct HashTable<Key: Hashable, Value> {
typealias Bucket = [HashElement<Key, Value>]
var buckets: [Bucket]
init(capacity: Int) {
assert(capacity > 0)
buckets = Array<Bucket>(repeatElement([], count: capacity))
}
class HashElement<T: Hashable, U> {
var key: T
var value: U?
init(key: T, value: U?) {
self.key = key
self.value = value
}
}
struct Stack<T> {
var isEmpty: Bool {
return items.isEmpty
}
var count: Int {
return items.count
}
@chriswebb09
chriswebb09 / Queue.swift
Created May 12, 2017 00:50
Queue Data Structure
struct Queue<T> {
var list = LinkedList<T>()
mutating func enqueue(_ element: T) {
list.append(value: element)
}
mutating func dequeue() -> T? {
guard !list.isEmpty, let element = list.first else { return nil }
@chriswebb09
chriswebb09 / ItemPlaylist.swift
Created May 11, 2017 19:49
Linked Lists In Real World
import UIKit
class PlaylistItem {
var track: iTrack?
var next: PlaylistItem?
weak var previous: PlaylistItem?
}
extension PlaylistItem: Equatable {
static func ==(lhs: PlaylistItem, rhs: PlaylistItem) -> Bool {
class LinkedList<T> {
public typealias Node = LLNode<T>
private var head: Node?
private var tail: Node?
var isEmpty: Bool {
return head == nil
}
class LLNode<T> {
var value: T
var next: LLNode?
weak var previous: LLNode?
init(value: T) {
self.value = value
}
}
import UIKit
class PlaylistItem {
var track: iTrack?
var next: PlaylistItem?
weak var previous: PlaylistItem?
}
extension PlaylistItem: Equatable {
static func ==(lhs: PlaylistItem, rhs: PlaylistItem) -> Bool {
import UIKit
class Playlist {
private var head: PlaylistItem?
var itemCount: Int = 0
var isEmpty: Bool? {
return head == nil