Skip to content

Commit 93f4ab4

Browse files
committed
sample code for list average tutorial
1 parent 37c438b commit 93f4ab4

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
## Relevant Articles
22
- [Using filter() and takeWhile() With Collections in Scala](https://www.baeldung.com/scala/filter-takewhile)
33
- [Finding Elements in a List using takeWhile() and dropWhile() in Scala](https://www.baeldung.com/scala/list-find-takewhile-dropwhile)
4+
- [Calculate the Average of a List in Scala](https://www.baeldung.com/scala/calculate-the-average-of-a-list-in-scala)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.scala.listaverage
2+
3+
object ListAverage {
4+
5+
6+
def naive(lst: List[Int]): Int = {
7+
var total = 0
8+
var nrElements = 0
9+
10+
for(elem <- lst) {
11+
total += elem
12+
nrElements += 1
13+
}
14+
15+
total / nrElements
16+
}
17+
18+
19+
def averageDouble(lst: List[Int]): Double = {
20+
var total = 0
21+
22+
// here we use double to ensure we dont round final number
23+
var nrElements = 0.0
24+
25+
for (elem <- lst) {
26+
total += elem
27+
nrElements += 1
28+
}
29+
30+
total / nrElements
31+
}
32+
33+
def averageWithListMethods(lst: List[Int]): Int = {
34+
lst.sum / lst.size
35+
}
36+
37+
def averageWithListMethodsDouble(lst: List[Int]): Double = {
38+
lst.sum / lst.size.toDouble
39+
}
40+
41+
def averageWithFold(lst: List[Int]): Double = {
42+
val (sum, size) = lst.foldLeft((0.0, 0))((pair, elem)=>(pair._1 + elem, pair._2 + 1))
43+
sum / size
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.scala.listaverage
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
6+
class ListAverageUnitTest extends AnyFlatSpec with Matchers {
7+
val lst = List(1,2,3,4,5)
8+
9+
"naive" should "return rounded average 2" in {
10+
ListAverage.naive(lst) shouldBe 2
11+
}
12+
13+
"naive with double" should "return average 2.5" in {
14+
ListAverage.averageDouble(lst) shouldBe 2.5
15+
}
16+
17+
"averageWithListMethods" should "return rounded average 2" in {
18+
ListAverage.averageWithListMethods(lst) shouldBe 2
19+
}
20+
21+
"averageWithListMethodsDouble" should "return average 2.5" in {
22+
ListAverage.averageWithListMethodsDouble(lst) shouldBe 2.5
23+
}
24+
25+
"averageWithFold" should "return average 2.5" in {
26+
ListAverage.averageWithFold(lst) shouldBe 2.5
27+
}
28+
29+
}

0 commit comments

Comments
 (0)