Search code examples
scalalistdata-structuresprimesfoldleft

How to return every nth even number in a list with foldLeft in Scala?


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


Solution

  • 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