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[0])+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

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

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

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"


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)


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[1])as$c)printf("%02d",ord($c)%32);


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


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.

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}

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.


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

IBM PC DOS 8088 Assembly, 33 32 bytes

be80 00ad 488b c832 edac 2c60 d40a 0530 308b d086 f2b4 02cd 2186 f2cd 21e2 eac3


Unassembled:

    MOV  SI, 80H            ; point SI to PSP
LODSW                   ; fetch length into AL, increment SI to 82H
DEC  AX                 ; remove leading space from string count
MOV  CX, AX             ; move to CX counter
XOR  CH, CH             ; clear CH
CH_LOOP:
LODSB                   ; load [SI] into AL
SUB   AL, 'a'-1         ; convert ASCII to a=1,b=2...z=26
AAM                     ; convert binary to BCD
ADD   AX, '00'          ; convert BCD to ASCII
MOV   DX, AX            ; save AX to DX for display
MOV   AH, 2             ; DOS display char function
XCHG  DH, DL            ; reverse bytes
INT   21H               ; write first digit
XCHG  DH, DL            ; reverse bytes back
INT   21H               ; write second digit
LOOP  CH_LOOP


This is a complete, runnable PC DOS COM program. Takes input string from command line.

I/O:

A>CIPH.COM helloworld
08051212152315181204

A>CIPH.COM codegolf
0315040507151206

A>CIPH.COM alphabetcipher
0112160801020520030916080518

A>CIPH.COM johncena
1015081403051401


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

Pyke, 7 bytes

F.oOOt


Try it here!

F       -  for i in input:
.o     -       ord(i)
OO   -      ^ + 4
  -     str(^)
t -    ^[1:]
- sum(^)


C#, 54 bytes

s=>String.Join("",s.Select(n=>(n<106?"0":"")+(n-96)));
`