Files
hello-algo/ja/codes/swift/chapter_hashing/array_hash_map.swift
Yudong Jin d7b2277d2b Re-translate the Japanese version (#1871)
* Retranslate Japanese docs with GPT-5.4

* Retranslate Japanese code with GPT-5.4
2026-03-30 07:30:15 +08:00

111 lines
3.0 KiB
Swift

/**
* File: array_hash_map.swift
* Created Time: 2023-01-16
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
class ArrayHashMap {
private var buckets: [Pair?]
init() {
// 100
buckets = Array(repeating: nil, count: 100)
}
/* */
private func hashFunc(key: Int) -> Int {
let index = key % 100
return index
}
/* */
func get(key: Int) -> String? {
let index = hashFunc(key: key)
let pair = buckets[index]
return pair?.val
}
/* */
func put(key: Int, val: String) {
let pair = Pair(key: key, val: val)
let index = hashFunc(key: key)
buckets[index] = pair
}
/* */
func remove(key: Int) {
let index = hashFunc(key: key)
// nil
buckets[index] = nil
}
/* */
func pairSet() -> [Pair] {
buckets.compactMap { $0 }
}
/* */
func keySet() -> [Int] {
buckets.compactMap { $0?.key }
}
/* */
func valueSet() -> [String] {
buckets.compactMap { $0?.val }
}
/* */
func print() {
for pair in pairSet() {
Swift.print("\(pair.key) -> \(pair.val)")
}
}
}
@main
enum _ArrayHashMap {
/* Driver Code */
static func main() {
/* */
let map = ArrayHashMap()
/* */
// (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: 15937)!
print("\n学籍番号 15937 を入力すると、名前 \(name) が見つかりました")
/* */
// (key, value)
map.remove(key: 10583)
print("\n10583 を削除後のハッシュテーブルは\nKey -> Value")
map.print()
/* */
print("\nキーと値の組 Key->Value を走査")
for pair in map.pairSet() {
print("\(pair.key) -> \(pair.val)")
}
print("\nキー Key を個別に走査")
for key in map.keySet() {
print(key)
}
print("\n値 Value を個別に走査")
for val in map.valueSet() {
print(val)
}
}
}