forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContents.swift
68 lines (58 loc) · 1.34 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
func countOccurrencesOfKey(_ key: Int, inArray a: [Int]) -> Int {
func leftBoundary() -> Int {
var low = 0
var high = a.count
while low < high {
let midIndex = low + (high - low)/2
if a[midIndex] < key {
low = midIndex + 1
} else {
high = midIndex
}
}
return low
}
func rightBoundary() -> Int {
var low = 0
var high = a.count
while low < high {
let midIndex = low + (high - low)/2
if a[midIndex] > key {
high = midIndex
} else {
low = midIndex + 1
}
}
return low
}
return rightBoundary() - leftBoundary()
}
// Simple test
let a = [ 0, 1, 1, 3, 3, 3, 3, 6, 8, 10, 11, 11 ]
countOccurrencesOfKey(3, inArray: a)
// Test with arrays of random size and contents (see debug output)
import Foundation
func createArray() -> [Int] {
var a = [Int]()
for i in 0...5 {
if i != 2 { // don't include the number 2
let count = Int(arc4random_uniform(UInt32(6))) + 1
for _ in 0..<count {
a.append(i)
}
}
}
return a.sorted()
}
for _ in 0..<10 {
let a = createArray()
print(a)
// Note: we also test -1 and 6 to check the edge cases.
for k in -1...6 {
print("\t\(k): \(countOccurrencesOfKey(k, inArray: a))")
}
}