Clearly, if you need to count up, count up. If you need to count down, count down. However, other things being equal, is one faster than the other? Here is my Scala code for a well-known puzzle - checking if a number is divisible by 13. In the first example, I reverse my array and count upwards in the subsequent for-loop. In the second example I leave the array alone and do a decrementing for-loop. On the surface, the second example looks faster. Unfortunately, on the site where I run the code, it always times out.
// works every time
object Thirteen {
import scala.annotation.tailrec
@tailrec
def thirt(n: Long): Long = {
val getNum = (n: Int) => Array(1, 10, 9, 12, 3, 4)(n % 6)
val ni = n.toString.split("").reverse.map(_.toInt)
var s: Long = 0
for (i <- 0 to ni.length-1) {
s += ni(i) * getNum(i)
}
if (s == n) s else thirt(s)
}
}
// times out every time
object Thirteen {
import scala.annotation.tailrec
@tailrec
def thirt(n: Long): Long = {
val getNum = (n: Int) => Array(1, 10, 9, 12, 3, 4)(n % 6)
val ni = n.toString.split("").map(_.toInt)
var s: Long = 0
for (i <- ni.length-1 to 0 by -1) {
s = s + ni(i) * getNum(i)
}
if (s == n) s else thirt(s)
}
}
I ask the following questions:
- Is there an obvious rule I am unaware of?
- What is an easy way to test two code versions for performance – reliably measuring performance in the JVM appears difficult.
- Does it help to look at the underlying byte code?
- Is there a better piece of code solving the same problem, If so, I'd be very grateful to see it.
Whilst I've seen similar questions, I can't find a definitive answer.
val s :Long = ni.indices.foldLeft(0L){case (acc,x) => acc + ni(x)*getNum(x)}
130
, I seei
bouncing forever at 0 and 1. With another println, it is recursing on13
and31
. So it's the algorithm, not the control structure or the Range.