Skip to content

Commit

Permalink
Merge pull request #50 from andreas-roehler/master
Browse files Browse the repository at this point in the history
solution1.6.2.3 added
  • Loading branch information
winitzki authored Jan 9, 2024
2 parents 86800d8 + 5f84f1e commit 4649f98
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
26 changes: 26 additions & 0 deletions chapter01/worksheets/solution1.6.2.3.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/** author: Andreas Röhler */

/**
Exercise 1.6.2.3
Given a function f: Int => Boolean, an integer n is called a “3- f ”
if there are only three different integers j ∈ [1, ..., n] such that f
( j) returns true. Define a function that takes f as an argument and
returns a sequence of all “3- f ” integers among n ∈ [1, ..., 1000].
What is the type of that function? Implement Exercise 1.6.2.2 using
that function.
*/

def is3Factor(n: Int): Boolean = {
val q = (2 to n-1)
val r = q.filter(y => (n != y) && (n % y == 0))
(r.length == 3)
}

def nestedIs3Factor(f: (Int => Boolean)): List[Int] = {
(1 to 1000).filter(x => f(x)).toList
}

val result = nestedIs3Factor(is3Factor)
val expected = Vector(16, 81, 625)

assert(result == expected)
22 changes: 22 additions & 0 deletions chapter01/worksheets/solution1.6.2.4.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/** author: Andreas Röhler */

/**
Exercise 1.6.2.4
Define a function see100 of type List[List[Int]] => List[List[Int]]
that selects only those inner lists whose largest value is at least
100.
Test with:
scala> see100( List( List(0, 1, 100), List(60, 80), List(1000) ) )
res0: List[List[Int]] = List(List(0, 1, 100), List(1000))
*/

def see100(a: List[List[Int]]): List[List[Int]] = {
a.filter(99 < _.max)
}

val result = see100( List( List(0, 1, 100), List(60, 80), List(1000) ) )

val expected:List[List[Int]] = List(List(0, 1, 100), List(1000))

assert(result == expected)
24 changes: 24 additions & 0 deletions chapter01/worksheets/solution1.6.2.5.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/** author: Andreas Röhler */

/**
Exercise 1.6.2.5
Define a function of type List[Double] => List[Double] that “normalizes” the list:
it finds the element having the largest absolute value and, if that
value is nonzero, divides all elements by that value and returns a new
list; otherwise returns the original list.
Test with: scala> normalize(List(1.0, -4.0, 2.0))
res0: List[Double] = List(0.25, -1.0, 0.5)
*/

def normalize(a: List[Double]): List[Double] = {

val b = a.map(k => k.abs).max
if (b == 0) a else a.map(_ / b)
}

val result = normalize(List(1.0, -4.0, 2.0))
val expected: List[Double] = List(0.25, -1.0, 0.5)

assert(result == expected)

0 comments on commit 4649f98

Please sign in to comment.