28
\$\begingroup\$

Given a string that contains only lowercase letters, encode that string with the alphabet cipher.

To encode with the alphabet cipher (I will be using the example hello):

  1. First, convert each letter in the string to a number depending on its position in the alphabet (a = 1, b = 2, etc.) Example: 8 5 12 12 15
  2. Pad each number to two characters with 0s. Example: 08 05 12 12 15
  3. Join. Example: 0805121215

Test cases

helloworld -> 08051212152315181204
codegolf -> 0315040507151206
alphabetcipher -> 0112160801020520030916080518
johncena -> 1015081403051401

Remember, this is , so the code with the fewest number of bytes wins.

\$\endgroup\$
1
  • \$\begingroup\$ Related. \$\endgroup\$
    – Oliver Ni
    Commented Oct 28, 2016 at 17:09

64 Answers 64

22
\$\begingroup\$

05AB1E, 11 6 bytes

Code:

Ç4+€¦J

Explanation:

First, we convert the string to their ASCII values. codegolf would become:

[99, 111, 100, 101, 103, 111, 108, 102]

To get to the indices of the alphabet, you subtract 96:

[3, 15, 4, 5, 7, 15, 12, 6]

To pad with zeros, add 100 to each element and remove the first character of each int. For the above example, +100 would be:

[103, 115, 104, 105, 107, 115, 112, 106]

And removing the first character of each would lead to:

[03, 15, 04, 05, 07, 15, 12, 06] 

We can merge both steps above (the -96 and the +100) part to just +4. For the code:

Ç       # Convert to an array of ASCII code points
 4+     # Add four to each element in the array
   €¦   # Remove the first character of each element
     J  # Join to a single string

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ What does ¦ do again? \$\endgroup\$ Commented Oct 28, 2016 at 17:33
  • \$\begingroup\$ @carusocomputing Removes the first element of a string, list, etc. \$\endgroup\$
    – Adnan
    Commented Oct 28, 2016 at 17:34
  • \$\begingroup\$ Beyond genius... \$\endgroup\$ Commented Oct 28, 2016 at 17:38
14
\$\begingroup\$

Python 2, 42 bytes

f=lambda s:s and`ord(s[0])+4`[1:]+f(s[1:])

Test it on Ideone.

\$\endgroup\$
1
  • 5
    \$\begingroup\$ Non recursive, same byte count: lambda s:''.join(`ord(x)+4`[1:]for x in s) \$\endgroup\$ Commented Oct 28, 2016 at 18:00
9
\$\begingroup\$

C, 55 43 bytes

f(char*c){for(;*c;)printf("%02d",*c++-96);}

ideone

\$\endgroup\$
1
  • 1
    \$\begingroup\$ printf("%02d",*c++-96);} is shorter and valid if I'm not mistaken. \$\endgroup\$
    – Dada
    Commented Oct 28, 2016 at 17:42
9
\$\begingroup\$

Pyth, 11 10 bytes

FNwpt`+4CN

Try it! My first go at Pyth.

FNwpt`+4CN
FNw         # For N in w (w is input, N will be single char)
   p        # Print without newline
        CN  # Int with code point `N`
      +4CN  # Add 4 to int with code point N
     `+4CN  # representation of above (basically to string)
    t`+4CN  # Tail (All but first character)

Python equivalent:

for N in input():
    print(repr(ord(N) + 4)[1:], end='')
\$\endgroup\$
1
  • \$\begingroup\$ Good job on your first Pyth program! \$\endgroup\$
    – hyperneutrino
    Commented Oct 28, 2016 at 19:04
7
\$\begingroup\$

Python, 46 bytes

lambda x:"".join("%02i"%(ord(j)-96)for j in x)

Pretty straightforward. Try it on repl.it!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Wow, two completely different attempts with the same byte count ;) \$\endgroup\$
    – Kade
    Commented Oct 28, 2016 at 17:19
7
\$\begingroup\$

Jelly, 9 7 bytes

O+4ṾḊ$€

TryItOnline

How?

O+4ṾḊ$€ - Main link: s                                e.g. hello
O       - cast to ordinals                            e.g. [ 104,  101,  108,  108,  111]
 +4     - add 4                                       e.g. [  108,  109,  112,  112,  115]
     $€ - last two links as a monad for €ach
   Ṿ    -    uneval, effectively converts to strings  e.g. ["108","109","112","112","115"]
    Ḋ   -    dequeue, remove the leading '1'          e.g. [ "08", "09", "12", "12", "15"]
        - implicit print                              e.g. "0809121215"
\$\endgroup\$
3
  • \$\begingroup\$ I came up with O+4DḊ€FṾ€ for the same count, perhaps golfable \$\endgroup\$ Commented Oct 28, 2016 at 17:39
  • \$\begingroup\$ @ETHproductions O+4Ṿ€Ḋ€ saves 2 bytes. \$\endgroup\$
    – Dennis
    Commented Oct 28, 2016 at 17:40
  • \$\begingroup\$ @Dennis I just did the same (ish)... \$\endgroup\$ Commented Oct 28, 2016 at 17:41
4
\$\begingroup\$

Haskell, fortyfour 30 28 bytes

(>>=tail.show.(+4).fromEnum)

Using the +4 approach from Adnan's answer saves 14 bytes.

Try it on Ideone. Usage:

> (>>=tail.show.(+4).fromEnum)"codegolf"
"0315040507151206"

Two bytes off thanks to xnor. Old version:

f a=['0'|a<'k']++(show$fromEnum a-96)
(f=<<)
\$\endgroup\$
1
  • \$\begingroup\$ You don't need the second set of parens. \$\endgroup\$
    – xnor
    Commented Oct 29, 2016 at 5:09
3
\$\begingroup\$

Perl, 29 bytes

28 bytes of code + -n flag.

printf"%02s",-96+ord for/./g

Run with :

perl -ne 'printf"%02s",-96+ord for/./g' <<< "helloworld"
\$\endgroup\$
1
  • \$\begingroup\$ 25 bytes (or 27 under the rules at the time of this challenge): Try it online! \$\endgroup\$
    – Xcali
    Commented Mar 26, 2020 at 20:14
3
\$\begingroup\$

JavaScript (ES6), 52 49 bytes

f=s=>s&&(s.charCodeAt()+4+f(s.slice(1))).slice(1)

Recursion turned out to be 3 bytes shorter than .replace:

s=>s.replace(/./g,s=>(s.charCodeAt()+4+"").slice(1))

parseInt(s,36) is slightly longer for each approach, because you have to change 4 to 91:

s=>s.replace(/./g,s=>(parseInt(s,36)+91+"").slice(1))
f=s=>s&&(parseInt(s[0],36)+91+f(s.slice(1))).slice(1)
\$\endgroup\$
3
\$\begingroup\$

Japt, 10 bytes

¡4+Xc)s s1

Probably doesn't get shorter than this...

Test it online!

Explanation

¡           // Map each char X in the input by this function:
 4+Xc)      //   Take 4 + the char code of X.
      s s1  //   Convert to a string, then remove the first char.
            // Implicit: output last expression
\$\endgroup\$
3
\$\begingroup\$

Java 7,60 bytes

void f(char[]s){for(int i:s)System.out.printf("%02d",i-96);} 
\$\endgroup\$
3
  • \$\begingroup\$ This answer might not be valid because it takes a char[] instead of a String. \$\endgroup\$
    – hyperneutrino
    Commented Oct 28, 2016 at 19:05
  • 1
    \$\begingroup\$ @AlexL. Lists of characters are considered strings. \$\endgroup\$ Commented Oct 28, 2016 at 19:23
  • \$\begingroup\$ @MartinEnder Okay. Thank you for the clarification. This answer has my upvote. \$\endgroup\$
    – hyperneutrino
    Commented Oct 28, 2016 at 19:23
3
\$\begingroup\$

MATL, 12 11 bytes

1 byte saved thanks to @Luis

4+!V4LZ)!le

Try it Online

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

Hexagony, 33 bytes

10}{'a({=!{{\.@29$\,<.-":!\>Oct\%

Try it Online!

Mm.. got a few no-ops in the Hexagon so I put today's date in.

Expanded Form with date replaced by no-ops

   1 0 } {
  ' a ( { =
 ! { { \ . @
. . $ \ , < .
 - " : ! \ >
  . . . \ %
   . . . .
  1. Initialise a 10 and move Memory Pointer to somewhere...
  2. $ skips the mirror and , reads a byte. < branches:
  3. If end of string (-1 which is non-positive) it goes to @ and terminates the program.
  4. Otherwise it subtracts 95 (decremented a), and then we print result / 10 (integer division) and result % 10 and loop again.
\$\endgroup\$
3
\$\begingroup\$

Stax, 5 bytes

öÇIªÆ

Run and debug it

For each character

  • add 4 to the codepoint e.g. 108
  • convert to string e.g. "108"
  • drop the first character e.g. "08"
\$\endgroup\$
3
+100
\$\begingroup\$

APL (Dyalog Unicode), 19 12 bytes SBCS

        ⎕UCS  ⍝ Convert the argument (string) into an array of codepoints.
      4+      ⍝ and add 4 to each of those codepoints.
     ¨        ⍝ Now, for each of those numbers
    ⍕         ⍝ turn it into a string
   ∘          ⍝ and
 1↓           ⍝ drop its first character.
∊             ⍝ Finally enlist the strings into a single string (as in, join them together)

Thanks @Bubbler for saving 7 bytes

my original 19 bytes

{,/{1↓⍕⍵}¨4+⎕UCS ⍵}

Try it online!

{                   } ⍝ Define a function taking a string as argument.
             ⎕UCS ⍵  ⍝ Convert the argument (string) into an array of codepoints.
           4+         ⍝ and add 4 to each of those codepoints.
   {     }¨           ⍝ For each number in the array,
      ⍕⍵             ⍝ convert it to a string
    1↓                ⍝ and drop the first character (the 1).
 ,/                   ⍝ Finally join everything and return.
\$\endgroup\$
3
  • \$\begingroup\$ 12 bytes. Check out the successive transformations to shorten the code. \$\endgroup\$
    – Bubbler
    Commented Mar 27, 2020 at 7:29
  • \$\begingroup\$ @Bubbler thanks for the step-by-step! I'll read what those glyphs you introduced do, and then update my answer! \$\endgroup\$
    – RGS
    Commented Mar 27, 2020 at 7:33
  • \$\begingroup\$ @Bubbler If I understand correctly, is acting as some sort of "flatten" right? Because I have a list of strings, i.e. a list of lists of characters, and then the enlist operator turns everything into a 1d array? \$\endgroup\$
    – RGS
    Commented Mar 27, 2020 at 19:33
3
\$\begingroup\$

Vyxal s, 6 bytes

C4+ƛSḢ

-1 byte thanks to @Steffan

Try it Online!

Explanation:

C       # Convert to ASCII codes
 4+     # Add 4
   ƛ    # On each number:
    S   #   Stringify
     Ḣ  #   Remove first char
\$\endgroup\$
2
  • \$\begingroup\$ Try it Online! for 6 bytes. \$\endgroup\$
    – naffetS
    Commented Jul 29, 2022 at 3:35
  • \$\begingroup\$ @Steffan Cool approach, thank you! \$\endgroup\$ Commented Jul 29, 2022 at 5:40
2
\$\begingroup\$

Vim, 60 keystrokes

:s/./\=char2nr(submatch(0))-96."\r"/g
:%s/\<\d\n/0&
V{gJ

An almost entirely regex based solution. As usual, using the eval register makes it obscenely long.

\$\endgroup\$
2
\$\begingroup\$

PHP, 58 Bytes

foreach(str_split($argv[1])as$c)printf("%02d",ord($c)%32);
\$\endgroup\$
1
  • \$\begingroup\$ you can -8 bytes iterating as a string 50 bytes TIO, or -11 bytes input via $argn 47 bytes TIO. \$\endgroup\$
    – 640KB
    Commented Aug 9, 2019 at 18:05
2
\$\begingroup\$

PowerShell v2+, 44 bytes

-join([char[]]$args[0]|%{"{0:D2}"-f($_%32)})

Takes input $args[0], casts it as a char-array, feeds into a loop. Each iteration, we take the current character $_ modulo 32, which implicitly casts as the ASCII value. Conveniently ;-), this lines up so a = 1, b = 2, etc. That fed into the -format operator, operating on string "{0:D2}", which specifies a two digit minimum (i.e., it prepends a leading zero if required). Those strings of digits are encapsulated in parens, -joined together into one string, and left on the pipeline. Output via implicit Write-Output happens at program conclusion.

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'hello'
0805121215

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'helloworld'
08051212152315181204

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'codegolf'
0315040507151206

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'johncena'
1015081403051401
\$\endgroup\$
2
\$\begingroup\$

Perl, 24 bytes

Includes +1 for -p

Give input on STDIN:

encode.pl <<< hello

encode.pl

#!/usr/bin/perl -p
s/./substr 4+ord$&,1/eg
\$\endgroup\$
5
  • \$\begingroup\$ Nicely done. I think you probably meant 4+ord$& instead of 5+ord$& though ;-) \$\endgroup\$
    – Dada
    Commented Oct 30, 2016 at 8:35
  • \$\begingroup\$ @Dada Right, pasted the version of my snippet buffer instead of the tested version again \$\endgroup\$
    – Ton Hospel
    Commented Oct 30, 2016 at 18:31
  • \$\begingroup\$ It happens! :) Could I ask you an unrelated question? Do you have any idea what is the 8 bytes perl solution to this question (reverse the input) (on anarchy) ? \$\endgroup\$
    – Dada
    Commented Oct 30, 2016 at 18:38
  • \$\begingroup\$ @Dada I'd say it is impossible in pure perl, so I expect it's some abuse of the automated system on that side. E.g. if input came from STDIN you could do exec rev \$\endgroup\$
    – Ton Hospel
    Commented Oct 31, 2016 at 7:12
  • \$\begingroup\$ Right, that makes sense, thanks! I was having a hard time figuring this out since print is 5 bytes, <> is 2 more, so I was wondering what was the 1 byte builtin to reverse I hadn't heard of! \$\endgroup\$
    – Dada
    Commented Oct 31, 2016 at 9:48
2
\$\begingroup\$

DASH, 27 bytes

@><""(->@rstr["."""]+4#0)#0

Example usage:

(@><""(->@rstr["."""]+4#0)#0)"helloworld"

Explanation

@ (                         #. take input through a lambda
  join "" (                 #. join with newlines the following:
    (map                    #. result of mapping
      @ (                   #. this lambda
        rstr ["." ; ""] (     #. replace first char w/ empty string:
          + 4 #0               #. mapped item's codepoint + 4
        )
      )
    ) #0                    #. over the argument
  )
)
\$\endgroup\$
2
\$\begingroup\$

Batch, 256 239 237 bytes

@echo off
set/ps=
set r=
set a=abcdefghijklmnopqrstuvwxyz
:g
set c=%a%
for /l %%i in (101,1,126)do call:l %%i
set s=%s:~1%
if not "%s%"=="" goto g
echo %r%
exit/b
:l
set i=%1
if %c:~,1%==%s:~,1% set r=%r%%i:~1%
set c=%c:~1%

Takes input on STDIN.

\$\endgroup\$
2
\$\begingroup\$

IBM PC DOS 8088 Assembly, 33 28 27 bytes

Assembled binary:

00000000: be82 00ac 2c60 7812 d40a 0530 3092 86f2  ....,`x....00...
00000010: b402 cd21 86f2 cd21 ebe9 c3              ...!...!...

Unassembled:

BE 0082     MOV  SI, 82H        ; point SI to command line string 
        CH_LOOP: 
AC          LODSB               ; load next char into AL
2C 60       SUB  AL, 'a'-1      ; convert ASCII to a=1,b=2...z=26 
78 12       JS   DONE           ; if char is terminator or not valid, exit
D4 0A       AAM                 ; convert binary to BCD 
05 3030     ADD  AX, '00'       ; convert BCD to ASCII 
92          XCHG DX, AX         ; save AX to DX for display 
86 F2       XCHG DH, DL         ; reverse bytes 
B4 02       MOV  AH, 2          ; DOS display char function 
CD 21       INT  21H            ; write first digit 
86 F2       XCHG DH, DL         ; reverse bytes back 
CD 21       INT  21H            ; write second digit 
EB E9       JMP  CH_LOOP        ; restart loop 
        DONE: 
C3          RET                 ; return to DOS

Standalone PC DOS executable. Input string from command line, output to console.

I/O:

enter image description here

\$\endgroup\$
2
\$\begingroup\$

BQN, 16 bytes

∾·(1↓•Fmt)¨4+-⟜@

Try it at BQN online!

Explanation

Same approach, independently derived, as RGS's APL answer and tybocopperkettle's Vyxal s answer.

∾·(1↓•Fmt)¨4+-⟜@
             -⟜@  Subtract null byte from each character, giving its ASCII value
           4+      Add 4 (a = 101, z = 126)
  (      )¨        Map this function to each number:
     •Fmt            Format as string
   1↓                Drop first character
∾·                Join together into a single string
\$\endgroup\$
2
\$\begingroup\$

K (ngn/k), 8 bytes

,/1_'$4+

Try it online!

4+ add 4 to (the ASCII codes of) the argument - this turns a into 101, b into 102, etc

$ format numbers as strings

1_' drop one digit from each

,/ concatenate

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Mind adding an explanation? \$\endgroup\$
    – Jonah
    Commented Jul 31, 2022 at 23:52
  • 1
    \$\begingroup\$ done ⁩⁩⁩⁩⁩⁩⁩⁩⁩ \$\endgroup\$
    – ngn
    Commented Aug 2, 2022 at 3:07
  • \$\begingroup\$ Oh that’s clever! \$\endgroup\$
    – Jonah
    Commented Aug 2, 2022 at 3:08
  • \$\begingroup\$ not much different from other array-lang solutions, to be honest \$\endgroup\$
    – ngn
    Commented Aug 2, 2022 at 3:10
  • \$\begingroup\$ Just saved me 7 bytes ¯\_(ツ)_/¯ \$\endgroup\$
    – Jonah
    Commented Aug 2, 2022 at 4:05
2
\$\begingroup\$

J, 25 22 15 bytes

[:,4}.@":@+3&u:

Try it online!

-7 bytes thanks to ngn's K approach

\$\endgroup\$
2
\$\begingroup\$

Knight, 45 41 bytes

-4 thanks Aiden

;=xP W<1Lx;O++*'0'-2L=a-Ax 96a'\'=xSxF1""

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Instead of A GxF1 you can simply do Ax, because ASCII already returns the ascii value of the first character in the string. \$\endgroup\$
    – Aiden Chow
    Commented Aug 14, 2022 at 23:11
  • \$\begingroup\$ Nice trick using SxF1 instead of Gx 1Lx \$\endgroup\$
    – naffetS
    Commented Aug 15, 2022 at 16:17
  • \$\begingroup\$ @Steffan SxF1"" and Gx 1Lx are the same bytecount and do the same thing, so it's just two different ways to do the same thing. \$\endgroup\$
    – Aiden Chow
    Commented Aug 15, 2022 at 17:04
  • \$\begingroup\$ Oh, for some reason I missed the "" lol \$\endgroup\$
    – naffetS
    Commented Aug 15, 2022 at 17:30
2
+100
\$\begingroup\$

Piet + ascii-piet, 44 bytes (2×22=44 codels)

tuuuumknnfbkqmkcalrmu_sajs?daltdddbfckkkkk ?

Try Piet online!

Input the string with the sentinel value _.

Pseudocode

while true:
  S = character input
  n = (codepoint of S) - 96
  if n+1 == 0:
    exit
  else:
    print(floor(n/10))
    print(n modulo 10)
\$\endgroup\$
1
\$\begingroup\$

MATL, 11 bytes

96-OH&YA!1e

Try it online!

         % Implicit input
96-      % Subtract 96. So 'a' becomes 1, 'b' becomes 2 etc
OH&YA    % Convert each number to 2 decimal digits. Gives a 2-column matrix
!1e      % Transpose and linearize into a row
         % Implicit display
\$\endgroup\$
1
\$\begingroup\$

Ruby, 53 46 bytes

->s{s.chars.map{|c|(c.ord-96).to_s.rjust(2,?0)}.join}

->s{s.chars.map{|c|(c.ord+4).to_s[1..2]}.join}

\$\endgroup\$
1
  • \$\begingroup\$ 41 bytes: ->s{s.chars.map{|c|"#{c.ord+4}"[1,2]}*''} \$\endgroup\$
    – Dingus
    Commented Apr 24, 2020 at 11:08

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.