# Encode the alphabet cipher

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.

# 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!

• What does ¦ do again? – Magic Octopus Urn Oct 28 '16 at 17:33
• @carusocomputing Removes the first element of a string, list, etc. – Adnan Oct 28 '16 at 17:34
• Beyond genius... – Magic Octopus Urn Oct 28 '16 at 17:38

# Python 2, 42 bytes

f=lambda s:s andord(s)+4[1:]+f(s[1:])


Test it on Ideone.

• Non recursive, same byte count: lambda s:''.join(ord(x)+4[1:]for x in s) – Jonathan Allan Oct 28 '16 at 18:00

# C, 55 43 bytes

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


ideone

• printf("%02d",*c++-96);} is shorter and valid if I'm not mistaken. – Dada Oct 28 '16 at 17:42

# 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='')

• Good job on your first Pyth program! – HyperNeutrino Oct 28 '16 at 19:04

# Python, 46 bytes

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


Pretty straightforward. Try it on repl.it!

• Wow, two completely different attempts with the same byte count ;) – Kade Oct 28 '16 at 17:19

# 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"  • I came up with O+4DḊ€FṾ€ for the same count, perhaps golfable – ETHproductions Oct 28 '16 at 17:39 • @ETHproductions O+4Ṿ€Ḋ€ saves 2 bytes. – Dennis Oct 28 '16 at 17:40 • @Dennis I just did the same (ish)... – Jonathan Allan Oct 28 '16 at 17:41 # 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=<<)

• You don't need the second set of parens. – xnor Oct 29 '16 at 5:09

## 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"

• 25 bytes (or 27 under the rules at the time of this challenge): Try it online! – Xcali Mar 26 at 20:14

# 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,36)+91+f(s.slice(1))).slice(1)


# 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


# Java 7,60 bytes

void f(char[]s){for(int i:s)System.out.printf("%02d",i-96);}

• This answer might not be valid because it takes a char[] instead of a String. – HyperNeutrino Oct 28 '16 at 19:05
• – Martin Ender Oct 28 '16 at 19:23
• @MartinEnder Okay. Thank you for the clarification. This answer has my upvote. – HyperNeutrino Oct 28 '16 at 19:23

# MATL, 12 11 bytes

1 byte saved thanks to @Luis

4+!V4LZ)!le


Try it Online

# 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. # 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. # PHP, 58 Bytes foreach(str_split($argv)as$c)printf("%02d",ord($c)%32);

• you can -8 bytes iterating as a string 50 bytes TIO, or -11 bytes input via $argn 47 bytes TIO. – 640KB Aug 9 '19 at 18:05 ## PowerShell v2+, 44 bytes -join([char[]]$args|%{"{0:D2}"-f($_%32)})  Takes input $args, 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  # 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

• Nicely done. I think you probably meant 4+ord$& instead of 5+ord$& though ;-) – Dada Oct 30 '16 at 8:35
• @Dada Right, pasted the version of my snippet buffer instead of the tested version again – Ton Hospel Oct 30 '16 at 18:31
• 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) ? – Dada Oct 30 '16 at 18:38
• @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 – Ton Hospel Oct 31 '16 at 7:12
• 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! – Dada Oct 31 '16 at 9:48

# 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
)
)


## Batch, 256239 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.

# IBM PC DOS 8088 Assembly, 3328 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:


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

I/O: # 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.

• 12 bytes. Check out the successive transformations to shorten the code. – Bubbler Mar 27 at 7:29
• @Bubbler thanks for the step-by-step! I'll read what those glyphs you introduced do, and then update my answer! – RGS Mar 27 at 7:33
• @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? – RGS Mar 27 at 19:33

# 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


## 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}

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

# R, 71 51 bytes

Saved 20 bytes thanks to Billywob. Takes input from stdin and outputs to stdout.

cat(sprintf("%02d",utf8ToInt(scan(,""))-96),sep="")


Examples:

helloworld -> 08051212152315181204

codegolf -> 0315040507151206

alphabetcipher -> 0112160801020520030916080518

johncena -> 1015081403051401

• You can use utf8toInt(scan(,"))-96 instead of the whole match thing. Don't think there's a better way to handle the padding though. – Billywob Oct 29 '16 at 10:26
• @Billywob Thanks! For the padding, I tried using formatC earlier but that worked out as needing one more byte than the current approach. – rturnbull Oct 29 '16 at 14:27

# Actually, 10 bytes

Using the neat algorithm in Adnan's 05AB1E answer. Golfing suggestions welcome. Try it online!

O4+$pXMΣ  Ungolfing  Implicit input s. O ord() every char in s. 4+ Add 4 to every ord in s. ...M Map the following function over s. Variable m.$        Push str(m).
pX       Discard the first char of str(m).
Invariably this is a 1 and we get our ciphered m.
Σ        sum() everything to get one string.
Implicit return.


=ArrayFormula(Join(,Text(Code(Mid(A1,Row(Indirect("1:"&Len(A1))),1))-96,"00"


Sheets will automatically add three closing parentheses when you exit the cell.
Input is in cell A1

Indirect("1:"&Len(A1)) returns a range as tall as the input is long.
Row(Indirect(~)) returns the row numbers, so it's a list of numbers from 1 to the input length.
Mid(A1,Row(~),1) returns each character from the input, one at a time.
Code(Mid(~))-96 returns the ASCII code for each character, down-shifted so a = 1.
Text(Code(~),"00") pads the result above to two digits.
Join(,Text(~)) joins all those padded results without a delimiter.
ArrayFormula(Join(~)) makes all the stuff above operate on arrays. Without, the result would just be the first padded alphabet code: helloworld would return 08. # Groovy, 51 Bytes

{it.collect{(((int)it-96)+"").padLeft(2,"0")}.join()}


# Labyrinth, 40 bytes

      ,")@
!{_10%! (
/       _
01_}:-69"


# Befunge-98, 19 bytes

#@~'-:a/'0+,a%'0+,


# Groovy - 31 bytes

Groovy conversion of NumberKnot's solution in java:

{it.each{printf("%02d",it-96)}}

Example here using various options:

http://ideone.com/vd0dTX