Last active
August 14, 2023 13:44
-
-
Save Soben/8053bb0f03fd9a00b91b96de53fef0b8 to your computer and use it in GitHub Desktop.
Cassidoo | Sheet Column lookup to get true column number from letter structure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Solving Cassidoo's coding problem from the newsletter sent February 6th. | |
Co-Pilot assisted *sigh* | |
I was on track to solve the problem, but co-pilot immediately spurted out the `pow` | |
function before I had a chance to figure out the math. I'm not sure if I'm happy or | |
annoyed. Co-Pilot is also helping me type this message out :| | |
*/ | |
function getColumnNames() { | |
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
} | |
function getLetterCount($letter) { | |
return (strpos(getColumnNames(), strtoupper($letter)) + 1); | |
} | |
function getBase($column) { | |
return pow(strlen(getColumnNames()), $column - 1); | |
} | |
function getColumnNumber($column) { | |
$columnLength = strlen($column); | |
$columnNumber = 0; | |
for ($i = 0; $i < $columnLength; $i++) { | |
$columnNumber += getLetterCount($column[$i]) * getBase($columnLength - $i); | |
} | |
return $columnNumber; | |
} | |
echo getColumnNumber("A") . PHP_EOL; // 1 | |
echo getColumnNumber("AA") . PHP_EOL; // 27 | |
echo getColumnNumber("AAZ") . PHP_EOL; // 728 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment