The challenge

The shortest code by character count that will output the numeric equivalent of an Excel column string.

For example, the A column is 1, B is 2, so on and so forth. Once you hit Z, the next column becomes AA, then AB and so on.

Test cases:

A:    1
B:    2
AD:   30
ABC:  731
WTF:  16074
ROFL: 326676

Code count includes input/output (i.e full program).

share

locked by Shog9 Apr 3 '15 at 16:34

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

19  
Code golf is pointless, APL always wins in the end. – BlueRaja - Danny Pflughoeft Apr 14 '10 at 3:09
1  
When you post a solution, please make sure it works across all the cases above (input/output as run is nice), and note where it does not. Thanks. – user166390 Apr 16 '10 at 18:49
3  
Why the hell is this tagged with rosetta-stone?! – Josh Stodola Apr 16 '10 at 19:59
2  
J is APL without the Greek. J will always win, no one speaks APL anymore. – Callum Rogers Apr 16 '10 at 21:48
1  
@BlueRaja: It's interesting that APL is still winning these things in 2010, almost 40 years after it left the mainstream. – Kragen Javier Sitaker Apr 16 '10 at 21:58

67 Answers 67

up vote 96 down vote accepted

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.

share
2  
Use $_ or $` instead of $n` and call print with no args. – mob Apr 14 '10 at 6:44
4  
use "-p" and drop print altogether : echo -n WTF | perl -p -e '$_=()=A..$_' Total code : 11 characters, AH AH! – wazoox Apr 16 '10 at 13:27
2  
switch print to say and drop another 2 characters :) – mpeters Apr 16 '10 at 14:38
16  
Ah I love the goatse operator :) – Ether Apr 16 '10 at 17:40
6  
Hey, Perl beats J! – David Apr 16 '10 at 23:20

Excel - 99 characters

Enter as array formula - I am not counting Excel adding { }

=SUM((CODE(MID(A1,ROW(INDIRECT("1:" & LEN(A1))),1))-64)*26^(LEN(A1)-ROW(INDIRECT("1:" & LEN(A1)))))

share

APL: 7 characters

Store desired string in variable w:

w←'rofl'

Assuming characters are lowercase:

26⊥⎕a⍳w

Assuming characters are uppercase:

26⊥⎕A⍳w

Mixed case or unsure of case (14 chars, but could possibly be improved):

26⊥⊃⌊/⎕a⎕A⍳¨⊂w
share

Excel, 9 chars :)

Use the right tool for the job:

=COLUMN()

=COLUMN()

share
166  
Use the right language for the job: Portuguese Excel =COL(). 6 characters. (See dolf.trieschnigg.nl/excel/excel.html ) – Debilski Apr 14 '10 at 11:03
21  
Great! only it does not support ROFL though. – YOU Apr 14 '10 at 11:14
63  
This solution even reproduces the limitations of Excel correctly. – kibibu Apr 15 '10 at 3:55
18  
It doesn't even take a string as input. Doesn't come close to doing what the problem said. It only works if it's in the column that happens to be named after the string in question. Totally not in the spirit of the question. – phkahler Apr 16 '10 at 14:51
21  
+1 for the SO column. – Alex Budovski Apr 18 '10 at 3:11

JavaScript 1.8: 66 characters

function a(p)Array.reduce(p,function(t,d)t*26+d.charCodeAt()-64,0)

Javascript 1.8: 72 characters

function a(p)(t=0,p.replace(/./g,function(d)t=t*26+d.charCodeAt()-64),t)

JavaScript 1.6: 83 characters

function a(p){t=0;p.split("").map(function(d){t=t*26+d.charCodeAt(0)-64});return t}

JavaScript: 95 characters

function a(p){r=0;t=1;l=p.length;for(i=0;i<l;i++){r+=(p.charCodeAt(l-1-i)-64)*t;t*=26}return r}

JavaScript: 105 characters

function a(p,i){i=i||0;l=p.length;return p?(p.charCodeAt(l-1)-64)*Math.pow(26,i)+a(p.slice(0,l-1),i+1):0}

Usage:

a("A")        // 1
a("B")        // 2
a("AD")       // 30
a("ABC")      // 731
a("WTF")      // 16074
a("ROFL")     // 326676
share
    
@Ates: Nice trick! I like map() :) – Daniel Vassallo Apr 14 '10 at 10:13
    
I shaved 4 more characters from the 1.6 solution using expression closures. You may be able to shrink it a bit more by refactoring the (t?g*26:0) part. – David Murdoch Apr 16 '10 at 18:39
    
UPDATE. I just shaved off 9 more characters by using [].reduce – David Murdoch Apr 16 '10 at 18:48
    
FWIW, I added an implementation using string#replace – Chetan Sastry Apr 16 '10 at 19:39
    
@Chetan, @David: Good job. That's neat! – Daniel Vassallo Apr 16 '10 at 19:42

Ruby, 20 characters

p('A'..$*[0]).count

Usage:

$ ruby a.rb ABC
731
share

in VBA I got it down to 98

Sub G(s)
Dim i, t
For i = 0 To Len(s) - 1
    t = t + ((Asc(Left(Right(s, i + 1), 1)) - 64)) * ((26 ^ i))
Next
MsgBox t
End Sub
share
3  
Surely you don't need the indentation. – user181548 Apr 14 '10 at 8:28
    
Force of habbit sorry! – Kevin Ross Apr 14 '10 at 8:46
    
You don't need to declare the sub as Public, and nor do you need to say "Next i" (just use "Next"). Also, I think if you loop from 1 rather than zero you can shave off a character or two. – Gary McGill Apr 16 '10 at 14:59
    
@Gary, thanks for the tips, this is my first "round" of code golf I'm sure I will get better after a few more goes – Kevin Ross Apr 16 '10 at 20:14

Ruby solution in 26 chars

p ("A"..$*[0]).to_a.size

share

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.
share
6  
+1 J pwns golfscript when it comes to base conversions :) – John La Rooy Apr 14 '10 at 22:25
2  
After reading a few comments about how the Excel solution really doesn't take a string input, I'm going to go with the solution that is the shortest, and actually takes a string input. – Vivin Paliath Apr 16 '10 at 16:44
    
Wow a J solution I can actually understand :) – Callum Rogers Apr 16 '10 at 21:49
    
J is made for this stuff. – Brandon Pelfrey Apr 16 '10 at 23:05
2  
@Brandon: J is made for everything, as long as you don't mind spending years learning how to read it. – David Apr 16 '10 at 23:19

Excel VBA, 19 characters:

range("WTF").Column

share

K 3.2 (13 characters)

26_sv -64+_ic

Usage:

  26_sv -64+_ic"ROFL"
326676

Explanation:

  • As mentioned above K evaluates from right to left, so the _ic function takes whatever is to its right and converts it to an integer value, this includes both single characters and character vectors
  • -64 is added to each item in the integer vector that to get a set of base values
  • _sv takes two arguments: the one on its left is the numeric base, 26, and the one on its right is the integer vector of offset values
share

F# (37 chars):

Seq.fold (fun n c -> int c-64+26*n) 0
share

k4 (kdb+), 11 characters

26/:1+.Q.A?

Explanation:

  • k4 parses left of right
  • .Q.A is defined within k4 - it is the vector "ABC...XYZ"
  • ? is the find operator - the index of the first match for items in the y arg within the x arg
  • +1 to offset the index
  • 26/: to convert to base 26

One caveat - this will only work where listed types are passed in:

  26/:1+.Q.A? "AD"
30

  26/:1+.Q.A? "WTF"
16074

but:

  26/:1+.Q.A? ,"A"
1
share

straight bash

filter: 97 chars

{ read c;i=0;while [ $c ];do eval s=({A..${c:0:1}});i=$((i*26+${#s[@]}));c=${c:1};done;echo $i;}

Usage:

echo ROFL | { read c;i=0;while [ $c ];do eval s=({A..${c:0:1}});i=$((i*26+${#s[@]}));c=${c:1};done;echo $i;}
326676

function: 98 chars

C(){ i=0;while [ $1 ];do eval s=({A..${1:0:1}});i=$((i*26+${#s[@]}));set -- ${1:1};done;echo $i;}

Usage:

C ROFL
326676

Explanation of the filter version:

read c;i=0;

Initialize the column and the total.

while [ $c ];do

while there are still column characters left

eval s=({A..${c:0:1}});

${c:0:1} returns the first character of the column; s=({A..Z}) makes s an array containing the letters from A to Z

i=$((i*26+${#s[@]}));

$((...)) wraps an arithmetic evaluation; ${#s[@]} is the number of elements in the array $s

c=${c:1};done;

${c:1} is the characters in $c after the first. done ends the while loop

echo $i

um i forget

better but dubious

Removing the 5 characters "echo " will result in the output for an input of "ROFL" being

326676: command not found

Also the i=0 is probably not necessary if you're sure that you don't have that variable set in your current shell.

share

OOBasic: 178 characters, not counting indentational whitespace

revised

This version passes all the test cases. I suspect that it would be more successfully golf if it didn't "take advantage" of the fact that there's a spreadsheet using this numbering system. See the notes on the original version below for info on why that's not particularly useful. I didn't try very hard to cut down the score.

Also note that this will only work when run as a macro from an OO calc spreadsheet, for obvious reasons.

Function C(st as String) as Long
    C = 0
    while len(st)
        C = C*26 + ThisComponent.Sheets(0).getCellRangeByName(left(st,1) &"1").CellAddress.Column+1
        st = mid(st,2)
    wend
End Function

original

OOBasic (OpenOffice Basic), too many characters (124):

Function C(co As String) As Long 
    C = ThisComponent.Sheets(0).getCellRangeByName(co &"1").CellAddress.Column+1
End Function

Limitations:

  • maximum value of co is AMJ (1024 columns). Anything larger results in an error with a completely uninformative error message.
    • This limitation is also present for the COLUMN() cell function. Presumably this is the maximum number of columns in an OOCalc spreadsheet; I didn't bother scrolling over that far or googling to find out.

Notes:

  • strangely it's not possible to give the variable 'co' a 1-letter name. Not sure what the logic is behind this, but after having spent enough time using OOBasic you stop looking for logic and begin to blindly accept the way things are (perhaps from gazing too long at the Sun).

Anyway entering =C("A"), =C("ABC"), etc. in a cell works for the first four test cases; the last two give errors.

share

Josl in 48 characters

main 0 0 argv each 64 - swap 26 * + next print

Examples:

$ josl numequiv.j A
1
$ josl numequiv.j ABC
731
$ josl numequiv.j ROFL
326676

Reading from standard input:

main 0 STDIN read-line each 64 - swap 26 * + next print
share

Python: 88 characters

using list comprehensions:

s=input()
print sum([((26**(len(s)-i-1))*(ord(s[i])-64)) for i in range(len(s))])
share

php 29 chars:


while($i++!=$t)$c++;echo$c+1;

  • assuming register_globals=On
  • assuming error_reporting=0
  • call via webserver ?i=A&t=ABC
share

PHP - 73 Chars

$n=$argv[1];$s=$i=0;while($i<strlen($n))$s=$s*26+ord($n[$i++])-64;echo$s;

Usage:

php -r '$n=$argv[1];$s=$i=0;while($i<strlen($n))$s=$s*26+ord($n[$i++])-64;echo$s;' AA

> 27
share
1  
You could lose 10 characters by removing the curly braces around your while function and dumping the variable initialization. – ChiperSoft Apr 16 '10 at 17:23

Go: 106 characters

It's not the shortest of all the languages. But it can be the shortest of C, C++, Java, and C#.

package main
import("os"
"fmt")
func main(){t:=0
for _,c := range os.Args[1]{t=t*26+c-64}
fmt.Println(t)}

Formated version:

package main

import (
    "os"
    "fmt"
)

func main() {
    t := 0
    for _, c := range os.Args[1] {
        t = t*26 + c - 64
    }   
    fmt.Println(t)
}
share

Prolog: 49 chars

c([],A,A).
c([H|T],I,R):-J is H-64+I*26,c(T,J,R).

Using the above code:

| ?- c("WTF",0,R).
R = 16074 ? 
yes
| ?- c("ROFL",0,R).
R = 326676 ? 
yes
share

Python, 64 49 characters

s=0
for c in raw_input():s=26*s+ord(c)-64
print s

You can also replace raw_input() with input() to reduce the character count by 4, but that then requires the input to contain quotation marks around it.

And here's a subroutine that clocks in at 47 characters:

f=lambda x:len(x)and 26*f(x[:-1])+ord(x[-1])-64
share
    
-1: Not a full program. – kennytm Apr 14 '10 at 13:07
    
@KennyTM: Fixed – Adam Rosenfield Apr 14 '10 at 15:22
    
your #2 should be named f. Try running it now, it doesn't work. And it can be made shorter(47 characters) with the help of lambdas and short circuit evaluation: f=lambda x:len(x)and 26*f(x[:-1])+ord(x[-1])-64 – Wallacoloo Apr 17 '10 at 1:02
    
@wallacoloo: Thanks. It's a community wiki, so you can feel free to make edits any time. – Adam Rosenfield Apr 17 '10 at 5:26
    
how about dropping len(x) for x alone? becomes 43 chars: f=lambda x:x and 26*f(x[:-1])+ord(x[-1])-64 – Nas Banov May 14 '10 at 22:16

Groovy: 51 Characters

char[] a=args[0];t=0;for(i in a)t=26*t+i-64;print t

Invoke as

groovy *scriptname* ROFL

or

groovy -e "char[] a=args[0];t=0;for(i in a)t=26*t+i-64;print t" ROFL

This essentially the same as Java. I imagine some possibilities with using ranges and closures, but nothing came to mind for this example. Anyone else see a way to shorten this?

A more groovy-looking version with a closure is a bit longer, unfortunately.

t=0;args[0].toCharArray().each{t=t*26+it-64};print t
share

MATLAB: 24 characters

polyval(input('')-64,26)

Usage:

>> polyval(input('')-64,26)
(after pressing enter) 'WTF'

ans =

       16074

Note: You can get it down to 16 characters if you pre-store the string in x, but I kind of thought it was cheating:

>> x = 'WTF'

x =

WTF

>> polyval(x-64,26)

ans =

       16074
share
    
How could I forget about polyval.. +1 for better solution – George Apr 17 '10 at 9:00

Factor: 47 characters

reverse [ 26 swap ^ swap 64 - * ] map-index sum

share

Matlab 38 chars


Works only with uppercase letters. Not sure if it has to work with lowercase too (none in example).

x=input('')'-64;26.^(size(x)-1:-1:0)*x

If new lines do not count only 37 (omitting semicolon):

x=input('')'-64
26.^(size(x)-1:-1:0)*x

I see Matlab beats a lot of languages. Who would expect that.

Example:

Input: 'ROFL' (dont forget the '' )
Output: ans = 326676
share

PHP, 38 chars

for($a=A;++$c,$a++!=$argv[1];);echo$c;

usage, e.g.

php -r 'for($a=A;++$c,$a++!=$argv[1];);echo$c;' WTF
share

Common Lisp, 86 characters.

(defun z(s)(let((a 0))(map nil(lambda(v)(setf a(+(* 26 a)(digit-char-p v 36)-9)))s)a))
share

C#, 117 111 chars

No contest compared to the likes of Perl, Ruby and APL but an improvement on the other C#/Java answers given so far.

This uses Horner's rule.

class C{static void Main(string[]a){int t=0;foreach(var c in a[0]){t=(t+c-64)*26;}System.Console.Write(t/26);}}
share
1  
You can save 3 chars by removing the space between the [] and the 'a', and the foreach braces. – Cameron MacFarland Apr 16 '10 at 17:09
    
I didn't know string implemented IEnumerable. Sweet! Unfortunately the page about Horner's rule is way over my head, but clearly a winning strategy. I don't like using Console.Write() though, due to the messy output. +1 – Igby Largeman May 10 '10 at 19:32

F# 92 chars :)


let e2n (c : string) = c |> Seq.map (fun x -> (int)x - 64) |> Seq.reduce(fun e a -> a*26+e)

share

Not the answer you're looking for? Browse other questions tagged or ask your own question.