Created
November 3, 2011 05:58
-
-
Save laiso/1335869 to your computer and use it in GitHub Desktop.
http://d.hatena.ne.jp/JunichiIto/20111102/1320253815 の"問題1: Excel列名変換問題"
This file contains hidden or 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
| #!/usr/bin/env php | |
| <?php | |
| function main($str=null){ | |
| if(!ctype_alpha($str)){ | |
| return; | |
| } | |
| $chars = str_split($str); | |
| $chars = array_reverse($chars); | |
| $range = range(0, count($chars)-1); | |
| $numbers = array_map(function($s, $i){ | |
| $code = ord($s)-64; | |
| if($code > 0 || $code < 27){ | |
| return pow(26, $i) * $code; | |
| } | |
| }, $chars, $range); | |
| return array_sum($numbers); | |
| } | |
| function test(){ | |
| assert(main('A') === 1); | |
| assert(main('B') === 2); | |
| assert(main('Z') === 26); | |
| assert(main('AA') === 27); | |
| assert(main('XFD') === 16384); | |
| assert(main() === null); | |
| assert(main(0) === null); | |
| assert(main('0') === null); | |
| assert(main('') === null); | |
| assert(main(false) === null); | |
| assert(main("ほげ") === null); | |
| } | |
| if(count($argv) !== 2){ | |
| echo 'Usage: '.$argv[0].' ARG', "\n"; | |
| exit(0); | |
| } | |
| $stdin = trim($argv[1]); | |
| if($stdin){ | |
| echo main($stdin), "\n"; | |
| } | |
| exit(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment