26
\$\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\$

49 Answers 49

23
\$\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!

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

Python 2, 42 bytes

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

Test it on Ideone.

| improve this answer | |
\$\endgroup\$
  • 5
    \$\begingroup\$ Non recursive, same byte count: lambda s:''.join(`ord(x)+4`[1:]for x in s) \$\endgroup\$ – Jonathan Allan Oct 28 '16 at 18:00
8
\$\begingroup\$

C, 55 43 bytes

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

ideone

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ printf("%02d",*c++-96);} is shorter and valid if I'm not mistaken. \$\endgroup\$ – Dada Oct 28 '16 at 17:42
8
\$\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='')
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Good job on your first Pyth program! \$\endgroup\$ – HyperNeutrino Oct 28 '16 at 19:04
6
\$\begingroup\$

Python, 46 bytes

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

Pretty straightforward. Try it on repl.it!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Wow, two completely different attempts with the same byte count ;) \$\endgroup\$ – Kade Oct 28 '16 at 17:19
6
\$\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"
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I came up with O+4DḊ€FṾ€ for the same count, perhaps golfable \$\endgroup\$ – ETHproductions Oct 28 '16 at 17:39
  • \$\begingroup\$ @ETHproductions O+4Ṿ€Ḋ€ saves 2 bytes. \$\endgroup\$ – Dennis Oct 28 '16 at 17:40
  • \$\begingroup\$ @Dennis I just did the same (ish)... \$\endgroup\$ – Jonathan Allan Oct 28 '16 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=<<)
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You don't need the second set of parens. \$\endgroup\$ – xnor Oct 29 '16 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"
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 25 bytes (or 27 under the rules at the time of this challenge): Try it online! \$\endgroup\$ – Xcali Mar 26 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)
| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Java 7,60 bytes

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

MATL, 12 11 bytes

1 byte saved thanks to @Luis

4+!V4LZ)!le

Try it Online

| improve this answer | |
\$\endgroup\$
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.
| improve this answer | |
\$\endgroup\$
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.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

PHP, 58 Bytes

foreach(str_split($argv[1])as$c)printf("%02d",ord($c)%32);
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ you can -8 bytes iterating as a string 50 bytes TIO, or -11 bytes input via $argn 47 bytes TIO. \$\endgroup\$ – 640KB Aug 9 '19 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
| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Nicely done. I think you probably meant 4+ord$& instead of 5+ord$& though ;-) \$\endgroup\$ – Dada Oct 30 '16 at 8:35
  • \$\begingroup\$ @Dada Right, pasted the version of my snippet buffer instead of the tested version again \$\endgroup\$ – Ton Hospel Oct 30 '16 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 Oct 30 '16 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 Oct 31 '16 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 Oct 31 '16 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
  )
)
| improve this answer | |
\$\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.

| improve this answer | |
\$\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

| improve this answer | |
\$\endgroup\$
2
+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.
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 12 bytes. Check out the successive transformations to shorten the code. \$\endgroup\$ – Bubbler Mar 27 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 Mar 27 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 Mar 27 at 19:33
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
| improve this answer | |
\$\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}

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

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Billywob Oct 29 '16 at 10:26
  • \$\begingroup\$ @Billywob Thanks! For the padding, I tried using formatC earlier but that worked out as needing one more byte than the current approach. \$\endgroup\$ – rturnbull Oct 29 '16 at 14:27
1
\$\begingroup\$

Actually, 10 bytes

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

O4+`$pX`MΣ

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.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Google Sheets, 76 bytes

=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.

Example

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Groovy, 51 Bytes

{it.collect{(((int)it-96)+"").padLeft(2,"0")}.join()}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Labyrinth, 40 bytes

      ,")@
!{_10%! (
/       _
01_}:-69"
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Befunge-98, 19 bytes

#@~'`-:a/'0+,a%'0+,
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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