Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bdd2de6

Browse files
committed
Added Scala Codebox
1 parent 039eb4c commit bdd2de6

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

‎HackerRank/ProjectEuler/Utils.scala

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
object Utils {
2+
3+
val in = {
4+
val lines = scala.io.Source.stdin.getLines
5+
lines flatMap (_ split ' ' filter (_.nonEmpty))
6+
}
7+
8+
def nextInt = in.next.toInt
9+
10+
val fibs: Stream[Long] = 1L #:: fibs.scanLeft(2L)(_ + _)
11+
12+
val primes: Stream[Int] = 2 #:: (Stream.from(3, 2) filter (n => primes.view takeWhile (p => p*p <= n) forall (n % _ != 0)))
13+
14+
@annotation.tailrec
15+
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
16+
17+
def lcm(a: Int, b: Int): Int = a / gcd(a, b) * b
18+
19+
@annotation.tailrec
20+
def binarySearch[T, U](key: U, xs: IndexedSeq[T], from: Int, end: Int, keyExtract: (T) => U = (x:T) => x)(implicit ordering: Ordering[U]): Option[Int] = {
21+
if (from >= end) None
22+
else {
23+
val mid = (from + end) / 2
24+
val t = keyExtract(xs(mid))
25+
val cmp = ordering.compare(key, t)
26+
if (cmp < 0) binarySearch(key, xs, from, mid, keyExtract)
27+
else if (cmp > 0) binarySearch(key, xs, mid + 1, end, keyExtract)
28+
else Some(mid)
29+
}
30+
}
31+
32+
def lowerBound[T, U](key: U, iseq: IndexedSeq[T], from: Int, end: Int, keyExtract: (T) => U = (x:T) => x)(implicit ordering: Ordering[U]): Int = {
33+
var lo = from
34+
var hi = end - 1
35+
while (lo <= hi) {
36+
val mid = (lo + hi) / 2
37+
if (ordering.lteq(key, keyExtract(iseq(mid))))
38+
hi = mid - 1
39+
else
40+
lo = mid + 1
41+
}
42+
hi + 1
43+
}
44+
45+
def upperBound[T, U](key: U, iseq: IndexedSeq[T], from: Int, end: Int, keyExtract: (T) => U = (x:T) => x)(implicit ordering: Ordering[U]): Int = {
46+
var lo = from
47+
var hi = end - 1
48+
while (lo <= hi) {
49+
val mid = (lo + hi) / 2
50+
if (ordering.lt(key, keyExtract(iseq(mid))))
51+
hi = mid - 1
52+
else
53+
lo = mid + 1
54+
}
55+
hi + 1
56+
}
57+
58+
}
59+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /