Skip to content

Instantly share code, notes, and snippets.

@ChristopherDavenport
Created May 8, 2021 05:47
Show Gist options
  • Select an option

  • Save ChristopherDavenport/119b51f6e2bd59b3907c33664b84e1e6 to your computer and use it in GitHub Desktop.

Select an option

Save ChristopherDavenport/119b51f6e2bd59b3907c33664b84e1e6 to your computer and use it in GitHub Desktop.
Add Ith Value, either early or late
object AddI {
def addIEarly(x: Int, i: Int): Int = {
require(x >= 0, "addIEarly: x must be positive")
require(i >= 0, "addIEarly: i must be positive")
val reset = i - 1
@scala.annotation.tailrec def go(x: Int, pos: Int, acc: Int): Int = {
println(s"go: x-$x acc-$acc, pos:$pos")
(x, pos) match {
case (0, _) => acc
case (other, 0) => go(other-1, reset, acc + other)
case (other, pos) => go(other-1, pos -1 , acc)
}
}
go(x, 0, 0)
}
addIEarly(3, 1) // Every 1 Should always equal Sum
addIEarly(4, 2) // Add 4 + 2
addIEarly(10, 5) // 10 + 5
addIEarly(10, 2)
println()
def addILate(x: Int, i: Int): Int = {
require(x >= 0, "addILate: x must be positive")
require(i >= 0, "addILate: i must be positive")
@scala.annotation.tailrec def go(x: Int, acc: Int, pos: Int): Int = {
println(s"go: x-$x acc-$acc, pos:$pos")
x match {
case 0 => acc
case other if (pos == i) => go(other-1, acc + other, 1)
case other => go(other-1, acc, pos + 1)
}
}
go(x, 0, 1)
}
addILate(3, 1) // Every 1 Should always equal Sum
addILate(4, 2) // Add 3 + 1
addILate(10, 5) // 6 + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment