Reputation: 397
For a university project I have to implement a function called takeNthEven which finds the nth even number in a list with the aid of foldLeft. For example:
takeNthEven(SinglyLinkedIntList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,18,5,3), 3)
should return: SinglyLinkedIntList(4, 10,18)
My attempt so far:
def takeNthEven(input: IntList, n: Int): IntList = {
var temp = SinglyLinkedIntList()
input.foldLeft(0 -> 0) {
case(acc,n) => if (acc == 2 || !(2 to (acc-1)).exists(x => i % x == 0)) temp.append(acc)
}._n
}
But unfortunately this does not even compile. I am not sure how to continue with this algorithm, could someone help me figure this out? I am new to functional programming and dont know how to go about this
Upvotes: 1
Views: 208
Reputation: 8711
Another foldLeft
val n = 3
val p = List(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,18,5,3)
p.foldLeft( (List.empty[Int],1) ) {
case((x,y),z) => {
val t = if(y%n==0 && z%2==0 ) z::x else x
(t,if(z%2==0) y+1 else y)
}
}._1.reverse
// List[Int] = List(4, 10, 18)
Upvotes: 0
Reputation: 51271
Here's my take on it. You'll probably have to make adjustments depending on how your IntList
is composed.
type IntList = List[Int]
def takeNthEven(input: IntList, n: Int): IntList = input.foldLeft(List.empty[Int]->1){
case ((acc,cnt),elem) if elem%2 < 1 => if (cnt%n < 1) (elem::acc, cnt+1)
else (acc, cnt+1)
case (skip,_) => skip
}._1.reverse
Upvotes: 1
Reputation: 22850
Something like this should work:
val (_, result) = input.foldLeft(0 -> List.empty[Int]) {
case ((count, acc), elem) =>
if ((elem % 2) == 0) {
val newCount = count + 1
if (newCount == n) {
0 -> (elem :: acc)
} else {
newCount -> acc
}
} else {
count -> acc
}
}
result.reverse
Upvotes: 2