Question: (I need help programming this code. If you can do it in Scala, that would be great. If not, Python works too. Thank you.) INSTRUCTIONS
(I need help programming this code. If you can do it in Scala, that would be great. If not, Python works too. Thank you.)
INSTRUCTIONS
Write a tail recursive implementation of the function findAllOddIndices that given a list List
returns a list of integers consisting of indices List
corresponding to all the odd number elements
in the original list. Note that you must return a list in the increasing order of indices.
Restrictions
Must be tail recursive.
Must not use any list operations/API functions other than the following:
- Cons (::)
- length, head, tail, reverse.
Note: ??? indicates that there is a missing function or code fragment that needs to be filled in. In scala, it is also a macro that throws a NotImplemented exception. Make sure that you remove the ??? and replace it with the answer.
###CODE
import scala.annotation.tailrec @tailrec // YOUR CODE HERE ???
###TEST CASE
def testMsg(lst: List[Int], lst_expected: List[Int], testName: String):Unit = { val lst_ret = findAllOddIndices(lst) // Call the student's code if (lst_ret == lst_expected){ // compare result against expected println(s"Test $testName passed") // let the good times roll. } else { println(s"Test $testName failed") //oops..Houston, we have a problem. println(s"Input: ${lst}, Your code: ${lst_ret}, Expected: ${lst_expected}") assert(false, "Assertion failed") } }
val lst1 = List(0, 5, 2, 1, 3, 4, 7) val lst1_expected = List(1, 3, 4, 6) testMsg(lst1, lst1_expected, "#1")
val lst2: List[Int] = Nil val lst2_expected:List[Int] = Nil testMsg(lst2, lst2_expected, "#2")
val lst3: List[Int] = List(0, 2, 4, 6, 8, 10, 12, 14, 16) val lst3_expected: List[Int] = Nil testMsg(lst3, lst3_expected, "#3")
val lst4: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15) val lst4_expected: List[Int] = (0 until 8).toList testMsg(lst4, lst4_expected, "#4")
val lst5: List[Int] = List(0, 0, 0, 0, 0, -5) // Sorry :-) val lst5_expected:List[Int] = List(5) testMsg(lst5, lst5_expected, "#5")
passed(10)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
