29
\$\begingroup\$

Challenge

In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc.

1 -> A
2 -> B
...
26 -> Z

A -> 1
B -> 2
...
Z -> 26

Rules

  • This is , so shortest code in bytes wins.
  • The input will only consist of either an uppercase letter from A to Z or an integer from 1 to 26 inclusive.
  • Trailing whitespaces (space and newline) are allowed.
\$\endgroup\$
15
  • 1
    \$\begingroup\$ Why duplicate? O.o It is not equal. \$\endgroup\$
    – Chad
    Aug 15, 2016 at 21:50
  • 3
    \$\begingroup\$ Welcome to Programming Puzzles and Code Golf! This challenge could use a bit of clarification. For example, you could specify what inputs we would need to handle, since there are invalid inputs. I recommend posting future challenges to the Sandbox where they can get meaningful feedback before being posted to the main site. \$\endgroup\$
    – Leaky Nun
    Aug 15, 2016 at 21:55
  • 2
    \$\begingroup\$ Will we receive 26 as an integer or "26" as a string, or are both allowed? \$\endgroup\$
    – Leaky Nun
    Aug 15, 2016 at 22:38
  • 2
    \$\begingroup\$ Does it have to be uppercase, or is lowercase acceptable instead? \$\endgroup\$
    – user45941
    Aug 16, 2016 at 1:45
  • 1
    \$\begingroup\$ Seriously, another alphabet challenge? ( ͡° ͜ʖ ͡°) \$\endgroup\$
    – shooqie
    Aug 16, 2016 at 7:11

58 Answers 58

1
2
1
\$\begingroup\$

Python 3, 49 48 53 50 bytes

Somehow I got the byte count wrong ;_; thanks dahuglenny

isalpha is shorter than isnumeric

lambda x:x.isalpha()and ord(x)-64or chr(int(x)+64)

takes input as string, which could be a letter or number

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can remove the space between x.isnumeric() and else to save one byte. \$\endgroup\$
    – acrolith
    Aug 15, 2016 at 23:34
1
\$\begingroup\$

Java, 61 bytes

int f(char c){return c^64;}char f(int i){return(char)(i^64);}

Ungolf'd:

int f(char c) {
    return c^64;
}

char f(int i) {
    return (char) (i^64);
}

Calling f('A') invokes the first function, retuning an int 1; calling f(1) invokes the second function, returning the char "A".

\$\endgroup\$
4
  • \$\begingroup\$ ` you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc.` I don't think a set of functions qualifies for this. \$\endgroup\$
    – Shaun Wild
    Aug 17, 2016 at 8:33
  • 1
    \$\begingroup\$ @SeanBean it's a function overload. \$\endgroup\$ Aug 18, 2016 at 4:50
  • 1
    \$\begingroup\$ That takes no input. That gives no output. There is no program! \$\endgroup\$ Aug 20, 2016 at 22:22
  • \$\begingroup\$ You should assume the input is either "A".."Z" or "0".."9". Since a string is the only primitive that can hold either (you don't know what the input it going to be) your function should expect a string argument. \$\endgroup\$
    – RobIII
    Sep 12, 2019 at 9:24
1
\$\begingroup\$

Javascript 86 77 66 60 bytes

i=>typeof i<'s'?String.fromCharCode(i+64):i.charCodeAt(0)-64
  • saved 7 bytes after comments about using arrow functions
  • saved another 11 bytes by removing return / brackets as noted by @manatwork
  • saved another 6 bytes thanks to @manatwork
\$\endgroup\$
9
  • 1
    \$\begingroup\$ Use arrow functions \$\endgroup\$ Aug 16, 2016 at 16:52
  • \$\begingroup\$ @BaldBantha cheers, changed it :-) \$\endgroup\$ Aug 17, 2016 at 8:11
  • \$\begingroup\$ No need for return statement: i=>typeof i=='number'?String.fromCharCode(i+64):i.charCodeAt(0)-64. \$\endgroup\$
    – manatwork
    Aug 17, 2016 at 8:22
  • \$\begingroup\$ @manatwork Cheers! \$\endgroup\$ Aug 17, 2016 at 8:24
  • 1
    \$\begingroup\$ According to task description the typeof input can be only "number" or "string". So no need to check for =='number', <'s' will also do it. \$\endgroup\$
    – manatwork
    Aug 17, 2016 at 8:31
1
\$\begingroup\$

ASM: 10 bytes

3C 40 77 04 2C 40 EB 02 04 40

Explanation: This is the assembled representation of a program that does exactly what is asked. It is not fully functional, because it needs some directives, but if it is added to the code segment of an assembly program it should work. It receives the input in the AL register, and if its a letter it subtracts 40h from the ASCII code value, leaving just the number(i.e B=42h, 42h-40h=2h). If the input is a number it does the opposite procedure by adding 40h. It leaves the result in the AL register. Below is the assembly source code

cmp al,40h
ja letter_to_number
sub al,40h
jmp continue
letter_to_number: add ax,40h
continue:

Also, if you convert all the other answers to machine code, I am positive that mine would be the smallest.

\$\endgroup\$
4
  • \$\begingroup\$ I think there are a few issues: 77 02 2C should be 77 **04** 2C; the sub and add are backwards. \$\endgroup\$
    – ceilingcat
    Aug 23, 2016 at 0:55
  • \$\begingroup\$ I applied the above corrections and created a "function" that you can call from a C program on an x86_64 machine. #define F(x) ((int(*)(int))"\x89\xf8\x3c\x40\x76\4\x2c\x40\xeb\2\4\x40\xc3")(x) \$\endgroup\$
    – ceilingcat
    Aug 23, 2016 at 0:58
  • \$\begingroup\$ What type of assembly is this? \$\endgroup\$
    – mbomb007
    Oct 26, 2016 at 14:39
  • \$\begingroup\$ Turbo Assembler \$\endgroup\$
    – 6a75616e
    Oct 28, 2016 at 19:15
1
\$\begingroup\$

Brachylog, 10 bytes

;.L∧Ṇi₁pL∧

Try it online!

The core of this is only 4 bytes, but the I/O for that version is a bit less than sane.

\$\endgroup\$
1
\$\begingroup\$

05AB1E (legacy), 9 bytes

di.bëÇ64-

Try it online or verify all test cases.

Also works in the new version of 05AB1E instead of the legacy, but the Ç wraps in a list: Try it online or verify all test cases.

Explanation:

di      # Legacy 05AB1E version: If the (implicit) input is an integer:
        # New 05AB1E version: If the (implicit) input is a positive (>= 0) integer:
  .b    #  Builtin to convert the integer to its 1-based uppercase alphabetic letter
 ë      # Else:
  Ç     #  Get the codepoint of the uppercase letter
   64-  #  And subtract 64 to convert it to its 1-based index
        # (after which the result is output implicitly)
\$\endgroup\$
1
\$\begingroup\$

Vyxal, 12 4 bytes

øAɾt

Try it Online!

  • -8 thanks to @lyxal

Explanation

Of course there's a built-in

øAɾt # Implicit input
øA   # Letter to number or number to letter
  ɾ  # Range or uppercase (overloaded)
   t # Last item

Old:

‹kA:?c[?ḟ›|i  # Implicit input
‹             # Decrement (no effect on strings)
 kA:          # Push uppercase alphabet and duplicate
    ?c        # Is the input alphabetic?
      [       # If it is:
       ?ḟ     #  Find the 0-based index of the input in the alphabet
         ›    #  And increment it to make it 1-based
          |   # Otherwise:
           i  #  Index input-1 into the alphabet
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Try it Online! for 4 bytes \$\endgroup\$
    – lyxal
    Mar 12, 2023 at 12:51
  • \$\begingroup\$ @lyxal nice, thanks \$\endgroup\$
    – The Thonnu
    Mar 12, 2023 at 12:59
1
\$\begingroup\$

Lua, 76 53 50 bytes

x=...y=x:byte()print(64<y and y-64or x.char(x+64))

Try it online!

Explanation

x=... -- unpack command line arguments into x
y=x:byte()
print(
64<y -- if the first byte of the string > 64:
and y-64 -- print the first byte-64
or x.char(x+64) -- else, print chr(x+64)
)
\$\endgroup\$
1
\$\begingroup\$

Julia 1.0, 22 bytes

~a=a-'@'
~n::Int=n+'@'

Try it online!

This solution involves a single function with 2 methods.

\$\endgroup\$
0
\$\begingroup\$

R, 75 bytes

f=function(l,a=which(LETTERS==l))ifelse(length(a),a,LETTERS[as.numeric(l)])

This function technically has two inputs. But the second one is merely there because by setting a through a default, I can get rid of 2 bytes. Give the function a quoted letter or number, or just a number, and it will return the opposite.

Explanation: a tests if it is a letter and which one it is. If it isn't it pulls the relevant letter.

\$\endgroup\$
0
\$\begingroup\$

Python 2, 45 44 bytes

Code:

lambda x:chr(x+64)if`x`[0]>"("else ord(x)-64
\$\endgroup\$
0
\$\begingroup\$

Pyth, 13 bytes

.xC+64sQhxr1G

Test suite.

\$\endgroup\$
0
\$\begingroup\$

Gema, 53 characters

<K>=@sub{@char-int{$0};64}
<D>=@int-char{@add{$0;64}}

Sample run:

bash-4.3$ gema '<K>=@sub{@char-int{$0};64};<D>=@int-char{@add{$0;64}}' <<< 'M'
13

bash-4.3$ gema '<K>=@sub{@char-int{$0};64};<D>=@int-char{@add{$0;64}}' <<< '13'
M
\$\endgroup\$
4
0
\$\begingroup\$

Dyalog APL, 14 bytes

{0::⎕A⍳⍵
⍵⊃⎕A}

0:: if any error happens:
⎕A⍳⍵ return the index of the argument in the alphabet

⍵⊃⎕A use the argument to pick an element from the alphabet (errors if the argument is character)

TryAPL online!

\$\endgroup\$
0
\$\begingroup\$

R, 62 Bytes

f=function(x)ifelse(is.finite(x),LETTERS[x],which(LETTERS==x))

Takes the input x and checks if it is finite, which is one byte shorter than checking if it is numeric and equivalent in this case. If yes, output the letter, if no, output the position in the alphabet equal to the character input.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Do you need ==1? is.finite returns logical \$\endgroup\$
    – bouncyball
    Aug 16, 2016 at 13:47
  • \$\begingroup\$ match(x,LETTERS) is 3 bytes shorter \$\endgroup\$
    – Giuseppe
    May 25, 2017 at 13:47
0
\$\begingroup\$

SQF, 72 bytes

Using the function-as-a-file format:

i=_this;if((str i)==i)then{toString[i+64]}else{((toArray i)select 0)-64}

Call as: ARG call NAME_OF_COMPILED_FUNCTION

\$\endgroup\$
0
\$\begingroup\$

q, 44 bytes

Reads from stdin

{$[0N~i:"J"$x;1+.Q.A?x 0;.Q.A i-1]}[read0 0]
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 41 bytes

x=>-x?(9+x).toString(36):parseInt(x,36)-9
\$\endgroup\$
4
  • \$\begingroup\$ Actually I just noticed this answer is wrong. The input will be uppercase, it doesn't work then \$\endgroup\$ Aug 17, 2016 at 14:07
  • \$\begingroup\$ @Dylan Fixed at the expense of three bytes. \$\endgroup\$ Aug 17, 2016 at 14:12
  • \$\begingroup\$ Nice, but it doesn't give upper-case output yet. Not sure if that is also required though ;-) Nice answer though (y) \$\endgroup\$ Aug 17, 2016 at 14:14
  • \$\begingroup\$ This is almost the same as my alternative answer, except for your -x golf. \$\endgroup\$
    – Neil
    Aug 21, 2016 at 11:37
0
\$\begingroup\$

Racket 58 bytes

(if(char? i)(-(char->integer i)64)(integer->char(+ 64 i)))

Ungolfed:

(define (f i)
  (if (char? i)
      (-(char->integer i) 64)
      (integer->char (+ 64 i))))

Testing:

(f 1)
(f 3)
(f #\A)
(f #\D)

Output:

#\A
#\C
1
4
\$\endgroup\$
0
\$\begingroup\$

DASH, 33 bytes

@[="num"type#0?fc +64#0?-(tc#0)64

Woo-hoo, first PPCG answer in my new functional programming language!

Installation and other info is all on the Github.

Usage

(@[="num"type#0?fc +64#0?-(tc#0)64])"A"  #. strings
(@[="num"type#0?fc +64#0?-(tc#0)64])26   #. numbers

Explanation

@                      #. lambda
  [                    #. start of conditional block
    = "num" (type #0)  #. check if argument is a number
      ? fc (+ 64 #0)   #. if so, add 64 to argument and convert from charcode
      ? - (tc #0) 64   #. otherwise, convert argument to charcode and subtract 64
                       #. we can actually leave off the closing bracket for now
\$\endgroup\$
0
\$\begingroup\$

tcl, 68

Not a champion by any measure, but I had to do it.

puts [expr {[string is di $a]?[format %c [incr a 64]]:[scan $a %c]}]

demo

\$\endgroup\$
0
\$\begingroup\$

C++ (gcc), 27 bytes

As unnamed generic lambda, accepting char or int and returning via reference parameter (input=output)

[](auto&r){r+=r<64?64:-64;}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

q/kdb+, 28 26 bytes

Solution:

{((?;@) -7=(@)x)[`,.Q.A]x}

Examples:

q){((?;@) -7=(@)x)[`,.Q.A]x}1
"A"
q){((?;@) -7=(@)x)[`,.Q.A]x}2
"B"
q){((?;@) -7=(@)x)[`,.Q.A]x}26
"Z"
q){((?;@) -7=(@)x)[`,.Q.A]x}"A"
1
q){((?;@) -7=(@)x)[`,.Q.A]x}"B"
2
q){((?;@) -7=(@)x)[`,.Q.A]x}"Z"
26

Explanation:

Check the type of the input, if it's a long (-7h) then use the apply @ operator to index into the alphabet .Q.A, otherwise use ? to lookup the input in the alphabet. Note that we add null to the start of the alphabet to fake the 1-indexing:

{((?;@) -7h=type x)[`,.Q.A;x]} / ungolfed solution
{                            } / lambda function
                   [      ; ]  / apply a function to this
                    `,.Q.A     / join ` (null) to the string "ABC...XYZ"
                           x   / implicit input (e.g. "A" or 13)
 (                )            / do all this together
        -7h=type x             / is the type of parameter x a long (-7)
  (?;@)                        / ? (lookup) if true, @ (index) if false

Notes:

  • -2 bytes by using indexing instead of switch statement.
\$\endgroup\$
0
\$\begingroup\$

MathGolf, 13 bytes

▄l!╧¿É$♦-É♦+$

Try it online.

Explanation:

 l         # Push the input as string
  !        # Convert it to lowercase
    ¿      # If
▄          #    the lowercase alphabet
   ╧       #                           contains this value:
     É     #  Execute the following three operations:
      $    #   Convert the (implicit) input to its unicode value
       ♦-  #   Subtract 64
           # (Implicit else:)
     É     #  Execute the following three operations:
      ♦+   #   Add 64 
        $  #   And convert it to the character with this unicode value
           # (after which the entire stack joined together is output implicitly)
\$\endgroup\$
0
\$\begingroup\$

Haskell, 63 62 bytes

This uses the rule that wrapping the output in an optional type is allowed. We just use the standard lookup function to search in a list of tuples that define the input/output relationship.

(`lookup`zip(c++n)(n++c))
c=pure<$>['A'..'Z']
n=show<$>[1..26]

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Commodore BASIC (C64/128/TheC64, VIC-20, PET) - 90 48 (tokenized) bytes

 0inputa$:ifval(a$)>0then?chr$(64+val(a$)):end
 1?asc(a$)-64

Explanation and screen shot later.

\$\endgroup\$
0
\$\begingroup\$

Stax, 15 bytes

Ö└╝╨→ε/óo↕[▄╢▐W

Run and debug it

This unpacks to the following 18 bytes:

cc%!{64+z+}{E64-}?

Run and debug it

\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 1 byte

Ä

Attempt This Online!

Overloaded built-in that works on both numbers (1 -> A, 2 -> B, ...) and letters (A -> 1, B -> 2, ...).

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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