S-99: Ninety-Nine Scala Problems
Do the S-99: Ninety-Nine Scala Problems
By convention, the first element in the list is element 0.
The List(n)
implementation:
def apply(n: Int): A = {
val rest = drop(n)
if (n < 0 || rest.isEmpty) throw new IndexOutOfBoundsException("" + n)
rest.head
}
The List.length()
implementation:
def length: Int = {
var these = self
var len = 0
while (!these.isEmpty) {
len += 1
these = these.tail
}
len
}
The List.reverse()
implementation, O(N)?:
override def reverse: List[A] = {
var result: List[A] = Nil
var these = this
while (!these.isEmpty) {
result = these.head :: result
these = these.tail
}
result
}
Think how flatMap implemented, map then flatten ?
use dropWhile
.
Notice the differences of List’s partition
and span
.
partition
will put all “true” elements in one list, and the others in the second list.
span
will put all elements in one list until an element is “false” (in terms of the predicate). For example:
scala> val list = List(1,1,2,1,3)
list: List[Int] = List(1, 1, 2, 1, 3)
scala> list.partition{_ == 1}
res0: (List[Int], List[Int]) = (List(1, 1, 1),List(2, 3))
scala> list.span{_ == 1}
res1: (List[Int], List[Int]) = (List(1, 1),List(2, 1, 3))
Use the result of problem P09 to implement the so-called run-length encoding(游程编码) data compression method.
Consecutive duplicates of elements are encoded as tuples (N, E) where N is the number of duplicates of the element E.
Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list.
Only elements with duplicates are transferred as (N, E) terms.
flatMap, List.fill
有区别吗?
zipWithIndex -> filter -> map
splitAt
slice
::
, :::
是prepend
range
利用java.util.Random和removeAt
使用P23的随机选择,复杂度 O(N^2)
Fisher–Yates shuffle算法,复杂度 O(N)
没有ClassTag,会报错 No ClassTag available for A。
sortWith
Use Euclid’s algorithm.
Euler’s so-called totient function phi(m) is defined as the number of positive integers r (1 <= r <= m) that are coprime to m.
Construct a flat list containing the prime factors in ascending order.