Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
add P02_Impl PenultimatElement
  • Loading branch information
rajeshsantha committed Nov 10, 2020
commit c93d7495f26071f41f19681b0849d4b9dd697bed
32 changes: 32 additions & 0 deletions src/com/concept/scala/NinetyNineProblems/P02_Impl.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.concept.scala.NinetyNineProblems

import scala.annotation.tailrec

/**
*
*
* @see P02
* @example penultimate(List(1, 1, 2, 3, 5, 8))
* res0: Int = 5
* @groupname Problem - 3
*
*/

class P02_Impl extends PenultimatElement {
override def penultimatElement_builtin[T](list: List[T]): T = if (list.nonEmpty) list.init.last else throw new NoSuchElementException

@tailrec
final override def penultimatElement_recursive[T](list: List[T]): T =
list match {
case penultimatElement :: lastElement :: Nil => penultimatElement
case head :: tail => penultimatElement_recursive(tail)
case _ => throw new NoSuchElementException
}

}

trait PenultimatElement {
def penultimatElement_builtin[T](list: List[T]): T

def penultimatElement_recursive[T](list: List[T]): T
}