feat: add Swift codes for hash_collision article (#569)

* feat: add Swift codes for hash_collision article

* refactor: extract common Pair

* Update hash_map.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
pull/576/head
nuomi1 1 year ago committed by GitHub
parent 69920a0599
commit 7f8b0fff54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -27,6 +27,8 @@ let package = Package(
// chapter_hashing
.executable(name: "hash_map", targets: ["hash_map"]),
.executable(name: "array_hash_map", targets: ["array_hash_map"]),
.executable(name: "hash_map_chaining", targets: ["hash_map_chaining"]),
.executable(name: "hash_map_open_addressing", targets: ["hash_map_open_addressing"]),
// chapter_tree
.executable(name: "binary_tree", targets: ["binary_tree"]),
.executable(name: "binary_tree_bfs", targets: ["binary_tree_bfs"]),
@ -90,7 +92,9 @@ let package = Package(
.executableTarget(name: "array_deque", path: "chapter_stack_and_queue", sources: ["array_deque.swift"]),
// chapter_hashing
.executableTarget(name: "hash_map", dependencies: ["utils"], path: "chapter_hashing", sources: ["hash_map.swift"]),
.executableTarget(name: "array_hash_map", path: "chapter_hashing", sources: ["array_hash_map.swift"]),
.executableTarget(name: "array_hash_map", dependencies: ["utils"], path: "chapter_hashing", sources: ["array_hash_map.swift"]),
.executableTarget(name: "hash_map_chaining", dependencies: ["utils"], path: "chapter_hashing", sources: ["hash_map_chaining.swift"]),
.executableTarget(name: "hash_map_open_addressing", dependencies: ["utils"], path: "chapter_hashing", sources: ["hash_map_open_addressing.swift"]),
// chapter_tree
.executableTarget(name: "binary_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree.swift"]),
.executableTarget(name: "binary_tree_bfs", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree_bfs.swift"]),

@ -4,16 +4,7 @@
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
class Pair {
var key: Int
var val: String
init(key: Int, val: String) {
self.key = key
self.val = val
}
}
import utils
/* */
class ArrayHashMap {

@ -0,0 +1,137 @@
/**
* File: hash_map_chaining.swift
* Created Time: 2023-06-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
class HashMapChaining {
var size: Int //
var capacity: Int //
var loadThres: Double //
var extendRatio: Int //
var buckets: [[Pair]] //
/* */
init() {
size = 0
capacity = 4
loadThres = 2 / 3
extendRatio = 2
buckets = Array(repeating: [], count: capacity)
}
/* */
func hashFunc(key: Int) -> Int {
key % capacity
}
/* */
func loadFactor() -> Double {
Double(size / capacity)
}
/* */
func get(key: Int) -> String? {
let index = hashFunc(key: key)
let bucket = buckets[index]
// key val
for pair in bucket {
if pair.key == key {
return pair.val
}
}
// key nil
return nil
}
/* */
func put(key: Int, val: String) {
//
if loadFactor() > loadThres {
extend()
}
let index = hashFunc(key: key)
let bucket = buckets[index]
// key val
for pair in bucket {
if pair.key == key {
pair.val = val
return
}
}
// key
let pair = Pair(key: key, val: val)
buckets[index].append(pair)
size += 1
}
/* */
func remove(key: Int) {
let index = hashFunc(key: key)
let bucket = buckets[index]
//
for (pairIndex, pair) in bucket.enumerated() {
if pair.key == key {
buckets[index].remove(at: pairIndex)
}
}
size -= 1
}
/* */
func extend() {
//
let bucketsTmp = buckets
//
capacity *= extendRatio
buckets = Array(repeating: [], count: capacity)
size = 0
//
for bucket in bucketsTmp {
for pair in bucket {
put(key: pair.key, val: pair.val)
}
}
}
/* */
func print() {
for bucket in buckets {
let res = bucket.map { "\($0.key) -> \($0.val)" }
Swift.print(res)
}
}
}
@main
enum _HashMapChaining {
/* Driver Code */
static func main() {
/* */
let map = HashMapChaining()
/* */
// (key, value)
map.put(key: 12836, val: "小哈")
map.put(key: 15937, val: "小啰")
map.put(key: 16750, val: "小算")
map.put(key: 13276, val: "小法")
map.put(key: 10583, val: "小鸭")
print("\n添加完成后,哈希表为\nKey -> Value")
map.print()
/* */
// key value
let name = map.get(key: 13276)
print("\n输入学号 13276 ,查询到姓名 \(name!)")
/* */
// (key, value)
map.remove(key: 12836)
print("\n删除 12836 后,哈希表为\nKey -> Value")
map.print()
}
}

@ -0,0 +1,158 @@
/**
* File: hash_map_open_addressing.swift
* Created Time: 2023-06-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
class HashMapOpenAddressing {
var size: Int //
var capacity: Int //
var loadThres: Double //
var extendRatio: Int //
var buckets: [Pair?] //
var removed: Pair //
/* */
init() {
size = 0
capacity = 4
loadThres = 2 / 3
extendRatio = 2
buckets = Array(repeating: nil, count: capacity)
removed = Pair(key: -1, val: "-1")
}
/* */
func hashFunc(key: Int) -> Int {
key % capacity
}
/* */
func loadFactor() -> Double {
Double(size / capacity)
}
/* */
func get(key: Int) -> String? {
let index = hashFunc(key: key)
// 线 index
for i in stride(from: 0, to: capacity, by: 1) {
//
let j = (index + i) % capacity
// key nil
if buckets[j] == nil {
return nil
}
// key val
if buckets[j]?.key == key, buckets[j] != removed {
return buckets[j]?.val
}
}
return nil
}
/* */
func put(key: Int, val: String) {
//
if loadFactor() > loadThres {
extend()
}
let index = hashFunc(key: key)
// 线 index
for i in stride(from: 0, through: capacity, by: 1) {
//
let j = (index + i) % capacity
//
if buckets[j] == nil || buckets[j] == removed {
buckets[j] = Pair(key: key, val: val)
size += 1
return
}
// key val
if buckets[j]?.key == key {
buckets[j]?.val = val
return
}
}
}
/* */
func remove(key: Int) {
let index = hashFunc(key: key)
// 线 index
for i in stride(from: 0, to: capacity, by: 1) {
//
let j = (index + i) % capacity
// key
if buckets[j] == nil {
return
}
// key
if buckets[j]?.key == key {
buckets[j] = removed
size -= 1
return
}
}
}
/* */
func extend() {
//
let bucketsTmp = buckets
//
capacity *= extendRatio
buckets = Array(repeating: nil, count: capacity)
size = 0
//
for pair in bucketsTmp {
if let pair, pair != removed {
put(key: pair.key, val: pair.val)
}
}
}
/* */
func print() {
for pair in buckets {
if let pair {
Swift.print("\(pair.key) -> \(pair.val)")
} else {
Swift.print("null")
}
}
}
}
@main
enum _HashMapOpenAddressing {
/* Driver Code */
static func main() {
/* */
let map = HashMapOpenAddressing()
/* */
// (key, value)
map.put(key: 12836, val: "小哈")
map.put(key: 15937, val: "小啰")
map.put(key: 16750, val: "小算")
map.put(key: 13276, val: "小法")
map.put(key: 10583, val: "小鸭")
print("\n添加完成后,哈希表为\nKey -> Value")
map.print()
/* */
// key value
let name = map.get(key: 13276)
print("\n输入学号 13276 ,查询到姓名 \(name!)")
/* */
// (key, value)
map.remove(key: 16750)
print("\n删除 16750 后,哈希表为\nKey -> Value")
map.print()
}
}

@ -0,0 +1,20 @@
/**
* File: Pair.swift
* Created Time: 2023-06-28
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
public class Pair: Equatable {
public var key: Int
public var val: String
public init(key: Int, val: String) {
self.key = key
self.val = val
}
public static func == (lhs: Pair, rhs: Pair) -> Bool {
lhs.key == rhs.key && lhs.val == rhs.val
}
}

@ -515,7 +515,20 @@ index = hash(key) % capacity
=== "Swift"
```swift title="array_hash_map.swift"
[class]{Pair}-[func]{}
/* 键值对 */
public class Pair: Equatable {
public var key: Int
public var val: String
public init(key: Int, val: String) {
self.key = key
self.val = val
}
public static func == (lhs: Pair, rhs: Pair) -> Bool {
lhs.key == rhs.key && lhs.val == rhs.val
}
}
[class]{ArrayHashMap}-[func]{}
```

Loading…
Cancel
Save