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,9 @@
def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
case _ if high < low => None
case mid if a(mid) > v => recurse(low, mid - 1)
case mid if a(mid) < v => recurse(mid + 1, high)
case mid => Some(mid)
}
recurse(0, a.size - 1)
}

View file

@ -0,0 +1,12 @@
def binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = {
var low: Int = 0
var high: Int = xs.size - 1
while (low <= high)
low + high >>> 1 match {
case guess if ordering.gt(xs(guess), x) => high = guess - 1 //too high
case guess if ordering.lt(xs(guess), x) => low = guess + 1 // too low
case guess => return Some(guess) //found it
}
None //not found
}

View file

@ -0,0 +1,10 @@
def testBinarySearch(n: Int) = {
val odds = 1 to n by 2
val result = (0 to n).flatMap(binarySearch(odds, _))
assert(result == (0 until odds.size))
println(s"$odds are odd natural numbers")
for (it <- result)
println(s"$it is ordinal of ${odds(it)}")
}
def main() = testBinarySearch(12)