Q:

Write a Scala program to find an element from the last position of a given list

0

Write a Scala program to find an element from the last position of a given list

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

object Scala_List {
  def last_Nth_num[A](nums: List[A], n: Int ): A = {
    if (n <= 0) throw new IllegalArgumentException("Nth position is less than 1!")
    if (n > nums.length) throw new NoSuchElementException("Nth position greater than list length!")
    nums.takeRight(n).head
   } 
     
   def main(args: Array[String]): Unit = {
         val nums = List(1, 2, 3, 4, 5, 7, 9, 11, 14, 12, 16)
         println("Result: " + last_Nth_num(nums, 3));
         println("Result: " + last_Nth_num(nums, 6));
         println("Result: " + last_Nth_num(nums, 0));
         }
}

Sample Output:

Result: 14
Result: 7

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now