Skip to content

Instantly share code, notes, and snippets.

@guersam
Last active February 16, 2019 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guersam/3448ecbe39c4a8aa2bf32d973b4b6fd1 to your computer and use it in GitHub Desktop.
Save guersam/3448ecbe39c4a8aa2bf32d973b4b6fd1 to your computer and use it in GitHub Desktop.
Better functional implementation of excel-style column name generation in Scala https://blog.jooq.org/2015/12/08/3-reasons-why-you-shouldnt-replace-your-for-loops-by-stream-foreach/
// Using new collection library in Scala 2.13
def nthColumnLabel(n: Int): String =
Iterator
.unfold(n) {
case 0 => None
case m =>
val m2 = m - 1
Some((m2 % 26 + 'A').toChar, m2 / 26)
}
.mkString
.reverse
// Using tail recursion
def nthColumnLabel2(n: Int): String = {
@annotation.tailrec
def iter(acc: List[Char], m: Int): String =
m - 1 match {
case -1 => acc.mkString
case m2 =>
iter((m2 % 26 + 'A').toChar :: acc, m2 / 26)
}
iter(Nil, n)
}
println(
(1 to 32)
.map(nthColumnLabel)
.mkString(", ")
)
// A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, AA, AB, AC, AD, AE, AF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment