Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,10 @@
func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
var recurse: ((Int, Int) -> Int?)!
recurse = {(low, high) in switch (low + high) / 2 {
case _ where high < low: return nil
case let mid where xs[mid] > x: return recurse(low, mid - 1)
case let mid where xs[mid] < x: return recurse(mid + 1, high)
case let mid: return mid
}}
return recurse(0, xs.count - 1)
}

View file

@ -0,0 +1,11 @@
func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
var (low, high) = (0, xs.count - 1)
while low <= high {
switch (low + high) / 2 {
case let mid where xs[mid] > x: high = mid - 1
case let mid where xs[mid] < x: low = mid + 1
case let mid: return mid
}
}
return nil
}

View file

@ -0,0 +1,15 @@
func testBinarySearch(n: Int) {
let odds = Array(stride(from: 1, through: n, by: 2))
let result = flatMap(0...n) {binarySearch(odds, $0)}
assert(result == Array(0..<odds.count))
println("\(odds) are odd natural numbers")
for it in result {
println("\(it) is ordinal of \(odds[it])")
}
}
testBinarySearch(12)
func flatMap<T, U>(source: [T], transform: (T) -> U?) -> [U] {
return source.reduce([]) {(var xs, x) in if let x = transform(x) {xs.append(x)}; return xs}
}