はじめに
仕事で Google SpreadSheet の操作を行う必要が出てきたため、こちらのエントリを参考に A1 notation の変換処理を実装してみた。
[A1表記と26進数]
(https://qiita.com/ttk1/items/83ed469cf62aebcc67ba)
実装
A1Notation.scala
object A1Notation {
def toA1Notation(num: Int): String = {
@scala.annotation.tailrec
def tailrec(num: Int, z: String): String = {
val str = ((num - 1) % 26 + 'A').toChar.toString + z
if (num <= 26) str
else tailrec((num - 1) / 26, str)
}
if (num > 0) tailrec(num, "")
else throw new IllegalArgumentException("The argument is not within the range of A1 notation.")
}
def toA1Number(a1notation: String): Int = {
if (a1notation.matches("[A-Z]+"))
a1notation.toCharArray.reverse.zipWithIndex.foldLeft(0) {
case (z, (char, index)) =>
z + (((char - 'A') + 1) * Math.pow(26D, index).toInt)
}
else throw new IllegalArgumentException("The argument is not A1 notation.")
}
}
見ての通り、冒頭で述べた列に対する変換の操作のみ。
おわりに
上記を使った Google Spreadsheet に関する記事も書いてみるか...。