scp1: finish task 1
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import scala.annotation.tailrec
|
||||
|
||||
@main def main(): Unit =
|
||||
// task 1 a)
|
||||
val values = new collection.mutable.ArrayBuffer[Int] // immutable pointer
|
||||
for (i <- 1 to 50)
|
||||
values.append(i)
|
||||
|
||||
println(values)
|
||||
println(iterative_sum(values.toArray))
|
||||
println(recursive_sum(values.toArray))
|
||||
println((0 to 10).map(fibonacci))
|
||||
|
||||
// task 1 b)
|
||||
def iterative_sum(numbers: Array[Int]): Int =
|
||||
var result = 0
|
||||
for (num <- numbers)
|
||||
result += num
|
||||
return result
|
||||
|
||||
// task 1 c)
|
||||
def recursive_sum(numbers: Array[Int]): Int =
|
||||
@tailrec def inner(numbers: Array[Int], accumulator: Int): Int =
|
||||
if numbers.length <= 0 then accumulator
|
||||
else inner(numbers.tail, numbers.head + accumulator)
|
||||
inner(numbers, 0)
|
||||
|
||||
// task 1 d)
|
||||
def fibonacci(n: Int): BigInt =
|
||||
if n <= 1 then BigInt(1)
|
||||
else fibonacci(n - 1) + fibonacci(n - 2)
|
||||
Reference in New Issue
Block a user