Reputation: 11
Hi everyone I have been working on this problem which is to find the n-th happy number. But I am struggling to make it work here as it is showing
Found: Unit
Required: Int
Maybe you are missing an else part for the conditional?
Here is how it works:
nThHappy(1) returns 1
• nThHappy(3) returns 10
• nThHappy(11) returns 49
• nThHappy(19) returns 97
def nThHappy(k: Int): Int = {
def isHappy(n: Int): Boolean = {
def sumOfDigitsSquared(n: Int): Int = n.toString.foldLeft(0) { (product, num) => product + num.asDigit * num.asDigit }
def loop(seen: Set[Int], x: Int): Boolean = {
x match {
case 1 => true
case _ if seen.contains(x) => false
case _ => loop(seen + x, sumOfDigitsSquared(x))
}
}
loop(Set(),n)
}
def helper(countN: Int,countK: Int, hNum:Int): Int =
countK match {
case hNum => countN
case _ => {
if (isHappy(countN) == false) {
helper(countN+1, countK, hNum)
}
else if(isHappy(countN) == true) { // <-- Here is the problem
helper(countN+1, countK+1, hNum)
}
}
}
helper(0,0,k)
}
Upvotes: 0
Views: 114
Reputation: 27421
You need an else
part for that last if
, or just remove the test (which is pointless), or just use match
:
case _ if isHappy(countN) =>
helper(countN+1, countK+1, hNum)
case _ =>
helper(countN+1, countK, hNum)
Upvotes: 1