1
1
package com .baeldung .scala
2
2
3
+ /**
4
+ * Some utility methods.
5
+ *
6
+ * @author Chandra Prakash
7
+ *
8
+ */
3
9
object Utils {
4
- def average (x : Double , y : Double ) = (x + y) / 2
5
-
6
- def gcd (x : Int , y : Int ): Int = {
7
- if (y == 0 ) x else gcd(y, x % y)
8
- }
9
-
10
- def gcdIter (x : Int , y : Int ): Int = {
11
- var a = x
12
- var b = y
13
- while (b > 0 ) {
14
- a = a % b
15
- val t = a
16
- a = b
17
- b = t
18
- }
19
- return a
20
- }
21
-
22
- def rangeSum (a : Int , b : Int ) = {
23
- var sum = 0 ;
24
- for (i <- a to b) {
25
- sum += i
26
- }
27
- sum
28
- }
29
-
30
- def factorial (a : Int ): Int = {
31
- var result = 1 ;
32
- var i = a;
33
- do {
34
- result *= i
35
- i = i - 1
36
- } while (i > 0 )
37
- result
38
- }
39
-
40
- def randomLessThan (d : Double ) = {
41
- var random = 0d
42
- do {
43
- random = Math .random()
44
- } while (random >= d)
45
- random
46
- }
47
-
48
- def whileLoop (condition : => Boolean )(body : => Unit ): Unit =
49
- if (condition) {
50
- body
51
- whileLoop(condition)(body)
52
- }
53
-
54
- def power (x : Int , y : Int ): Int = {
55
- def powNested (i : Int , accumulator : Int ): Int = {
56
- if (i <= 0 ) accumulator
57
- else powNested(i - 1 , x * accumulator)
58
- }
59
- powNested(y, 1 )
60
- }
61
-
62
- def fibonacci (n : Int ): Int = n match {
63
- case 0 | 1 => 1
64
- case x if x > 1 => fibonacci(x - 1 ) + fibonacci(x - 2 )
10
+ def average (x : Double , y : Double ) = (x + y) / 2
11
+
12
+ def randomLessThan (d : Double ) = {
13
+ var random = 0d
14
+ do {
15
+ random = Math .random()
16
+ } while (random >= d)
17
+ random
18
+ }
19
+
20
+ def power (x : Int , y : Int ) : Int = {
21
+ def powNested (i : Int , accumulator : Int ) : Int = {
22
+ if (i <= 0 ) accumulator
23
+ else powNested(i - 1 , x * accumulator)
65
24
}
25
+ powNested(y, 1 )
26
+ }
27
+
28
+ def fibonacci (n : Int ) : Int = n match {
29
+ case 0 | 1 => 1
30
+ case x if x > 1 =>
31
+ fibonacci(x - 1 ) + fibonacci(x - 2 )
32
+ }
66
33
}
0 commit comments