Skip to content

Instantly share code, notes, and snippets.

@sentenza
Created February 26, 2017 00:24
Show Gist options
  • Save sentenza/1402013015008f6ca436618f69140987 to your computer and use it in GitHub Desktop.
Save sentenza/1402013015008f6ca436618f69140987 to your computer and use it in GitHub Desktop.
A recursive way to increment a sequence of Integers - which are in fact Digits [0 ... 9].
/** Given a Sequence of Integers Seq(2, 3, 4) - which represents the number 234 base 10 - increments
* by one without converting types.
*
* @param s Seq[Int] The original sequence representation of the number
* @return The incremented by one Sequence
*/
def sequenceIncrement(s: Seq[Int]): Seq[Int] = {
sequenceIncrementRec(s.reverse, Seq.empty, carry = true).reverse
}
/** Recursively increment a sequence of integers
*
* @param seq Seq[Int] A sequence of integers (e.g. Seq(2,7,1) => 2 * 10^0 + 7 * 10^1 + 1 * 10^2)
* @param accumulator Seq[Int] The sequence to carry on during recursion
* @param carry Boolean true if balance carried forward
* @return The incremented by one sequence where the unit is the head element (e.g. Seq(3,7,1))
*/
def sequenceIncrementRec(seq: Seq[Int], accumulator: Seq[Int], carry: Boolean): Seq[Int] = seq match {
case Nil => if(carry) accumulator :+ 1 else accumulator
case head::tail =>
val current = head + (if(carry) 1 else 0)
val curried = current % 10
sequenceIncrementRec(tail, accumulator :+ curried, curried != current)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment