Created
December 30, 2014 20:54
-
-
Save linkov/c7cd63bf0031422157b2 to your computer and use it in GitHub Desktop.
Simle hash table implementation in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class SDWHashTable { | |
var arr:[Array<String>] = []; | |
var maxArraySize = 5; | |
convenience init(maxSize: Int) { | |
self.init() | |
self.maxArraySize = maxSize | |
self.constuctDataStucture() | |
} | |
// MARK: - API | |
func containsObject(str: String) -> Bool { | |
let indexForHash = hashFromString(str, tableSize: maxArraySize) | |
let arrayAtindex:Array = arr[indexForHash] | |
for arrStr in arrayAtindex { | |
if str == arrStr { | |
return true; | |
} | |
} | |
return false; | |
} | |
func addObject(str: String) -> Void { | |
let indexForHash = hashFromString(str, tableSize: maxArraySize) | |
var arrayAtindex:Array = arr[indexForHash] | |
arrayAtindex.append(str) | |
arr[indexForHash] = arrayAtindex | |
} | |
func removeObject(str: String) -> Void { | |
let indexForHash = hashFromString(str, tableSize: maxArraySize) | |
let arrayAtindex:Array = arr[indexForHash] | |
arr[indexForHash] = arrayAtindex.filter( {$0 != str} ) | |
} | |
// MARK: - private | |
/* instead of simple strings we will store arrays to handle cases when hash is the same for 2 values */ | |
private func constuctDataStucture() -> Void { | |
for index in 0...maxArraySize { | |
let innerArray:Array<String> = [] | |
arr.insert(innerArray, atIndex: index) | |
} | |
} | |
/* create hash from summ of unicode char numbers % array count */ | |
private func hashFromString(personName: String?, tableSize: Int) -> Int { | |
if let existingName = personName { | |
var summOfCharacterCodes:Int = 0 | |
let characterCount = existingName.utf16Count | |
let charArr:Array = existingName.cStringUsingEncoding(NSUTF8StringEncoding)! | |
for charNumber in charArr { | |
var num:NSNumber = NSNumber(char: charNumber) | |
summOfCharacterCodes += num.integerValue | |
} | |
return summOfCharacterCodes % tableSize | |
} | |
return 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment