Skip to content

Instantly share code, notes, and snippets.

@laiso
Created November 3, 2011 05:58
Show Gist options
  • Select an option

  • Save laiso/1335869 to your computer and use it in GitHub Desktop.

Select an option

Save laiso/1335869 to your computer and use it in GitHub Desktop.
http://d.hatena.ne.jp/JunichiIto/20111102/1320253815 の"問題1: Excel列名変換問題"
#!/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