21
2
This one comes from a real life problem. We solved it, of course, but it keeps feeling like it could have be done better, that it's too lengthy and roundabout solution. However none of my colleagues can think of a more succinct way of writing it. Hence I present it as code-golf.
The goal is to convert a nonnegative integer into a string the same way Excel presents its column headers. Thus:
0 -> A
1 -> B
...
25 -> Z
26 -> AA
27 -> AB
...
51 -> AZ
52 -> BA
...
16,383 -> XFD
It has to work at least up to 16,383, but beyond is acceptable too (no bonus points though). I'm looking forward most to the C# solution, but, as per traditions of code-golf, any real programming language is welcome.
r1c1 notation is allowed? – tuskiomi – 2016-10-21T20:15:08.957
That would be too easy :) – Vilx- – 2016-10-22T14:07:30.730
This is a super old challenge, but I'm a bit flummoxed why you've specified a 0-based index, since Excel itself uses a 1-based index.
=ADDRESS(1,1)
returns$A$1
. See Dr. belisarius' Excel answer. – BradC – 2018-05-01T16:44:57.900@BradC - You know, I don't really remember anymore. :) It could be that I'm just used to 0-based indexing. Or maybe we did use that result as an index in a 0-based array (we used C#). Or maybe that's how it appears internally in the XLSX files. Anyways, converting from 0-based to 1-based is just a
+1
, so it doesn't matter much. :) – Vilx- – 2018-05-01T17:26:20.310Are you sure that 16383 should be XFD? What do you get for 676 and 702? – Peter Taylor – 2011-11-24T23:29:41.677
Well, that's what Excel shows, and I found it on the web that it has 16384 columns. I'll test it tomorrow with our (known to work) code (is late night right now where I live). – Vilx- – 2011-11-24T23:56:50.883
Also, testing with Excel itself reveals that 676=ZA and 702=AAA. – Vilx- – 2011-11-24T23:59:05.673
1The reason I ask is that I wrote some straightforward base-26 code, got results which fit yours precisely, but broke on 676 and 702. – Peter Taylor – 2011-11-25T08:21:45.280
1Yup. It's not Base-26. That's the problem. ;) – Vilx- – 2011-11-25T08:44:15.797
If your numbering started from 1 it would be base-27 (A-Z and the empty string representing the 0), I think. As it is, the rightmost column has 26 possible values and the rest have 27. Which is awkward. – Gareth – 2011-11-25T09:28:43.493
@Gareth, it's more complicated than that, because e.g. the 2nd least significant column only has 27 possible values if the 3rd least significant column is ''. Otherwise it's restricted to 'A'..'Z'. – Peter Taylor – 2011-11-25T10:24:23.277
@PeterTaylor True. I know it took a good half hour or so of fiddling to get my version to give the correct result. – Gareth – 2011-11-25T10:59:07.433