Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Golf: Numeric equivalent of an Excel column name

Excel, 9 chars :)

Use the right tool for the job:

=COLUMN()

=COLUMN()


Perl, 36 34 33 31 30 17 15 11 characters

$_=()=A..$_

Usage:

$ echo -n WTF | perl -ple '$_=()=A..$_'
16074

Reduced to 17 by using echo -n to avoid a chop call.

Reduced to 15 by using say instead of print.

Reduced to 11 by using -p instead of say.

Explanation: A is evaluated in string context and A..$_ builds a list starting at "A" and string-incrementing up to the input string. Perl interprets the ++ operator (and thus ..) on strings in an alphabetic context, so for example $_="AZ";$_++;print outputs BA.

=()= (aka "goatse" operator) forces an expression to be evaluated in list context, and returns the number of elements returned by that expression i.e., $scalar = () = <expr> corresponds to @list = <expr>; $scalar = @list.


J, 17 12 10 characters

26#.64-~av

Example:

26#.64-~av  'WTF'
16074

Explanation:

  • J parses from right to left.
  • av returns a list of the ascii indexes of each of the characters in its argument, so for example av'ABC' returns 65 66 67.
  • Then we subtract 64 from each element of that list with the verb 64-~.
  • Then we convert the list to base 26 using the #. verb.

Brainf*ck, 81 characters (no whitespace)

,[>>>[->>+++++[-<+++++>]<+<]>[-<+>]<<++++++++[<++++++++>-]<[<->-]<[>>>+<<<-],]>>>

Explanation

,[  // get character input into p[0], enter loop if it isn't null (0)
>>>[->>+++++[-<+++++>]<+<] // take what's in p[3] and multiply by 26, storing it in p[4]
>[-<+>] // copy p[4] back to p[3]
<<++++++++[<++++++++>-]< // store 64 in p[1]
[<->-]< // subtract p[1], which is 64, from the input char to get it's alphabetical index
[>>>+<<<-] // add p[0] to p[3]
,] // get another character and repeat
>>> // move to p[3], where our final result is stored

So you'll notice I didn't actually convert the numerical value to an ascii string for printing. That would likely ruin the fun. But I did the favor of moving the pointer to the cell with the result, so at least it's useful to the machine.

Hey, what do you know, I beat C#!