Skip to content

Commit

Permalink
feat(strings): spreadsheet encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Dec 17, 2024
1 parent 1eea7bf commit ecefc7e
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion buildSrc/src/main/kotlin/Versions.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
object Versions {
const val PROJECT = "2.1.1"
const val KOTLIN = "2.0.21"
const val KOTLIN = "2.1.0"
const val GRADLE = "6.8.3"

const val DETEKT = "1.9.1"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Spreadsheet Encoding

We will be considering how to solve the problem of implementing a function that converts a spreadsheet column ID
(i.e., “A”, “B”, “C”, …, “Z”, “AA”, etc.) to the corresponding integer. For example, “A” equals 1 because it represents
the first column, while “AA” equals 27 because it represents the 27th column.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.kotlinground.strings.spreadsheetencode
import kotlin.math.pow

/**
* This encodes a Spreadsheet column ID as an integer and returns it.
* Here the encoding uses the alphabets A, B, C, etc. and
* further uses the indexing of the alphabet starting from 1 like: A=1, B=2, C=3,..., Z=26
* Complexity
* Where n represents the number of characters in the column_id
*
* - Time O(n) as we iterate over each character in the column ID to calculate the encoding
* - Space O(1) no extra space is required to perform the encoding
* @param columnID [String] column ID to encode, e.g. A or ZZ
* @return [Int] the encoded column ID
*/
fun spreadsheetEncodeColumn(columnID: String): Int {
var num = 0
var count = columnID.length - 1

for (char in columnID) {
val diff = char.code - 'A'.code + 1
val base = 26.0.pow(count).toInt()
num += base * diff
count--
}

return num
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.kotlinground.strings.spreadsheetencode

import kotlin.test.Test
import kotlin.test.assertEquals

class SpreadsheetEncodeTest {

@Test
fun `should return 702 for a column ID of ZZ`() {
val columnID = "ZZ"
val expected = 702
val actual = spreadsheetEncodeColumn(columnID)
assertEquals(expected, actual)
}
}

0 comments on commit ecefc7e

Please sign in to comment.