title: Implement a One-Time Pad

text:
# Question
Title: Implement a One-Time Pad
## Background

A one-time pad is a form of encryption that has been proven impossible to crack if used properly.

Encryption is performed by taking a plaintext (comprised of only letters A-Z) and generating a random string on the same length (also only letters). This string acts as the key. Each character in the plaintext is then paired up with the corresponding character in the key. The ciphertext is computed as follows: For each pair, both characters are converted to numbers (A=0, B=1, ... Z=25). The two numbers are added modulo 26. This number is the converted back into a character.

Decryption is exactly the opposite. The characters in the ciphertext and key are paired up and converted to numbers. The key is then subtracted from the ciphertext modulo 26, and the result is converted back into a character A-Z.

## The Challenge

Your challenge is to write the shortest program possible that can both encrypt and decrypt a one-time pad.

On the first line of input (to STDIN), there will be either the word "ENCRYPT" or the word "DECRYPT".

If the word is encrypt, then the next line will be the plaintext. Your program should output two lines (to STDOUT), the first being the key, and the second being the ciphertext.

If the word is decrypt, your program will get two more line of input. The first line will be the key, and the second line will be the ciphertext. You program should output one line, which will be the plaintext that has been decrypted.

The plaintext, ciphertext, and key should always consist of uppercase letters A-Z. They will always be a single line and contain no whitespace.

The key should always be random. No large parts of it should repeat between runs, and there should be no patterns that can be found in the text.

Two simple examples:

```
ENCRYPT
HAPPYBIRTHDAY
>ABKJAQLRJESMG
>HBZYYRTICLVME

DECRYPT
ABKJAQLRJESMG
HBZYYRTICLVME
>HAPPYBIRTHDAY

```

The `>` represents which lines are output, so you don't have to print that symbol as output.

# Answer
> 8 votes
## GolfScript, 53 chars

```
n%(0=2%{~.,[{26rand 65+}*]:K]}*zip{{-}*~)26%65+}%K]n*

```

This is a task for which GolfScript seems just about perfectly suited.

To keep the code short, I'm using the same code for both encryption and decryption: to decrypt, I subtract the key from the ciphertext, while for encryption, I first generate a random ciphertext and then subtract the plaintext from it. Even so, the extra code for implementing encryption mode takes just a little over half the length of the program.

De-golfed version with comments:

```
n %             # split input into an array of lines

# KEY GENERATION FOR ENCRYPTION MODE:
(               # extract the first line from the array
0 = 2 %         # check if the first char of that line is odd (E = 69)...
{               # ...and execute this block if it is:
    ~           # dump the remaining lines (of which the should be only one) on the stack
    . ,         # calculate the length of the last line...
    [ { 26 rand 65 + } * ]  # ...make an array of that many random letters...
    :K          # ...and assign it to K
    ]           # collect all the lines, including K, back into an array
} *

# ENCRYPTION / DECRYPTION ROUTINE:
zip             # transpose the array of 2 n-char strings into n 2-char strings...
{               # ...and execute this block for each 2-char string:
    {-} *       # subtract the second char code from the first
    ~ )         # negate the result (using the two's complement trick -x = ~x+1)
    26 % 65 +   # reduce modulo 26 and add 65 = A
} %

# OUTPUT:
K ] n*         # join the result and K (if defined) with a newline, stringifying them

```

# Answer
> 4 votes
# Ruby (200 185)

sample runs + wc:

```
$ ruby onetimepad.rb
ENCODE
ANOTHERTESTINPUTZZZ
ZYCLGHDWLDASFUTHWKC
BPMIBXOXTPTQIVBMDPX
$ ruby onetimepad.rb
DECODE
ZYCLGHDWLDASFUTHWKC
BPMIBXOXTPTQIVBMDPX
ANOTHERTESTINPUTZZZ
$ wc onetimepad.rb
       4       7     185 onetimepad.rb

```

```
def f;gets.scan(/./).map{|b|b.ord-65};end
s=->a{a.map{|b|(b+65).chr}*''}
r=->b,a,o{s[a.zip(b).map{|a,b|(a.send o,b)%26}]}
puts(gets=~/^D/?r[f,f,:+]:[s[k=(p=f).map{rand 26}],r[k,p,:-]])

```

# Answer
> 4 votes
# APL (Dyalog Unicode), 46 bytes

```
⎕A[26|{'N'∊⍞:⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞⋄-⌿⎕A⍳↑⍞⍞}1]

```

Try it online!

The current full program is the result of a 2hr long session at The APL Orchard., with a lot of golfing input from Adám (-13 bytes!).

Requires `⎕IO←0` (0-indexing).

## Explanation

```
⎕A[26|{'N'∊⍞:⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞⋄-⌿⎕A⍳↑⍞⍞}1]
      {                                    }1  inner fn(called with junk param)
           ⍞                                   first input
       'N'∊                                    is 'N' present in it?
            :⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞             if so, eNcrypt:
                               w←⍞              store message in w
                          26?⍨⍴                 generate 26 random numbers,
                        x←                      store in x
                 (⎕A⍳w)+                        add that to the indices in the alphabet
                ⍪                               table them
              x,                                join with the random numbers
             ⍉                                  transpose to get key and encrypted value
                                  ⋄-⌿⎕A⍳↑⍞⍞    else, decrypt:
                                         ⍞⍞     input key and value
                                        ↑       convert to matrix
                                     ⎕A⍳        get the indices of both in the alphabet
                                   -⌿           difference of all columns
   26|                                          mod the result of the inner fn.
  [                                          ] index the result of the program in
⎕A                                             the capitalized alphabet.

```

# Answer
> 3 votes
## Haskell, 203 characters

```
import Random
main=newStdGen>>=interact.(unlines.).(.lines).f.randomRs('A','Z')
f k['E':_,x]=[z const k x,z(e(+))k x]
f _[_,k,x]=[z(e(-))k x]
e(%)k x=toEnum$65+o x%o k`mod`26
o c=fromEnum c-65;z=zipWith

```

**Example:**

```
$ runghc OneTimePad.hs <<< $'ENCRYPT\nHELLOWORLD'
QMNQKGFZFD
XQYBYCTQQG
$ runghc OneTimePad.hs <<< $'DECRYPT\nQMNQKGFZFD\nXQYBYCTQQG'
HELLOWORLD

```

# Answer
> 3 votes
# Perl, 220 171 characters

```
if(<>=~/D/){$_=<>;$w=<>;print chr((ord(substr$w,$i++,1)-ord$1)%26+65)while/(.)/g}else{$_=<>;$c.=chr((ord($1)-65+($i=rand(26)))%26+65),print chr$i+65while/(.)/g;print$/.$c}

```

Sample Run:

```
ENCRYPT
HELLO
CCTKK
JGEVY

DECRYPT
CCTKK
JGEVY
HELLO

```

Note: at least when I run it, "Press any key to continue..." is appended to the end of the last output. I hope this is ok, because it isn't part of the program. If not, I can make it so it appears on the next line.

This is my first real program in Perl, and my first golf ever, so I would really appreciate tips. Also, I found `/(.)/g` on the internet, but I have no idea how it works (is it a regular expression? I haven't learnt those yet). Can somebody explain it to me?

EDIT: Thanks to Ilmari Karonen for helping me out with the regexps, I used my new knowledge to save 7 characters!

Expanded, slightly legible version:

```
if(<>=~/D/){
    $_=<>;
    $w=<>;
    print chr((ord(substr$w,$i++,1)-ord$1)%26+65)while/(.)/g
}
else{
    $_=<>;
    $c.=chr((ord($1)-65+($i=rand(26)))%26+65),print chr$i+65while/(.)/g;
    print$/.$c
}

```

# Answer
> 2 votes
# Python - 304 295

```
import random
r=raw_input
R=lambda s:range(len(s))
o=lambda c:ord(c)-65
j=''.join
if r()[0]=='D':
 s=r()
 d=r()
 print j(chr((o(s[i])-o(d[i]))%26+65)for i in R(s))
else:
 s=r()
 d=[random.randint(0,26)for i in R(s)]
 print j(chr((o(s[i])+d[i])%26+65)for i in R(s))
 print j(chr(n+65)for n in d)

```

I believe that this meets the specs exactly (Including the `'>'` at the start of the input prompts.) It does not validate input, so I think that it will just produce garbage output if you give it characters outside of `[A-Z]`. It also only checks the first letter of the input command. Anything starting with `D` will result in a decryption and anything else at all will result in an encryption.

# Answer
> 1 votes
## C++ - 220 241 chars, 4 lines

```
#include<cstdlib>
#include<cstdio>
#define a scanf("%s"
char i,s[99],t[99];int main(){a,t);a,s);if(t[0]>68){for(;s[i];++i)s[i]=(s[i]+(t[i]=rand()%26+65))%26+65;puts(t);}else for(a,t);s[i];++i){s[i]=65+t[i]-s[i];if(s[i]<65)s[i]+=26;}puts(s);}

```

Edit 1- The MSVS standard library seems to include a lot of unnecessary files which meant that ios had all the includes that I needed but this didn't work with other compilers. Changed ios for the actual files that the functions needed appear in cstdlib and cstdio. Thanks to Ilmari Karonen for pointing this out.

# Answer
> 1 votes
## Python - 270

```
import random
i=raw_input
m=i()
a=i()
r=range(len(a))
o=ord
j=''.join
if m=='ENCRYPT':
  k=j(chr(65+random.randint(0,25)) for x in r)
  R=k+"\n"+j(chr((o(a[x])+o(k[x]))%26+65) for x in r)
elif m=='DECRYPT':
  k=i()
  R=j(chr((o(k[x])-o(a[x]))%26+65) for x in r)
print R

```

Sample output:

```
$ python onetimepad.py
ENCRYPT
HELLOWORLD
UXCYNPXNNV
BBNJBLLEYY
$ python onetimepad.py
DECRYPT
UXCYNPXNNV
BBNJBLLEYY
HELLOWORLD

```

Character count:

```
$ wc -c onetimepad.py
270 onetimepad.py

```

# Answer
> 1 votes
# J : 94 bytes

```
3 :0]1
c=:(26&|@)(&.(65-~a.&i.))
r=:1!:1@1:
((],:+c)[:u:65+[:?26$~#)@r`(r-c r)@.('D'={.)r 1
)

```

All necessary white space counted.

Commented version:

```
3 :0]1                                          NB. Make a function and call it
c=:(26&|@)(&.(65-~a.&i.))                       NB. Adverb for operating on the alphabet
                                                NB. (used for adding and subtracting the pad)
r=:1!:1@1:                                      NB. Read input line and decide (right to left)
((],:+c)[:u:65+[:?26$~#)@r   ` (r-c r)            @. ('D'={.)r 1
NB. Encryption (ger    0)    | Decryption (ger 1)| Agenda
NB. pad,:(crypt=:plain + pad)| crypt - pad       | If D is first input, do (ger 1), else do (ger 0)
)

```

# Answer
> 1 votes
# C# (445 416)

Forgot about Aggregate. Cut off a good bit.

Somewhat golfed:

```
namespace G {
using System;
using System.Linq;
using x = System.Console;
class P {
    static void Main() {
        string p = "", c = "", k = "";
        Random r = new Random();
        int i = 0;
        if (x.ReadLine()[0] == 'E') {
            p = x.ReadLine();
            k=p.Aggregate(k,(l,_)=>l+(char)r.Next(65,90));
            c=p.Aggregate(c,(m,l)=>m+(char)((l+k[i++])%26+65));
            x.WriteLine(k + "\n" + c);
        } else {
            k = x.ReadLine();
            c = x.ReadLine();
            p=c.Aggregate(p,(l,a)=>l+(char)((a-k[i++]+26)%26+65));
            x.WriteLine(p);
        }
    }
}

```

}

Golfed:

```
namespace G{using System;using System.Linq;using x=System.Console;class P{static void Main(){string p="",c="",k="";Random r=new Random();int i=0;if (x.ReadLine()[0]=='E'){p=x.ReadLine();k=p.Aggregate(k,(l,_)=>l+(char)r.Next(65,90));c=p.Aggregate(c,(m,l)=>m+(char)((l+k[i++])%26+65));x.WriteLine(k+"\n"+c);}else{k=x.ReadLine();c=x.ReadLine();p=c.Aggregate(p,(l,a)=>l+(char)((a-k[i++]+26)%26+65));x.WriteLine(p);}}}}

```

# Answer
> 1 votes
# JavaScript 239

```
var F=String.fromCharCode
function R(l){var k='';while(l--)k+=F(~~(Math.random()*26)+65);return k}
function X(s,k,d){var o='',i=0,a,b,c
while(i<s.length)a=s.charCodeAt(i)-65,b=k.charCodeAt(i++)-65,c=d?26+(a-b):a+b,o+=F((c%26)+65)
return o}

```

Usage:

```
var str = "HELLOWORLD";
var key = R(str.length);
var enc = X(str, key, false);
console.log(enc);
console.log(X(enc,key, true));

```

# Answer
> 0 votes
# Ruby - 184 179 177 chars

```
def g;gets.scan(/./).map{|c|c.ord-65}end
m,=g
k=(s=g).map{rand 26}
m==4?(puts k.map{|c|(c+65).chr}*'';y=:+):(k,s=s,g)
puts s.zip(k).map{|c,o|(c.send(y||:-,o).to_i%26+65).chr}*''

```

Run it like this: `$ ruby pad-lock.rb`

Here is the ungolfed version if anyone is interested (it's not quite up to date with the golfed one though)

```
def prompt
    gets.scan(/./).map{ |c|c.ord - 65 }
end

mode = prompt[0]
operator = :-
secret = prompt
key = secret.map { |char| rand(26) }

if mode == 4 # the letter E, or ENCRYPT
    key.map { |char| print (char + 65).chr }
    puts
    operator = :+
else
    # make the old secret the new key,
    # and get a new secret (that has been encrypted)
    key, secret = secret, prompt
end

chars = secret.zip(key).map do |secret_char, key_char|

    # if mode == 4 (E) then add, otherwise subtract
    i = secret_char.send(operator, key_char).to_i

    ((i % 26) + 65).chr
end

puts chars.join("")

```

# Answer
> 0 votes
# C (159 + 11 for compiler flags)

Golfed:

```
d(a,b){return(a+b+26)%26+65;}a;char s[999],b,*c=s-1;main(){g;a=*s-69;g;while(*++c)a?b=-*c,*c=getchar():putchar(b=rand()%26+65),*c=d(*c,b);a||puts("");puts(s);}

```

Ungolfed:

```
d(a,b){
    //*a = (*a + b - 2*65 + 26) % 26 + 65;
    return (a + b + 26) % 26 + 65;
}
a; char s[999], b, *c = s-1;
main(){
    gets(s);
    a = *s - 69; // -1 if decrypt 0 if encrypt
    gets(s);
    while(*++c){
        if(!a)
            putchar(b = rand() % 26 + 65); // 'A'
        else
            b = -*c, *c = getchar();
        *c = d(*c,b);
    }
    if(!a) puts("");
    puts(s);
}

```

Compile with `-Dg=gets(s)`.

Example:

```
$./onetimepad
ENCRYPT
FOOBAR
>PHQGHU
>UVEHHL
$./onetimepad
DECRYPT
PHQGHU
UVEHHL
>FOOBAR

```

---
Tags: code-golf, cryptography
---


title: The Decryption Function

text:
# Question
Title: The Decryption Function
You must write a program that takes an encrypted string and decrypt it according to specific rules and then print it out. Decryption will occur by performing two operations.

**Sample Input Argument 1** (the encrypted string)

```
HGJILKBADCFE

```

**Operation 1:**

Swap the first half of the string with the second half, which should leave you with:

```
BADCFEHGJILK

```

**Operation 2:**

Swap every two characters with each other such as swapping character 1 with 2, 3 with 4, etc., which should leave you with the decrypted string:

```
ABCDEFGHIJKL

```

**Guidelines:**

* Input Argument 1 will contain only uppercase letters
* Input Argument 1's length will be between 2 and 100 characters
* Input Argument 1's length will always be an even number
* Preferably the input will be taken from the command line (like below).
* Another Test Case `MPORQTSVUXWZYBADCFEHGJILKN` is the input, Output is `ABCDEFGHIJKLMNOPQRSTUVWXYZ`

**My Attempt**

```
import sys
_,a=sys.argv
b=len(a)//2
s=a[b:]+a[:b]
print(''.join(x+y for x,y in zip(s[1::2],s[::2])))

```

# Answer
# Ruby `-p`, <sup>~~48~~</sup> 47 bytes

```
$_=$_[l= ~/$//2,l]+$_[0,l];gsub /(.)(.)/,'\2\1'

```

Try it online!

Operation 1 is handled by splitting `$_` (the predefined global variable that contains the input) into two substrings of equal length; `~/$/` gives the length of the input. Then `gsub /(.)(.)/,'\2\1'` completes Operation 2 by swapping each pair of characters. (With the `-p` flag, `gsub` without a receiver implicitly acts on `$_`.)
> 5 votes

# Answer
# , 15 bytes

```
[:,_2|.\-:@#|.]

```

Try it online!

Straightforward implementation of the formula.

---

Slightly more interesting (not helpful for J golfing, but maybe for another lang) is that the algorithm can be solved with a scan sum:

1. First take a `1` followed by `-1 3`, with `-1 3` repeated up to the length of the list.
2. Scan sum that list.
3. Rotate the numbers half the list length.
4. Sort the original according those numbers.

See the TIO for a demo in J.
> 5 votes

# Answer
# 05AB1E, ~~13~~ 12 bytes

```
D2äRJ2ι`s.ιJ

```

Try it online!

*-1 thanks to a golfing tip by @Kevin I saw on another answer*

## Explained

```
D2äRJ2ι`s.ιJ

```
* Duplicate the input (`D`)
* Split it into 2 chunks ()
* Reverse the list and join it into a single string (`RJ`)
* Uninterleave that string on every second character ()
* Push all items from the uninterleaved string onto the stack (\`\`\`)
* Interleave those items ()
* And join the resulting list (`J`)
> 5 votes

# Answer
# APL+WIN, ~~24~~ 22 bytes

-2 bytes thanks to Jo King

Prompts for input of string:

```
,⌽n⍴⊖(⌽n←⌽2,.5×⍴s)⍴s←⎕

```

Try it online! Courtesy of Dyalog Classic
> 5 votes

# Answer
# , ~~78~~ ~~80~~ 79 bytes

*Edit: +2 bytes thanks to Dingus for bug-spotting, and -1 byte thanks to pajonk*

```
n=nchar(s<-scan(,''));o=1:n;cat(substring(s,p<-(o+n/2-2+2*o%%2)%%n+1,p),sep='')

```

Try it online!

Input given through R console (which could be considered the 'command line' for the R workspace).
R can also be invoked from a (non-R) shell, using the `Rscript` helper front-end, which would allow command-line arguments to directly follow the call, in which case a modified program could be 87 bytes and called using `Rscript decrypt.r HGJILKBADCFE`.

Calculates positions of decoded letters, and then outputs rearranged string.

Commented:

```
 n=nchar(                   # n = number of characters in...
         s<-scan(,''));     # s = the input.
 o=1:n;                     # o = sequence from 1 to n
 p=                         # p = positions of decoded characters:
   (o+n/2-1                 #   - reverse the first & second halves of o
                            #     by adding n/2-1
                            #     (will be fixed with final modulo below)
         +2*o%%2-1)         #   - then add 2 at every odd position
                            #     and subtract 1 from all, so in effect
                            #     adding to odds & subtracting from evens
                   %%n      #   - all modulo n
                      +1    #   - add 1 to get 1-based indices
 cat(                       # output:
   substring(s,p,p),sep='') #   characters of s from positions p to p

```
> 5 votes

# Answer
# Jelly, 7 bytes

```
ŒHṚFs2U

```

Try it online!

Equivalently 7 bytes, `ṙLH$s2U`.

## Explanation

```
ŒHṚFs2U  Main Link
ŒH       Split into two halves of similar length
  Ṛ      Reverse the order (swap the two halves)
   F     Flatten back into a single string
    s2   Slice into chunks of length 2
      U  Reverse each chunk
         Output is implicitly as one string

```

The other one otates it by `$`(`H`alf of the string's `L`ength) and then does the same thing for the second part of the challenge.
> 3 votes

# Answer
# Python 3, 75 bytes

Exactly as asked: input from command line, output to STDOUT.

```
import sys
_,s=sys.argv
i=1
while s[i:]:print(end=s[i-len(s)//2]);i+=3|i%-2

```

Try it online!

---

## Python 2, 52 bytes

If we can use a function:

```
f=lambda s,i=1:s[i:]and s[i-len(s)/2]+f(s,i+3-i%2*4)

```

Try it online!

---

The idea of all of these is that the index of the \\$i\\$'th output character in a string of length \\$n\\$ is:

$$ i - \frac{n}{2} + (-1)^i $$

Subject to the usual Python indexing semantics. If we rewrite this in an iterative fashion, then the \\$i\\$'th output character is:

$$ a\_i - \frac{n}{2} \text{ where } a\_0 = 1 \text{ and } a\_i = a\_{i-1} + 3 - 4(i\\%2) $$

Shorter with certain precedence is:

$$ a\_i - \frac{n}{2} \text{ where } a\_0 = 1 \text{ and } a\_i = a\_{i-1} + 3|(i\\%-2) $$
> 3 votes

# Answer
# Python 2, 50 bytes

```
f=lambda s,i=0:s[i:]and s[(i^1)-len(s)/2]+f(s,i+1)

```

Try it online!

Borrowing ideas from Sisyphus, the `i`'th character of the output is the character at index `(i^1)-len(s)/2` of the input. Here, `i^1` is XOR with `1`, which flips the last bit and so swaps even/odd pairs `0<->1`, `2<->3`, `4<->5`, ...

Here's a non-recursive alternative for the same length, though it outputs a list of characters which I'm not sure is allowed.

```
lambda s:[s[(i^1)-len(s)/2]for i in range(len(s))]

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~73~~ ~~72~~ 70 bytes

Saved 2 bytes thanks to Dominic van Essen!!!

```
i;l;f(char*s){for(i=1;(l=strlen(s))/i;)putchar(s[(i+l/2-++i%2*2)%l]);}

```

Try it online!

Inputs a string and outputs the decryption.

### Explanation

Maps the index (starting at \\$0\\$ to the end), of the input string, \\$s\\$ of length \\$l\\$, to the correct place by shifting it over \\$\frac{l}{2}+1\\$ places and then back \\$2\\$ for odd indices. Using this \\$\mod{l}\\$ gives the correct index of \\$s\\$ for the next output character.
> 3 votes

# Answer
# JavaScript (Node.js), 71 65 bytes

```
s=>(s.slice(l=s.length/2)+s.slice(0,l)).replace(/(.)(.)/g,'$2$1')

```

Try it online!

Saved 6 bytes thanks to @Shaggy.

Original 71 byte solution:

```
s=>(l=>s.slice(l)+s.slice(0,l))(s.length/2).replace(/(\w)(\w)/g,'$2$1')

```

Pretty simple stuff here - I used an inner function because I had to surround the `slice` calls anyway - this saves 4 bytes.
> 3 votes

# Answer
# Brachylog, 8 bytes

```
ḍ↔cġ₂↔ᵐc

```

Try it online!

### How it works

```
ḍ↔cġ₂↔ᵐc
ḍ        split in two halves
 ↔       reverse
  c      join
   ġ₂    group with length two
     ↔ᵐ  reverse each
       c join

```
> 2 votes

# Answer
# Python 3, 91 bytes

```
a=input();x=len(a)//2;b=a[x:]+a[:x];c=''
for i in range(0,len(b),2):c+=b[i+1]+b[i]
print(c)

```

Try it online!
> 1 votes

# Answer
# Pip, 21 bytes

```
RV_M(JRV(a<>#a/2)<>2)

```

Try it online!

## Explanation

```
RV_M(JRV(a<>#a/2)<>2)
        (a<>#a/2)     split input into parts of size length/2
     JRV              reverse the list, and join it to string
                 <>2  split the joined string into parts of size 2
RV_M                  reverse each of those parts
                      implicit output

```
> 1 votes

# Answer
# C (gcc), ~~78~~ ~~76~~ ~~78~~ 74 bytes

Thanks to ceilingcat for the -4!

Edit: Reverted to use addition instead of OR to avoid operator precedence issues.

Rather than splitting the string, the function starts at the middle of the string and wraps around the entire string has been processed. To flip every other character, the index inverts the 1s position of the counter.

```
f(s,i,j)char*s;{for(i=strlen(s),j=0;write(1,s+(i/2+j++/2*2+j%2)%i,j<i););}

```

Try it online!

If the program absolutely must take from the command line: 82 bytes

```
main(i,s,j)char**s;{for(i=strlen(*++s),j=0;write(1,*s+(i/2+j++/2*2+j%2)%i,j<i););}

```

Try it online!
> 1 votes

# Answer
# Stax, 10 bytes

```
ü♠yαæ♠╟«ºñ

```

Run and debug it

What a wonderful online interpreter.

Link is to unpacked version of code.

## Explanation

```
;%h/r$2/Frp
;           copy input
 %          get it's length
  h         halve it
   /        split input into parts of that size
    r       reverse
     $      join to string
      2/    split into parts of size 2
        F   for each element in the resulting array:
         rp reverse, and print without newline.

```
> 1 votes

# Answer
# K (ngn/k), 17 bytes

```
,/|'0N 2#,/|2 0N#

```

Try it online!
> 1 votes

# Answer
# Factor, 89 bytes

```
: d ( s -- s ) halves swap [ >array ] bi@ append 2 group [ reverse ] map concat >string ;

```

Try it online!
> 1 votes

# Answer
# , ~~64~~ 63 bytes

```
m=matrix;intToUtf8(m(m(utf8ToInt(scan(,"")),,2)[,2:1],2)[2:1,])

```

Try it online!

Took a different approach than Dominic van Essen, who golfed down a byte. Uses matrix reshaping/indexing to do the reversing.

Ungolfed:

```
s <- utf8ToInt(scan(,""))		# read input and convert to a list of byte values
m <- matrix(s,,2)			# convert to a Nx2 matrix, filling down by columns
m <- m[,2:1]				# reverse the columns of the matrix (flip the halves)
m <- matrix(m,2)			# convert to an Nx2 matrix, filling down by the columns
m <- m[2:1,]				# reverse the rows (swap adjacent characters)
intToUtf8(m)				# convert back to string

```
> 1 votes

# Answer
# bash+sed, 57 bytes

Takes input as a command line argument.

```
<<<"${1:${#1}/2}${1:0:${#1}/2}" sed 's/\(.\)\(.\)/\2\1/g'

```

Try it online!
> 1 votes

# Answer
# Burlesque, 17 bytes

```
iRsa2./!!2co)<-++

```

Try it online!

Description:

```
iR               # Generate all rotations of the input string
  sa             # Duplicate and get length (which equals string length)
    2./          # Divide by two
       !!        # And grab the string that's been rotated that many times
         2co     # Split the rotated string into chunks of two
            <-   # Reverse each chunk
              ++ # Join together and implicitly output

```
> 0 votes

# Answer
# Japt `-P`, 9 bytes

```
éUÊz)ò mw

```

Try it

```
éUÊz)ò mw     :Implicit input of string U
é             :Rotate right by
 UÊ           :  Length of U
   z          :  Floor divided by 2
    )         :End rotate
     ò        :Partitions of length 2
       m      :Map
        w     :  Reverse
              :Implicitly join and output

```
> 0 votes

# Answer
# Charcoal, 13 bytes

```
⭆⪪⪫⮌⪪θ⊘Ｌθω²⮌ι

```

Try it online! Link is to verbose version of code. Explanation:

```
        θ       Input string
       Ｌ        Length
      ⊘         Halved
    ⪪θ          Split input string into substrings of this length
   ⮌            Reverse
  ⪫      ω      Join together
 ⪪        ²     Split into substrings of length 2
⭆               Map over substrings and join
            ι   Current substring
           ⮌    Reversed
                Implicitly print

```
> 0 votes

# Answer
# Retina 0.8.2, 36 bytes

```
((.)+?)((?<-2>.)+)$
$3$1
(.)(.)
$2$1

```

Try it online! Explanation: The first stage uses a .NET balancing group to match as few characters as possible into `$1` while still matching the same number of characters into `$3`. `$#2` increments for each character matched into `$1` and decrements for each character matched into `$3` but it cannot decrement below zero, so `$1` is forced to consume the first half of the string to allow the end of the string to be reached. The second stage then flips pairs of adjacent characters. (Also ASCII art bewbs.)
> 0 votes

# Answer
# MathGolf, 10 bytes

```
h½/xy2/mx~

```

Try it online.

**Explanation:**

```
h           # Get the length of the (implicit) input-string (without popping)
            #  i.e. "HGJILKBADCFE" → "HGJILKBADCFE" and 12
 ½          # Halve this length
            #  → "HGJILKBADCFE" and 6
  /         # Split the string into parts of that size
            #  → ["HGJILK","BADCFE"]
   x        # Reverse this pair
            #  → ["BADCFE","HGJILK"]
    y       # Join it back together to a string
            #  → "BADCFEHGJILK"
     2/     # Split it into parts of size 2
            #  → ["BA","DC","FE","HG","JI","LK"]
       m    # Map over each pair:
        x   #  Reverse the pair
            #  → ["AB","CD","EF","GH","IJ","KL"]
         ~  # Pop and push all strings separated to the stack
            #  → "AB", "CD", "EF", "GH", "IJ", and "KL"
            # (after which the entire stack joined together is output implicitly)
            #  → "ABCDEFGHIJKL"

```
> 0 votes

# Answer
# Red, 89 bytes

```
func[s][move/part s tail s(length? s)/ 2
rejoin collect[foreach[b a]s[keep rejoin[a b]]]]

```

Try it online!
> 0 votes

# Answer
# Lua, 67 bytes

```
a=...b=#a//2print(((a:sub(b+1)..a:sub(1,b)):gsub('(.)(.)','%2%1')))

```

Try it online!

First, string is cut in two using `sub` functions and then concatenated back in reverse order. Then, `gsub` is used to swap pairs of characters.
> 0 votes

# Answer
# Wolfram Language (Mathematica), ~~64~~ 51 bytes

```
#[[#+UnitStep@#&@Array[#+(-1)^#&,L=Tr[1^#],-L/2]]]&

```

Try it online!

Port of Sisyphus's Python solution
> 0 votes

# Answer
# CJam, 13 bytes

```
q2/::\_,2//:\

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-pF`, 40 bytes

```
for$p("."x(@F/2),"."){s/($p)($p)/$2$1/g}

```

Try it online!
> 0 votes

# Answer
# Poetic, 472 bytes

```
DECODING THINGS:A BRIEFING
o,o,hello!i am agent Q
nah,Q`s chosen by an infamous phoney
a misprint!oh,sorry!am i sorry
i am agent J.W,tech/A.I hacker
i see a piece o code,i am trying at a means on how i decode it
what i am doing:i am laying all A-Z clearly along a pathway
midway,put in zeros(O,O)cause J.W needs it to split em
i shift em in tandem,i get B,A
lastly,if it leaves you a letter,it is moved
o,then i am doing A-Z again,it is taken to a shift
ah ha!spying is EZ

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: How happy is this emoticon? (2.0)

text:
# Question
Title: How happy is this emoticon? (2.0)
OG post

# Task

In this challenge, you will be given an string emoticon, and your task will be to output its happiness.

## How?

An emoticon will always have eyes and mouth. It can also include eyebrows and nose. Each part will influence the overall happiness rating, which is the sum of happiness ratings of all parts. Emoticons may be flipped, reversing the order of parts. Here is the different possible parts and their happiness rating:

```
Symbol    Flipped symbol    Happiness rating

Eyebrows:

<None>    <None>            0
<         >                -2
[         ]                -1
|         |                 0
]         [                 1
>         <                 2

Eyes:

:         :                 0
;         ;                 1

Noses:

^         ^                 0
-         -                 0

Mouth

<         >                -3
(         )                -2
[         ]                -1
|         |                 0
]         [                 1
)         (                 2
>         <                 3

```

## Test cases:

```
In        Out

:)        2
<:(      -4
|:-|      0
>;^)      5
(;        3
>-:<     -1
(:|       2

```

## Rules

1. You must be able to handle flipped emoticons. If the input can be interpreted both ways (for example \<:\<) you can output either of the possible results
2. Standard loopholes and I/O rules apply.
3. This is code-golf, so shortest code wins.

# Answer
# 05AB1E, ~~60~~ 59 bytes

```
„:;S¡D€gÆI„()SkàĀ-dUv">)]|"')NXQ×K©.ºDysÃk®g<-X·<*yĀ*}I';åO

```

Try it online or verify all test cases.

**Explanation:**

```
„:;S              # Push string ":;", and convert it to a list of characters: [":",";"]
    ¡             # Split the (implicit) input-string on these characters
     D            # Duplicate the pair
      €g          # Get the length of each part
        Æ         # Reduce by subtracting
I                 # Push the input again
 „()S             # Push string "()", and convert it to a list of characters: ["(",")"]
     k            # Get the 0-based index of these characters in the string
                  # (or -1 if it isn't present)
      à           # Pop and push the maximum
       Ā          # Check that this is NOT 0 (0 if 0; 1 if -1, 1, 2, or 3)
-                 # Subtract the two from one another
 d                # Check that this is non-negative (>=0)
  U               # And pop and store this result in variable `X`
                  # (X=1 for faces where the mouth is left; X=0 for faces where the
                  # mouth is right or where we couldn't determine mouth/eyebrows)
v                 # Loop over the parts `y` in the pair we duplicated after the split:
 ">)]|"           #  Push string ">)]|"
         N        #  Push the 0-based loop-index
          XQ      #  Check if it's equal to variable `X` (1 if N==X, 0 if N!=X)
       ')   ×    '#  Repeat ")" that many times (")" if N==X, "" if N!=X)
             K    #  Remove that from string ">)]|"
              ©   #  Store this string in variable `®` (without popping)
               .º #  Mirror it with overlap: ">)]|"→">)]|[(<" or ">]|"→">]|[<"
 D                #  Duplicate this mirrored string
  y               #  Push the current part
   s              #  Swap so the copy of the mirrored string is at the top
    Ã             #  Keep only those characters in the part (removes noses "^"/"-")
     k            #  Get the 0-based index of the character in the mirrored string
      ®g          #  Push string `®`, and pop and push its length
        <         #  Decrease it by 1
         -        #  And subtract this from the index
 X                #  Push variable `X`
  ·               #  Double it
   <              #  Decrease it by 1
    *             #  And multiply the top two values
                  #  (negates the current value if X==0, or leaves it as is if X==1)
 y                #  Push the current part again
  Ā               #  Check that it's NOT empty (0 if empty; 1 otherwise)
   *              #  And multiply that as well, so empty parts become 0
}I                # After the loop, push the input again
  ';å            '# Check if it contains a ";" (1 if truthy; 0 if falsey)
O                 # And sum all values on the stack
                  # (after which the result is output implicitly)

```
> 5 votes

# Answer
# JavaScript (ES6),  ~~181~~  176 bytes

```
s=>((/^[()]|[-^][:;]|[:;]$/.test(s)?s=[...s].reverse(q=-1):q=1,[b,e,n,m]=s,n?m?0:e<':'|e>';'?[e,b,m]=s:m=n:[e,m,b]=s,"<[|]>".indexOf(b)-2)%3+q*(e>':')+"<([|])>".indexOf(m)-3)*q

```

Try it online!

### Commented

```
s => (                      // s = smiley string
  (                         //
    /^[()]|[-^][:;]|[:;]$/  // the smiley is unambiguously flipped if:
                            //   - it starts with a parenthesis
                            //   - or there's a nose before the eyes
                            //   - or it ends with the eyes
    .test(s) ?              // if the smiley is flipped:
      s = [...s]            //   reverse s
          .reverse(q = -1)  //   and set q to -1
    :                       // else:
      q = 1,                //   set q to 1
    [b, e, n, m] = s,       // default order: eyebrows, eyes, nose, mouth
    n ?                     // if s is at least 3 character long:
      m ?                   //   if s is 4 character long:
        0                   //     we got it right, so do nothing
      :                     //   else (3 characters):
        e < ':' | e > ';' ? //     if there's a nose:
          [e, b, m] = s     //       new order: eyes, nose, mouth
                            //       but we actually load the nose into the
                            //       eyebrows to invalidate them
        :                   //     else:
          m = n             //       the nose is actually the mouth
    :                       // else (2 characters):
      [e, m, b] = s,        //   new order: eyes, mouth
                            //   (and set eyebrows to undefined)
    "<[|]>".indexOf(b) - 2  // compute the score for the eyebrows
  ) % 3 +                   // turn -3 into 0
  q * (e > ':') +           // add the score for the eyes
  "<([|])>".indexOf(m) - 3  // add the score for the mouth
) * q                       // multiply the final result by q

```
> 3 votes

# Answer
# Retina 0.8.2, 165 bytes

```
$
@
([()].+|..[:;].|.+[:;])@
@$1
T`()><`Ro`@.|.@
T`(<[]>)`Ro`@.+
[[<(]
#$&
T`()<>[];`33221
\d
$*1@
1
@1
+`#@1
#1#
+`#1[^1]*@1|@1[^1]*#1

[^#1]

^(#)?(1#*)*
$#1$*-$#2

```

Try it online! Link includes test cases. Explanation:

```
$
@

```

Append a chin to the face.

```
([()].+|..[:;].|.+[:;])@
@$1

```

If the face seems flipped then prepend the chin instead.

```
T`()><`Ro`@.|.@

```

Switch `()`s and `><`s in the mouth, so that `><`s are scored consistently.

```
T`(<[]>)`Ro`@.+

```

Flip the characters in a flipped face.

```
[[<(]
#$&

```

Mark the unhappy characters.

```
T`()<>[];`33221

```

Get the happiness of each character.

```
\d
$*1@

```

Convert the happiness to unary.

```
1
@1

```

Initially mark the happiness as positive.

```
+`#@1
#1#

```

Propagate negative happiness.

```
+`#1[^1]*@1|@1[^1]*#1

```

Pair happiness and unhappiness and delete both.

```
[^#1]

```

Delete all other characters.

```
^(#)?(1#*)*
$#1$*-$#2

```

Calculate the total happiness.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 213 bytes

```
Association[Thread[{""<>#,""<>(Reverse@#/.(Rule@@@Characters@"<>><())([]]["~Partition~2))}&[StringTake[" <[|]>:; ^-<([|])>",List/@{##}+{0,6,8,11}]~StringDelete~" "]->If[#<2,4,#]+#2+#4-9]&@@@Tuples@Range@{6,2,3,7}]

```

Try it online! This is an expression which evaluates to an `Association` object. It takes a string as input and returns an integer as output. The logic is very simple: it generates and rates all possible emoticons, and then it returns the rating for the given emoticon.
> 1 votes

# Answer
# Jelly, 56 bytes

```
O:6ṣ9Ẉ>/ȯḢƲ%5Ḣ
ṚÇ©¡“<[|]>“<([|])>”iⱮ€U2¦o3SḢḟ0_7N®¡+”;e$

```

**Try it online!** Or see the test-suite. Or see all the emoticons.

### How?

This decides whether to reverse the string using the helper link (if the left of the eyes is longer than the right or if the string starts with a `(` or `)`, all using ordinals div six). Then finds the unflipped values of the eyebrows and mouth by indexing into two lists of characters while special-casing a lack of eyebrows and then offsetting the sum. Negates this result if we reversed the string (effectively the same as flipping the characters). Finally adds one to the result if the eyes are winking.

```
ṚÇ©¡“<[|]>“<([|])>”iⱮ€U2¦o3SḢḟ0_7N®¡+”;e$ - Main Link: list of characters, E
   ¡                                      - repeat...
 Ç                                        - ...number of times: call helper link as f(E)
  ©                                       -    (and copy the result to the register)
Ṛ                                         - ...action: reverse
    “<[|]>“<([|])>”                       - list of lists of characters = ["<[|]>","<([|])>"]
                     €                    - for each (list, p, in that list):
                    Ɱ                     -   map (across c in E) with:
                   i                      -     first index (of c) in (p)
                      U2¦                 - reverse the second of the resulting list
                         o3               - replace 0s (not found) with 3s
                                            (offsetting a lack of eyebrows)
                           S              - sum (e.g. [[2,4],[5,1]] -> [7,5])
                            Ḣ             - head -> the sum of the relevant indices
                                                    zero if empty
                             ḟ0           - filter discard zeros
                               _7         - subtract 7
                                   ¡      - repeat...
                                  ®       - ...number of times: recall from register
                                 N        - ...action: negate
                                        $ - last two links as a monad:
                                     ”;   -   ';' character
                                       e  -   exists in (E)?
                                    +     - add
                                          - implicit print (the result is a list containing a single integer, which is printed as that integer)

O:6ṣ9Ẉ>/ȯḢƲ%5Ḣ - Link 1, should_reverse?: list of characters, E
O              - ordinals
 :6            - integer divide by six
   ṣ9          - split at nines (':' or ';')
          Ʋ    - last four links as a monad - f(x):
     Ẉ         -   length of each
       /       -   reduce by:
      >        -     greater than?
         Ḣ     -   head (x)
        ȯ      -   logical OR (replace a 0 with the list of ordinals of the left part)
           %5  - modulo by five - '(' and ')' give 1, others give 0
             Ḣ - head

```
> 1 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Amount Of Potential Keys That'll Fit The Lock
## Introduction:

You're a key maker, and want to access something from a safe that has a lock. Unfortunately, the key to that lock is lost, so you'll have to make a new one. You have access to a bunch of blank keys, to which you can add notches to turn it into actual keys. You also have loads of keys with notches already applied lying around.

## Challenge:

Given a list of list of digits (all of equal length) representing the list of keys with notches you have lying around, where each digit represents the height of the notch 'column', as well as an integer list of digits of the key you want to make for the lock of the safe, output the amount of keys you should potentially make in order to try to open the lock.

How would we determine this? Here an example:
Let's say the key that's supposed to go into the lock is `[7,5,2,5]` (where the first digit is at the opening of the lock). And let's say the list of keys you have available is `[[2,5,3,5],[3,7,5,8],[8,2,1,0],[6,3,6,6],[7,9,5,7],[0,2,2,1]]` (where the last digits are the tips of the keys).

Here is how far we can insert each key into the lock:

Let's take the first key `[2,5,3,5]` as more in-depth example:

```
[2,5,3,5]         # First notch:  5<=7, so it fits
    [7,5,2,5]     # Second notch: 5<=5 & 3<=7, so it fits
                  # Third notch:  5>2 (& 3<=5 & 5<=7), so it can't be inserted that far into the lock
                  # Based on this key we now know the following about the safe-key:
                  # First notch:  >=5
                  # Second notch: >=5
                  # Third notch:  <5

```

Here a visual representation, to perhaps better understand it, where the blue cells are key `[2,5,3,5]`, the yellow parts is the key that's supposed to go into the lock `[7,5,2,5]`, and the black parts are the lock itself:

As for the other keys:

```
[3,7,5,8]         # First notch: 8>7, so it can't even be inserted into the lock at all
        [7,5,2,5] # base on this key we now know the following about the safe-key:
                  # First notch:  <8

[8,2,1,0]         # First notch:  0<=7, so it fits
  [7,5,2,5]       # Second notch: 0<=5 & 1<=7, so it fits
                  # Third notch:  0<=2 & 1<=5 & 2<=7, so it fits
                  # Fourth notch: (0<=5 & 1<=2 & 2<=5 &) 8>7, so it can't be inserted that far
                  # Based on this key we now know the following about the safe-key:
                  # First notch:  >=2 & <8
                  # Second notch: >=1
                  # Third notch:  >=0 (duh)
                  # Fourth notch: nothing; we couldn't insert it to due to first notch

[6,3,6,6]         # First notch:  6<=7, so it fits
      [7,5,2,5]   # Second notch: 6>5 (& 6<=7), so it can't be inserted that far
                  # Based on this key we now know the following about the safe-key:
                  # First notch:  >=6
                  # Second notch: <6

[7,9,8,7]         # First notch:  7<=7, so it fits
      [7,5,2,5]   # Second notch: 7>5 & 8>7, so it can't be inserted that far
                  # Based on this key we now know the following about the safe-key:
                  # First notch:  >=7 & <8
                  # Second notch: <7

[0,2,2,1]         # First notch:  1<=7, so it fits
[7,5,2,5]         # Second notch: 1<=5 & 2<=7, so it fits
                  # Third notch:  1<=2 & 2<=5 & 2<=7, so it fits
                  # Fourth notch: 1<=5 & 2<=2 & 2<=5 & 0<=7, so it fits
                  # Based on this key we now know the following about the safe-key:
                  # First notch:  >=2
                  # Second notch: >=2
                  # Third notch:  >=2
                  # Fourth notch: >=1

```

Combining all that:

```
# First notch:  ==7 (>=7 & <8)
# Second notch: ==5 (>=5 & <6)
# Third notch:  >=2 & <5
# Fourth notch: >=1

```

Leaving all potential safe-keys (**27** in total, which is our output):

```
[[1,2,5,7],[1,3,5,7],[1,4,5,7],[2,2,5,7],[2,3,5,7],[2,4,5,7],[3,2,5,7],[3,3,5,7],[3,4,5,7],[4,2,5,7],[4,3,5,7],[4,4,5,7],[5,2,5,7],[5,3,5,7],[5,4,5,7],[6,2,5,7],[6,3,5,7],[6,4,5,7],[7,2,5,7],[7,3,5,7],[7,4,5,7],[8,2,5,7],[8,3,5,7],[8,4,5,7],[9,2,5,7],[9,3,5,7],[9,4,5,7]]

```

## Challenge rules:

* Assume we'll know all notches when it doesn't fit, even though the lock would in reality be a black box. Let's just assume the key maker is very experienced, and can feel such a thing. What I mean by this, is for example shown with key `[7,9,8,7]` in the example above. It fails at the second stage because of both `7>5` and `8>7`. In reality we wouldn't know which of those two caused it to be blocked and making us unable to insert the key any further, but for the sake of this challenge we'll assume we know all of them if there are more than one.
    + Also note that for `[8,2,1,0]` we don't know anything about the fourth notch, because we couldn't insert it past the third.
    + Also, in reality the key maker could test some of the keys he makes after testing all existing ones to further decrease the amount of potential keys he has to make, so the number would be much lower than `72` in the example, but for the sake of this challenge we'll just determine the amount of all possible safe-keys for the lock based on the given existing keys once.
    + EDIT/NOTE: Even the intended `[7,5,2,5]` key wouldn't be able to insert all the way into its intended lock `[7,5,2,5]` in how the keys and locks interact in this challenge. This doesn't change the actual challenge nor test cases, but does make the backstory pretty flawed.. :/ Key `[7,5,2,5]` in lock `[7,5,2,5]` would act like this: first notch: `5<=7`, so it fits; second notch: `5<=5 & 2<=7`, so it fits; third notch: `5>2 (& 2<=5 & 5<=7)`, so it can't be inserted that far.
* You can take the I/O in any reasonable format. Can be a list of strings or integers (note that leading 0s are possible for the keys) instead of the list of lists of digits I've used.
* You can assume all keys of the input have the same length, which is \\$1\leq L\leq10\\$.
* You are allowed to take the safe-key input in reversed order, and/or all keys in the list in reversed order. **Make sure to mention this in your answer if you do!**
* You can assume the safe-key is not in the list of other keys.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input safe-key:   [7,5,2,5]
Input other keys: [[2,5,3,5],[3,7,5,8],[8,2,1,0],[6,3,6,6],[7,9,5,7],[0,2,2,1]]
Output:           27  ([[1,2,5,7],[1,3,5,7],[1,4,5,7],[2,2,5,7],[2,3,5,7],[2,4,5,7],[3,2,5,7],[3,3,5,7],[3,4,5,7],[4,2,5,7],[4,3,5,7],[4,4,5,7],[5,2,5,7],[5,3,5,7],[5,4,5,7],[6,2,5,7],[6,3,5,7],[6,4,5,7],[7,2,5,7],[7,3,5,7],[7,4,5,7],[8,2,5,7],[8,3,5,7],[8,4,5,7],[9,2,5,7],[9,3,5,7],[9,4,5,7]])
                      (==7, ==5, >=2&<5, >=1)

Input safe-key:   [3]
Input other keys: [[1],[6],[2],[9]]
Output:           4  ([[2],[3],[4],[5]])
                     (>=2&<6)

Input safe-key:   [4,2]
Input other keys: [[4,1],[3,7],[4,4],[2,0]]
Output:           9  ([[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]])
                     (>=1&<4, >=4&<7)

Input safe-key:   [9,8,7,5,3]
Input other keys: [[4,6,7,0,6],[5,5,0,7,9],[6,3,3,7,6],[9,1,0,3,1],[3,8,5,3,4],[3,6,4,9,7]]
Output:           48  ([[9,7,6,4,1],[9,7,6,4,2],[9,7,6,4,3],[9,7,6,5,1],[9,7,6,5,2],[9,7,6,5,3],[9,7,7,4,1],[9,7,7,4,2],[9,7,7,4,3],[9,7,7,5,1],[9,7,7,5,2],[9,7,7,5,3],[9,7,8,4,1],[9,7,8,4,2],[9,7,8,4,3],[9,7,8,5,1],[9,7,8,5,2],[9,7,8,5,3],[9,7,9,4,1],[9,7,9,4,2],[9,7,9,4,3],[9,7,9,5,1],[9,7,9,5,2],[9,7,9,5,3],[9,8,6,4,1],[9,8,6,4,2],[9,8,6,4,3],[9,8,6,5,1],[9,8,6,5,2],[9,8,6,5,3],[9,8,7,4,1],[9,8,7,4,2],[9,8,7,4,3],[9,8,7,5,1],[9,8,7,5,2],[9,8,7,5,3],[9,8,8,4,1],[9,8,8,4,2],[9,8,8,4,3],[9,8,8,5,1],[9,8,8,5,2],[9,8,8,5,3],[9,8,9,4,1],[9,8,9,4,2],[9,8,9,4,3],[9,8,9,5,1],[9,8,9,5,2],[9,8,9,5,3]])
                      (==9, >=7&<9, >=6, >=4&<6, >=1&<4)

Input safe-key:   [5,4]
Input other keys: [[6,3]]
Output:           30  ([[0,3],[0,4],[0,5],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,3],[3,4],[3,5],[4,3],[4,4],[4,5],[5,3],[5,4],[5,5],[6,3],[6,4],[6,5],[7,3],[7,4],[7,5],[8,3],[8,4],[8,5],[9,3],[9,4],[9,5]])
                      (>=3&<6, n/a)

```

# Answer
> 9 votes
# Python 2, 196 bytes

```
l,o=input()
b=[[[0],[10]]for _ in l]
for k in o:
 R=range(len(l))
 for i in R:
	for x in 0,1:
	 for j in R[:i+1]:
		if(k[~i+j]>l[j])+x:b[j][~x]+=k[~i+j],;R*=x
for a,b in b:x*=min(b)-max(a)
print x

```

Try it online!

**Commented**:

```
l,o=input()                    # input: safe-key/lock, other keys
b=[[[0],[10]]for _ in l]       # for each column in the lock b stores:
                               #   a list of inclusive lower bounds and
                               #   a list of exclusive upper bounds
for k in o:                    # iterate over the other keys
  R=range(len(l))
  for i in R:                  #   each insertion-level i (0-indexed)
    for x in 0,1:              #     x=0: check if the key can't move there, update upper bounds
                               #     x=1: if the key fits, update lower bounds
                               #     this final value of x will be used later
      for j in R[:i+1]:        #     for each column:
        if(k[~i+j]>l[j])+x:    #       if the key doesn't fit at column j of the lock or x=1:
          b[j][~x]+=k[~i+j],   #         update the the right list of bounds
          R*=x                 #         and, if x=0, set R to the empty list
                               #          if this happens the 'for j in R[:i+1]'-loop will complete,
                               #          but will then never run again for the current key

for a,b in b:                  # for lower and upper bounds of each column
 x*=min(b)-max(a)              #   calculate the product in x (previously 1)
print x                        # print the result

```

---
Tags: code-golf, number, integer
---


title: Generate Menu Access Keys

text:
# Question
Title: Generate Menu Access Keys
This is thematically similar to Generate keyboard shortcuts for a menu, but its actually a pretty different challenge.

Let's take PHPStorm's menu as an example:

```
New Project
New
Open Directory
Open
Open URL
New Project from Existing Files
Save As
Open Recent
Close Project
Rename Project

```

We need to assign a single-letter access keys for each of these menu items. Typically we pick the first letter, but if you notice, many of the above menu items start with the same letter!

Therefore, we'd want to pick:

```
P -> New Project
N -> New
D -> Open Directory
O -> Open
U -> Open URL
F -> New Project from Existing Files
S -> Save As
E -> Open Recent  (We don't pick "R" here because "Rename Project" needs it)
C -> Close Project
R -> Rename Project

```

Therefore, for our list we need to maximize (in order of importance):

1. The number of access keys actually contained in the string.
    * `["X" -> "New"]` should be avoided unless its your only option.
2. The number of access keys that start a word.
    * `["N"->"New", "P"->"New Project"]` is better than `["E"->"New", "N"->"New Project"]`
3. The number of access keys that start the sentence.
    * `["N"->"New Project"]` is better than `["P"->"New Project"]`

Access keys are case-insensitive, so if your menu is `["Add", "add"]`, one of them will need to use `D` as its access key.

# Input/output

You need to input a list of strings. The strings will only contain alphabetic characters and spaces. You can optionally input a single string with a delimiter for each of the lines. You can assume there will be between 1 and 26 menu items (inclusive).

You need to output either:

1. A Key-value map, where the key is the access key letter, and the value is the string it maps to
2. A list of access key letters, where the Nth entry pairs with the Nth item in the list.

You can either return the objects themselves, or a reasonable string representation of them. Access key letters can be in any case.

# Test Cases:

```
A                            -> A
Add,add                      -> A,D
Add To,Add                   -> T,A
Add To,Add Around,Add For    -> T,A,F
Add To,Flip To,Add For       -> T,F,A
Add,add,Dip,Around           -> A,D,I,R
Add,add,Dad                  -> A,B,D
Add,add,Dad,dad,ad dadad,B   -> A,C,D,E,Z,B
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,A,B,C -> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Add,Bz,Cx -> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y,Z,X

```

# Answer
# Jelly, 41 bytes

```
e/€S;eḲ1ịⱮƊ}¥/€;=Ḣ¥/€µS
LØAœ!ż€³Œu¤ÇÐṀẎḢ€

```

Try it online!

This is really messy and also O(26^n) lol.

Explanation: literally just brute forces it .\_.

-6 bytes thanks to caird coinheringaahing
> 3 votes

---
Tags: code-golf, string
---


title: Project Euler's "Harshad Numbers"

text:
# Question
Title: Project Euler's "Harshad Numbers"
Project Euler Problem 387 states:

> A *Harshad* or *Niven number* is a number that is divisible by the sum of its digits. 201 is a Harshad number because it is divisible by 3 (the sum of its digits.) When we truncate the last digit from 201, we get 20, which is a Harshad number. When we truncate the last digit from 20, we get 2, which is also a Harshad number. Let's call a Harshad number that, while recursively truncating the last digit, always results in a Harshad number a *right truncatable Harshad number*.
>
> Also: 201/3=67 which is prime. Let's call a Harshad number that, when divided by the sum of its digits, results in a prime a *strong Harshad number*.
>
> Now take the number 2011 which is prime. When we truncate the last digit from it we get 201, a strong Harshad number that is also right truncatable. Let's call such primes *strong, right truncatable Harshad primes*.

Given a number `n`, determine the first `n` strong, right truncatable Harshad primes.

**Input:** An integer, `n`, where `n<50`. (This means your program will need to be somewhat efficient.)

**Output:** The first `n` strong, right truncatable Harshad primes, with some form of whitespace in between each value.

**Reference Table:** The first 20 strong, right truncatable Harshad primes are:
1-10:`181 211 271 277 421 457 631 2011 2017 2099`
11-20:`2473 2477 4021 4027 4073 4079 4231 4813 4817 6037 8011`

Shortest code wins. Good luck!

# Answer
> 4 votes
## Python 188 bytes

```
r=range(10)
h=zip(r,r)
w=input()
p=lambda n:all(n%~i for i in range(1,int(n**.5)))%n
while w:
 n,s=h.pop(1)
 for i in r:
    d=s+i;i+=10*n
    if i%d<1:h+=[(i,d)]
    if p(n/s)and p(i):print i;w-=1

```

This could be made shorter, but my primary concern was efficiency. This code maintains a list of the 'right truncable harshad numbers', as well as the their digital sum, and then uses this list to extend itself by one digit iteratively, allowing only new truncable numbers. I don't see any way to obtain the efficiency required without maintaining such a list. Runtime for `n<=50` is less than one second.

A less efficient version, which calculates everthing as it goes (**139 bytes**, has an acceptable runtime for `n<=31`):

```
s=9
w=input()
while w:
 n=s=s+2;x=2;f=0
 while n>9:n/=10;z=sum(map(int,`n`));x-=n%z;f=f or(n/z<3)+n/z
 if(1<<s)%s==(1<<f)%f==x:print s;w-=1

```

# Answer
> 3 votes
## Python, 204

```
def p(x):
 i=2
 while x%i:i+=1
 return i==x
def h(x):s=sum(map(int,`x`));return[0,x/s][x%s<1]
f=lambda x:x<10or h(x/10)and f(x/10)
n=input()
i=99
while n:
 i+=2
 if f(i)and p(h(i/10))and p(i):print i;n-=1

```

# Answer
> 3 votes
# K, 190

```
w:{i:0;l:();while[x>#l;if[{$[x>9;$[{&/(h:{a=_a:(d:{x%+/"I"$'$x})x})'{-1_"I"$_[-1]\[$x]}x}q:"I"$-1_$x;$[{(h x)&(p:{(x>1)&&/{x-y*x div y}[_x;2_!_x]})d x}q;$[p x;1;0];0];0];0]}i;l,:i];i+:1];l}

```

.

```
k)w 10
181 211 271 277 421 457 631 2011 2017 2099

```

An easier to read version of the unintelligible one-liner above:

```
d:{x%+/"I"$'$x}                                     /divide number by sum of digits
h:{a=_a:d x}                                        /test for harshad number
t:{-1_"I"$_[-1]\[$x]}                               /right-truncate a number recursively
r:{&/h't x}                                         /right-truncatable harshad
p:{(x>1)&&/{x-y*x div y}[_x;2_!_x]}                 /isPrime
s:{(h x)&p d x}                                     /strong harshad
m:{$[x>9;$[r q:"I"$-1_$x;$[s q;$[p x;1;0];0];0];0]} /strong right truncatable harshad prime
w:{i:0;l:();while[x>#l;if[m i;l,:i];i+:1];l}        /print the first n harshad srthps

```

# Answer
> 0 votes
# Jelly, 22 bytes

```
DṖSḍḌƊÐƤP$×Ḍ÷SƊẒ$Ɗ×Ẓµ#

```

Try it online!

This really should be shorter :/

## How it works

```
DṖSḍḌƊÐƤP$×Ḍ÷SƊẒ$Ɗ×Ẓµ# - Main link. No arguments
         $×      Ɗ× µ# - Read an integer, n, and return the first n integers for which the following three conditions are true:
                   Ẓ   -   1. The integer is prime
DṖSḍḌƊÐƤP              -   2. The integer is a right truncatable Harshad number:
D                      -      Convert to digits
 Ṗ                     -      Remove the last one
     ƊÐƤ               -      Generate the suffixes of the digit list, then, for each:
  S                    -        Take the sum of the suffix
    Ḍ                  -        Convert the suffix back to a number
   ḍ                   -        Does the sum divide the number?
        P              -      Is this true for all the suffixes?
DṖ         Ḍ÷SƊẒ$      -   3. The right truncated integer is a strong Harshad number:
D                      -      Convert to digits
 Ṗ                     -      Remove the last digit
                $      -      Group the previous two commands together:
              Ɗ        -        Group the previous three commands together:
             S         -          Take the sum of the digits
           Ḍ           -          Convert back to an integer
            ÷          -          Divide the integer by the sum
               Ẓ       -        Is this number prime?

```

---
Tags: code-golf, math
---


title: Interpret +p code

text:
# Question
Title: Interpret +p code
Inspired by the recent craze over another two character language, `;#`

**Intro**

According to community consensus, acceptable answers on this site must use programming languages that, at minimum:

1. Can determine if a natural number is prime
2. Can add two natural numbers together
3. Can represent a list/tuple of numbers, as well as a single number

For purposes of this challenge, we will ignore #3. Therefore, the simplest language that could be used on this site (ignoring #3) would have exactly two commands, `isPrime` and `add`. For ease of interpretation and byte count, let's assign `isPrime` to `p` and `add` to `+`. Thus, we have our language, `+p`. Your challenge is to interpret some `+p` code.

**Behavior**

* `+` the `add` instruction takes two numbers, adds them, and outputs the result
* `p` the `isPrime` instruction takes a single number, and outputs `1` if it is prime, and `0` if it is not

**Rules**

* You must write a program/function which, given a string of characters, interprets that string as `+p` code. You may assume well-formed input (only `+` and `p` characters).
* Input is flexible. You may take in the program as a string, character array, integer array of codepoints, etc. Input for the program being interpreted is also flexible. You may take in an integer array, and use up entries as the program executes, or each instruction (`+` and `p`) may individually request input. You may assume there will be enough input for every instruction. Input is guaranteed to consist of numbers between 0 and 200 (but your algorithms should theoretically work for any positive integer input).
* Output is also flexible. You may print the results, return them as a list, return a string that contains all the results, etc. If printed or returned as a string, output must be separated by some non-digit, consistent separator, such as a new line, tab, space, or `,` character. You may have a trailing separator or some trailing whitespace. Also, `p`'s output may be any truthy or falsey value, as defined by the language you are working in, rather than `1` or `0`.
* The interpreter may or may not terminate (if it is a full program), but it must stop printing after all instructions are interpreted. (It cannot continue printing the separator forever, or a null character, etc.).
* These standard loopholes are forbidden by default
* This is , the answer with the least bytes wins

**Test Cases**

```
Program: +
Input: [56, 50]
Output: 106
----------------------------------
Program: p
Input: [12]
Output: 0
----------------------------------
Program: p
Input: [13]
Output: 1
----------------------------------
Program: ++
Input: [172, 120, 33, 58]
Output: 292 91
----------------------------------
Program: p
Input: [29]
Output: 1
----------------------------------
Program: pp
Input: [176, 12]
Output: 0 0
----------------------------------
Program: ++++p
Input: [32, 16, 69, 197, 73, 171, 21, 178, 72]
Output: 48 266 244 199 0
----------------------------------
Program: pp+++p+pp+
Input: [151, 27, 119, 189, 198, 107, 174, 15, 166, 106, 134, 108, 169, 55, 42]
Output: 1 0 308 305 189 0 240 0 0 97
----------------------------------
Program: p+p+++++++pp+p
Input: [143, 67, 30, 149, 178, 52, 112, 122, 55, 122, 142, 199, 20, 175, 138, 80, 116, 180, 50, 116, 15, 92, 74]
Output: 0 97 1 230 234 177 341 195 218 296 0 0 107 0
----------------------------------
Program: ++p++p+pp+++++p+p+pp++
Input: [120, 177, 23, 116, 163, 52, 65, 98, 177, 16, 96, 131, 160, 48, 153, 0, 139, 33, 62, 49, 129, 86, 99, 135, 187, 80, 137, 130, 113, 136, 0, 1, 186, 100, 38, 153]
Output: 297 139 1 117 275 0 227 0 0 153 172 111 215 234 0 217 0 249 0 0 286 191
----------------------------------
Program: ++p+++++p+p+++++++
Input: [181, 169, 6, 84, 68, 171, 129, 107, 106, 114, 197, 58, 11, 88, 156, 169, 43, 77, 49, 43, 102, 78, 93, 51, 91, 37, 64, 93, 82, 126, 181, 81, 44]
Output: 350 90 0 300 213 311 69 244 0 120 0 145 171 142 101 175 307 125
----------------------------------
Program: ++p+
Input: [131, 127, 115, 40, 113, 196, 83]
Output: 258 155 1 279
----------------------------------
Program: +ppp++p+ppp+p++++++++p+p+++pp+ppp++
Input: [6, 9, 187, 168, 96, 167, 178, 139, 86, 148, 99, 103, 166, 18, 119, 15, 132, 77, 16, 88, 139, 34, 58, 90, 43, 69, 68, 152, 59, 106, 134, 49, 155, 100, 52, 55, 27, 188, 41, 77, 23, 49, 171, 23, 193, 84, 111, 165, 80, 18, 63, 23, 116, 112, 119]
Output: 15 0 0 0 345 225 0 202 0 0 0 147 0 104 173 148 112 220 165 183 255 0 82 0 118 72 194 1 0 276 0 0 0 139 231
----------------------------------
Program: ++++++++p++++++++++++
Input: [156, 5, 34, 25, 117, 98, 139, 131, 88, 82, 191, 13, 1, 170, 51, 116, 144, 85, 92, 170, 25, 94, 149, 131, 19, 161, 115, 160, 8, 6, 195, 101, 11, 185, 87, 50, 33, 140, 188, 135, 164]
Output: 161 59 215 270 170 204 171 167 0 177 195 243 150 276 168 201 112 272 83 328 299
----------------------------------

```

Many, many, very long test cases

The java code used to generate test cases

**Example**

Below is an ungolfed java function which will interpret `+p`:

```
public static void interpret(String program, int[] input) {
    int index = 0;
    for (char inst : program.toCharArray()) {
        switch (inst) {
            case '+':
                System.out.print((input[index++] + input[index++]) + " ");
                break;
            case 'p':
                int n = input[index++];
                System.out.print((isPrime(n) ? 1 : 0) + " ");
                break;
        }
    }
}

public static boolean isPrime(long n) { //Taken from https://stackoverflow.com/a/2385999/4484294
    if (n < 2) return false;
    if (n == 2 || n == 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    long sqrtN = (long) Math.sqrt(n) + 1;
    for (long i = 6L; i <= sqrtN; i += 6) {
        if (n % (i - 1) == 0 || n % (i + 1) == 0) return false;
    }
    return true;
}

```

Note: Using the search query `prime AND add AND interpret is:question`, there do not appear to be any duplicates to this question. If there is one, sorry.

# Answer
# 05AB1E, 5 bytes

```
vy.V,

```

Try it online!

**Explanation**

This challenge fit 05AB1E like a glove :)

```
vy      # for each instruction in the program
  .V    # execute as 05AB1E code
    ,   # print

```
> 33 votes

# Answer
# Python 2, ~~135~~ 133 bytes

```
l,p=input()
i=j=0
while len(l)-i:print(int(all(l[i]%k for k in range(2,l[i])))if p[j]=='p'else l[i]+l[i+1]);i+=1+'p+'.find(p[j]);j+=1

```

-2 bytes thanks to kundor
> 7 votes

# Answer
# Python 2, 91 bytes

```
p,i=input()
for c in p:n=i.pop(0);print all(n%k for k in range(2,n))if c>'+'else n+i.pop(0)

```

Try it online!
> 6 votes

# Answer
# Haskell, ~~88~~ 79 bytes

```
('+':r)!(a:b:c)=a+b:r!c
('p':r)!(a:c)=min(foldr((*).mod a)1[2..a-1])1:r!c
_!e=e

```

`"commands" ! [args]` for use.

* Saved 9 bytes thanks to @Laikoni (#56433)

I'm still learning Haskell; golfing tips appreciated!
> 5 votes

# Answer
# Perl 6, 70 bytes

```
{@^b.rotor($^a.comb.map(1+(*ne'p'))).map({$_-2??.[0].is-prime!!.sum})}

```

First the `rotor` method is used to split the input list into chunks of size 1 or 2 depending on whether the next character of the program is `p` or not. Then that chunked list is mapped over; chunks of size 2 are summed, and chunks of size 1 have their sole element tested for primality.
> 4 votes

# Answer
# Ruby 2.4, 77+7 = 84 bytes

Uses the `-rprime` flag.

```
->g,i{g.chars.map{|c|c==?p?i.shift.prime?? 1:0: c==?+?i.shift(2).sum: p}-[p]}

```
> 4 votes

# Answer
# Jelly, 18 bytes

```
ÆP,+/ị@L
OḂ‘Bṁ@Ç€K

```

Try it online!

**Alternate solution, 18 bytes**

```
⁴Ḣ
¢+¢µ¢ÆPµḂ?
OÇ€K

```

Try this one online!
> 3 votes

# Answer
# C#, ~~130~~ 129 bytes

```
p=>d=>{var i=0;p.Any(c=>{Console.Write((c==43?d[i++]+d[i]:Enumerable.Range(2,d[i]-2).Any(x=>d[i]%x==0)?0:1)+" ");return++i<0;});}

```

Try it online!

* Saved 1 byte by currying the function (thanks to Cyoce)
> 3 votes

# Answer
## PowerShell 3+, ~~151~~ 121 Bytes

```
$r,$v=$args;$p={0-notin((2..(($n=0+"$args")-1)|%{$n%$_}))};$i=0;$r|%{if($_-eq"p"){&p $v[$i]}else{$v[$i]+$v[($i+=1)]}$i++}

```

PowerShell has no prime built-ins so I had to roll my own. My first version was terrible and I took from most of the other ones that test for 0 among modulus results which saves a lot. Also sabed a few bytes by using `-notin` instead of `-notcontains` but it mean PowerShell v2 is out.

### Comment based explanation

```
# $r is the program code. Assumed char array
# $v is the remaining variables in an assumed integer array.
$r,$v=$args
# Anonymous function to determine if a number is a prime or not.
# Test all potential factors. Check if any 0 modulus remainders are present
$p={0-notin((2..(($n=0+"$args")-1)|%{$n%$_}))}
# $i is an index for tracking location in $v
$i=0
# Cycle each of the instructions
$r|%{if($_-eq"p"){
        # Call the prime checking anonymous function on this number
        &p $v[$i]
    }else{
        # Add the next two numbers. Adjust the index accordingly.
        $v[$i]+$v[($i+=1)]

    }
    # Next number in list.
    $i++
}
    # Next number in list.
    $i++
}

```
> 2 votes

# Answer
# F#, 130 bytes

```
let rec r=function|[],_->()|'+'::t,f::s::u->printf"%i "(f+s);r(t,u)|_::t,n::u->printf"%b "(List.exists((%)n>>(=)0)[2..n-1]);r(t,u)

```

Try it online!
> 1 votes

# Answer
# QBasic, 122 bytes

```
INPUT p$
FOR i=1TO LEN(p$)
INPUT x
IF"+"=MID$(p$,i,1)THEN INPUT y:?x+y:ELSE f=0:FOR j=2TO x:f=f-(x MOD j=0):NEXT:?f=1
NEXT

```

Takes the code as a line of input, then takes each input number on its own line. The outputs are interspersed with the inputs because they're printed as soon as they're calculated. The truthy value is `-1`; falsey is `0`.
> 0 votes

# Answer
# Japt, 15 bytes

Takes the programme as a character array, outputs `true` or `false` for the prime test.

```
Ëø²?Vv j:Vv +Vv

```

Try it (Header splits the programme into an array)
> 0 votes

# Answer
# Rockstar, ~~206~~ ~~197~~ 177 bytes

Outputs `0` for composites and `-0.5` for primes

```
listen to S
cut S
while S
listen to N
if roll S's "+"
listen to I
say N-I/-1
else
let D be N
let P be N-1
while P and D-2
let D be-1
let M be N/D
turn M up
let P be N/D-M

say P

```

Try it here (Code will need to be pasted in, with the programme as the first line of input and each integer on its own line)
> 0 votes

---
Tags: code-golf, interpreter
---


# Question
Title: Find the result of some assignment statements
In this challenge, the goal is to find the values of some variables after a number of assignments are done. An example input:

```
a = 5
b = 4
c = a = b
a = 2
b = a

```

This would result in:

```
a = 2
b = 2
c = 4

```

Each statement will be one of the following:

* A variable name (`[a-z_]+`)
* A numeric value (`[0-9]+`)
* An assignment operation, with a variable name on the left and a statement on the right

You may assume that the input will be a list of statements, formatted however you want. Variable names will have differing lengths (if you need a hard value to gold within, assume 16 chars max).

Note that statements can contain more or less than one assignment (such as `a`, `23`, or `a = b = c = 4`), and that variables can appear that are never assigned to. Assume no undefined variables are used as values in an assignment (such as `a = undefined_variable`), and that no variable will be on both sides of an assignment (such as `a = a` or `a = a = 1`).

You can take input any way you wish (such as a string with a character to delimit statements, a list formatted as `[["a", 5], ["b", "a"]]`, etc.), and output can be in any consistent format (such as a hash map of names to values, or a list of values in the order that the variables first appeared).

Test cases:

```
a = 5                     -> a = 5
b = 512, c = a = 2        -> a = 2, b = 512, c = 2
def, 2, e = 8, 101        -> e = 8
                          ->
a                         ->
fgh = 4, i = 3, fgh = i   -> fgh = 3, i = 3
j = k = l = m = n = 14    -> j = 14, k = 14, l = 14, m = 14, n = 14
s = t = u = 6, t = v = 7  -> s = 6, t = 7, u = 6, v = 7
o = 3, o = p              -> [undefined]
q = r                     -> [undefined]
w = w = 2                 -> [undefined]
x = 4, x = x              -> [undefined]

```

This is , so shortest answer per language wins!

# Answer
> 9 votes
# APL (Dyalog Unicode), 22 bytes

```
{n⊣⍵{0::0⋄⍵⍎⍺}¨n←⎕NS⍬}

```

Try it online!

Takes a list of statements in the form of `a←b←3`, and returns a namespace which is essentially a hashmap of variable names to values. You can't print all the contents of it directly, but you can inspect individual variables like `ns.somevar` or list all names using `ns.⎕NL ¯2`.

Oh, and APL doesn't have any alphanumeric-only keywords!

```
{n⊣⍵{0::0⋄⍵⍎⍺}¨n←⎕NS⍬}  ⍝ ⍵: list of statements
               n←⎕NS⍬   ⍝ Create an empty namespace
   ⍵{        }¨         ⍝ For each statement...
          ⍵⍎⍺           ⍝ Try executing the statement inside the namespace
     0::0⋄              ⍝ ignoring any errors (undefined name)
 n⊣                     ⍝ Return the populated namespace

```

# Answer
> 8 votes
# Python ~~3~~ 2, ~~80~~ ~~75~~ 69 bytes

*-5 bytes thanks to @Sisyphus*
*-6 bytes thanks to @xnor*

```
g={}
for s in input():
 k=s.pop()
 for n in s:g[n]=g.get(k,k)
print g

```

Try it online!

Takes input as a list of lists of terms, returns a dict of variable name to value.

## Explanation

```
def f(x,g={}):    # Save a few bytes by defining g as a default argument.
 for s in x:
  k=s.pop(-1)     # Take the last term, which is the value we'll be using.
  for n in s:     # For all *other* values:
   g[n]=g.get(k,k)    # .get(k, k) means "get the value called k, if not found use k raw" (numbers will not be found)
 return g

```

Note that it never actually differentiates between numbers and variables, just trusts that the input won't try to assign to a number. This means you *can* actually use it to assign to a number - this input:

```
[9, 5],
['b', 9],
['c', 'a', 'b'],
['a', 2],
['b', 9]

```

Will result in this output:

```
{9: 5, 'b': 5, 'c': 5, 'a': 2}

```

# Answer
> 5 votes
# , 66 bytes

33 bytes for the `_ =: 1` special case …

```
(rplc&('a0';'_')@}.~&_6;".)&>@r0[0!:110@rplc&('_';'a0')[r0=:4!:5@1

```

Try it online!

### How it otherwise works

```
(_6&}.;".)&>@r0[0!:110[r0=:4!:5@1

```

It's a mess! `m!:n` are special functions, that do stuff depending on `m` and `n`.

* `r0=:4!:5@1`: "4!:5 (1) produces a list of global names assigned since the last execution of 4!:5." Store as `r0`, so we can execute it again cheaply while it won't be overwritten.
* `0!:110` execute input string as script, ignoring any output/errors (so predefined values won't cause harm.)
* `r0` execute `4!:5@1` again, get boxed list of changed variables
* `&>` unbox and …
* `".` execute each variable to get its value
* `_6}&.` drop last 6 characters from the variable (which contain the namespace `_base_`.)
* `;` join name and result together

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~55~~ ~~51~~ 43 bytes

```
($=<||>;($@#2=#/.$)&~Fold~Reverse@#&/@#;$)&

```

Try it online!

-8 thanks to w123

# Answer
> 4 votes
# JavaScript (ES6), 81 bytes

Expects a string in the format described in the challenge. Returns an array of `[name, value]` pairs.

```
s=>Object.keys(o={},eval(s.replace(/[_-z]+/g,"o.X$&"))).map(k=>[k.slice(1),o[k]])

```

Try it online!

### How?

We define an object `o` initially empty and add the prefix `"o.X"` to all variable names in the input string.

Example:

```
/* before */ "s = t = u = 6, t = v = 7"
/* after  */ "o.Xs = o.Xt = o.Xu = 6, o.Xt = o.Xv = 7"

```

We need the leading `X` to prevent the reserved property `__proto__` from being overridden this way.

Provided that the input string is in the expected format -- which is guaranteed by the challenge rules -- the transformed string can be safely `eval()`'uated. We then iterate on the keys of `o` to build a list of pairs consisting of 1) the key name without the leading `X` and 2) the final value associated to the key.

Without the `__proto__` issue, this could be done in just 45 bytes without any post-processing:

```
s=>(eval(s.replace(/[_-z]+/g,"o.$&",o={})),o)

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~159~~ ~~141~~ ~~152~~ 128 bytes

```
def f(s):
	g={}
	for k in s:
		if'='in k:
			*v,l=k.split('=')
			for r in v:
				try:g[r]=int(l)
				except:g[r]=g[l]
	return g

```

Try it online!

-18 bytes thanks to pxeger

+11 bytes thanks to Shaggy for pointing out a bug

-24 bytes thanks to ovs

Python really isn't my strong suit for golfing :/ Note the use of tabs rather than spaces, so the indentation levels are still a single byte each. Takes input as a list of lines with assignments separated by `=` (no spaces) and returns a dictionary of variables and values

# Answer
> 3 votes
# Batch, ~~331~~ ~~317~~ 72 bytes

```
@setlocal
@for /f "delims==" %%a in ('set')do @set %%a=
@set/a%*
@set

```

Takes a comma-separated list of assignments on the command line. Explanation:

```
@setlocal

```

Don't modify the parent environment.

```
@for /f "delims==" %%a in ('set')do @set %%a=

```

Delete all variables, including predefined variables such as `PATH`. We're only using shell builtins, so we don't need them.

```
@set/a%*

```

Evaluate the assignments.

```
@set

```

List all of the resulting variables.

# Answer
> 3 votes
# Python 3.9rc2, 67 bytes

```
def f(x):
 g={}
 for*u,k in x:g|={n:g.get(k,k)for n in u}
 return g

```

No TIO link, as TIO doesn't support Python 3.9.

Borrows ideas from Artemis' answer, with the following improvements:

* We can use an iterable unpack `*u,k` in the for loop.
* In Python 3.9 we can merge dicts using `a|=b`, which is much shorter than the old `a.update(b)` and `{**a,**b}` methods.

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 183 bytes

```
	T =TABLE()
N	X =INPUT	:F(O)
R	X SPAN(&LCASE '_') . Y (' ' | RPOS(0)) . Z ='T<"' Y '">' Z	:S(R)
	EVAL(X)	:(N)
O	A =CONVERT(T,'ARRAY')
I	I =I + 1
	OUTPUT =A<I,1> ' = ' A<I,2>	:S(I)
END

```

Try it online!

Takes input separated by newlines with spaces between the `=`, and returns in the same format.

# Answer
> 2 votes
# Ruby, 63 bytes

```
def f(a)
a.reduce({}){|m,x|*r,k=x
r.map{|y|m[y]=m[k]||k}
m}
end

```

Try it online!

I rarely golf in Ruby (tips appreciated) but I use it for work, and I liked Artemis's clean answer so much that I decided to see what a translation into ruby would look like.

# Answer
> 2 votes
# JavaScript, ~~52~~ 88 bytes

+36 bytes to handle a single fecking edge case :\

```
a=>a.map(a=>a.map(k=>o[0+k]=o[0+v]|v,v=a.pop()),o={})&&JSON.stringify(o).split`0`.join``

```

Try it online!

# Answer
> 2 votes
# Scala, 98 bytes

```
_./:(Map[String,String]()){case(m,a::b)=>val x=m.getOrElse(a,a);(m/:b.map(_->x))(_+_)case(m,_)=>m}

```

Try it online!

The statements have to be reversed (`List("2","b")` for "b=2"). The solutions below can't handle empty input.

# Scala, ~~96~~ 94 bytes

```
_./:(Map[String,String]()){(m,l)=>val x=m.getOrElse(l.last,l.last);(m/:l.init.map(_->x))(_+_)}

```

Try it online!

Takes a `List[List[String]]` and returns a `Map[String,String]`

## Scala, 86 bytes

This is shorter, but the statements are reversed

```
_./:(Map[String,String]()){case(m,a::b)=>val x=m.getOrElse(a,a);(m/:b.map(_->x))(_+_)}

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 85 bytes

```
G`=
+`=(.+(=.+))
$2¶$1
+rm`(^\4=(.+)¶(.+¶)*?.+=)(.+)$
$1$2
+m`^(.+)=.+¶((.+¶)*\1=)
$2

```

Try it online! Link includes test suite that converts the input from comma separated to newline separated assignments with no spaces. Explanation:

```
G`=

```

Ignore statements that have no assignments.

```
+`=(.+(=.+))
$2¶$1

```

Split up assignment chains into individual assignments.

```
+rm`(^\4=(.+)¶(.+¶)*?.+=)(.+)$
$1$2

```

Substitute the values of variables used on the right-hand side of assignments. The matching is performed right-to-left so that the most recent value is used.

```
+m`^(.+)=.+¶((.+¶)*\1=)
$2

```

Remove superseded assignments.

# Answer
> 1 votes
# Red, ~~74~~ 69 bytes

```
func[b][context collect[forall b[if set-word? first t: b/1[keep t]]]]

```

Try it online!

Takes the input as a list of lists, in each of them `=` replaced with `:` (Red has `set-words` rather than assignment operator)

# Answer
> 1 votes
# Java 10, 137 bytes

```
a->{var r=new java.util.TreeMap();for(var p:a)for(int l=p.length-1,i=l;i-->0;)r.put(p[i],p[l]instanceof Long?p[l]:r.get(p[l]));return r;}

```

Input as a Object-matrix (variables as Strings, values as Longs), output as a sorted HashMap.

Try it online.

**Explanation:**

```
a->{                            // Method with Object-matrix parameter & TreeMap return
  var r=new java.util.TreeMap();//  Create the result sorted HashMap
  for(var p:a)                  //  Loop over each Object-list of the input-matrix:
    for(int l=p.length-1,       //   Integer `l`, set to the last index of the list
        i=l;i-->0;)             //   Inner loop `i` in the range (length-1, 0]:
      r.put(                    //    Add to the result TreeMap:
         p[i],                  //     The `i`'th value of the list as key
         p[l]instanceof Long?   //     If the last item is a Long:
          p[l]                  //      Use that last item as value
         :                      //     Else:
          r.get(p[l]));         //      Get the value of this last item from the
                                //      result-Map, and use that as value
  return r;}                    //  Return the resulting TreeMap (sorted HashMap)

```

# Answer
> 1 votes
# , 172 bytes

Takes input as a list of strings, returns a named vector. Just `eval` in R with aggressive escaping using the `A` character.

```
function(i){i=paste(gsub('([a-z_])', 'A\\1',i)[grepl('=',i)],collapse=';')
eval(parse(text=i))
rm("i")
u=ls()
x=sapply(u,function(name)get(name))
names(x)=gsub('A','',u)
x}

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~30~~ 29 bytes

```
εRćÐþÊiU¯ʒXk_}θθ}δ‚€ˆ}¯.¡н}€θ

```

Ugh.. :/ Not the right language for the job.

Input as a list of lists.

Try it online or verify all test cases.

**Explanation:**

```
ε              # For each list in the (implicit) input-list:
 R             #  Reverse the list
  ć            #  Extract its head; pop and push remainder-list and first item separated
               #  to the stack
   Ð           #  Triplicate this value
    þ          #  Pop one copy, and only leave its digits
     Êi        #  If the top two copies are NOT the same (so it's not an integer):
       U       #   Pop and store the last copy in variable `X`
        ¯      #   Push the global_array
         ʒ     #   Filter it by:
          Xk   #    Where the index of `X`
            _  #    Is 0 (thus the key of the pair)
         }θ    #   After the filter: leave the last pair
           θ   #   Pop and leave its value
      }        #  Close the if-statement
       δ       #  For each value in the remainder-list:
        ‚      #   Pair it with the top value
         €     #  Then for-each pair in this list:
          ˆ    #   Add this pair to the global_array
}¯             # After the outer for-each: push the global_array
  .¡           # Group this list of pairs by:
    н          #  Its first value (the key)
   }€          # After the group-by: map over each group:
     θ         #  And only leave the last pair
               # (after which the top of the stack is output implicitly as result)

```

# Answer
> 1 votes
# Python 3, ~~69~~ 103 bytes

```
import re
def f(x):g={};exec(re.sub('(^|\n)[^=]+($|\n)','',x).upper(),{},g);return eval(str(g).lower())

```

Try it online!

+34 bytes to remove no-op lines in the input and avoid undefined variables

Takes advantage of the fact that no python keywords are uppercase, and variable names for this challenge will all be lowercase.

Saves several bytes thanks to a comment on my original (invalid) answer by @ovs:

> Note that your original answer could have been 35 bytes with exec(x,{},g), since exec does not add **builtins** to the locals dictionary. (This is still invalid)

# Answer
> 1 votes
# Perl 5 `-p`, 57 bytes

```
s/[a-z_]+/\$k{'$&'}/g;/=/&&eval}{say"$_=$k{$_}"for keys%k

```

Try it online!

# Answer
> 1 votes
# Pip `-rl`, 57 bytes

```
{YDQaIx~'^.y.,wYXI~$'Fva.sxR:'^.v.,`.+|^$`v.y.n}Mg^sUQx^n

```

Try it online!

Takes input (from stdin) and produces output (to stdout) as a series of lines, each of the form `a b c 5` (for `a = b = c = 5`). The output will have an extra blank line in it somewhere, which can be eliminated for +1 byte.

Pip is handicapped here by not having a dictionary/hashmap type. Our approach is to build the output as a string, using regex substitutions to update with new assignments. Further explanation available upon request, although I also hope to golf this more. Here's an earlier, pre-golfed version which may be easier to decipher.

# Answer
> 1 votes
# Haskell, ~~177~~ ~~145~~ 141 bytes

```
r t=f(?)[](reverse.words.filter(/='=')<$>lines t)
s?(x:y)=f(#)s y where z|Just v<-lookup x s=v|1<2=read x;s#k=(k,z):[x|x<-s,fst x/=k]
f=foldl

```

Try it online!

Ungolfed:

```
run :: Read v => String -> [(String, v)]
run input = foldl assign [] (reverse . words . filter (/='=') <$> lines input)

assign :: Read v => [(String, v)] -> [String] -> [(String, v)]
assign scope (first:keys) = foldl acons scope keys
  where value | Just v <- lookup first scope = v
              | otherwise = read first
        acons scope' k = (k, value) : [x | x <- scope', fst x /= k]

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 128 bytes

```
x=>{var z=new Dictionary<string,string>();x.ForEach(l=>{var s=l.Pop();l.Any(o=>(z[o]=z.ContainsKey(s)?z[s]:s)=="");});Print(z);}

```

Try it online!

# Answer
> 0 votes
# PHP, 65 bytes

```
eval(preg_filter('/([a-z_]+)/','\$$1',$argn));var_dump($GLOBALS);

```

Try it online!

Takes input as string with `;` as separator, outputs an array.

I'm not sure this is valid, as the rules for the output are not very precise: the result is present at the end, but there are other unnecessery things displayed before... For the first time PHP's `$` comes useful, as it allows to use keywords as var names (works with names such as `function`, `echo` etc)

---
Tags: code-golf, string
---