# Question
Title: Convert infix expressions to postfix notation
When I saw the title of this closed question, I thought it looked like an interesting code golf challenge. So let me present it as such:

### Challenge:

Write a program, expression or subroutine which, given an arithmetical expression in infix notation, like `1 + 2`, outputs the same expression in postfix notation, i.e. `1 2 +`.

(Note: A similar challenge was posted earlier in January. However, I do feel the two tasks are sufficiently different in detail to justify this separate challenge. Also, I only noticed the other thread after typing up everything below, and I'd rather not just throw it all away.)

### Input:

The input consists of a valid infix arithmetical expression consisting of **numbers** (non-negative integers represented as sequences of one or more decimal digits), balanced **parentheses** to indicate a grouped subexpression, and the four infix binary **operators** `+`, `-`, `*` and `/`. Any of these may be separated (and the entire expression surrounded) by an arbitrary number of space characters, which should be ignored.1

For those who like formal grammars, here's a simple BNF-like grammar that defines valid inputs. For brevity and clarity, the grammar does not include the optional spaces, which may occur between any two tokens (other than digits within a number):

```
expression     := number | subexpression | expression operator expression
subexpression  := "(" expression ")"
operator       := "+" | "-" | "*" | "/"
number         := digit | digit number
digit          := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

```

1 The only case where the presence of spaces may affect the parsing is when they separate two consecutive numbers; however, since two numbers not separated by an operator cannot occur in a valid infix expression, this case can never happen in valid input.

### Output:

The output should be a postfix expression equivalent to the input. The output expression should consist only of numbers and operators, with **a single space character** between each pair of adjacent tokens, as in the following grammar (which *does* include the spaces)2:

```
expression  := number | expression sp expression sp operator
operator    := "+" | "-" | "*" | "/"
number      := digit | digit number
digit       := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
sp          := " "

```

2 Again for simplicity, the `number` production in this grammar admits numbers with leading zeros, even though they're forbidden in the output by the rules below.

### Operator precedence:

In the absence of parentheses, the following precedence rules apply:

* The operators `*` and `/` have higher precedence than `+` and `-`.
* The operators `*` and `/` have equal precedence to each other.
* The operators `+` and `-` have equal precedence to each other.
* All operators are left-associative.

For example, the following two expressions are equivalent:

```
1 + 2 / 3 * 4 - 5 + 6 * 7
((1 + ((2 / 3) * 4)) - 5) + (6 * 7)

```

and they should both yield the following output:

```
1 2 3 / 4 * + 5 - 6 7 * +

```

(These are the same precedence rules as in the C language and in most languages derived from it. They probably resemble the rules you were taught in elementary school, except possibly for the relative precedence of `*` and `/`.)

### Miscellaneous rules:

* If the solution given is an expression or a subroutine, the input should be supplied and the output returned as a single string. If the solution is a complete program, it should read a line containing the infix expression from standard input and print a line containing the postfix version to standard output.
* Numbers in the input *may* include leading zeros. Numbers in the output *must not* have leading zeros (except for the number 0, which shall be output as `0`).
* You are not expected to evaluate or optimize the expression in any way. In particular, you should not assume that the operators necessarily satisfy any associative, commutative or other algebraic identities. That is, you should not assume that e.g. `1 + 2` equals `2 + 1` or that `1 + (2 + 3)` equals `(1 + 2) + 3`.
* You may assume that numbers in the input do not exceed 231 − 1 = 2147483647.

These rules are intended to ensure that the correct output is uniquely defined by the input.

### Examples:

Here are some valid input expressions and the corresponding outputs, presented in the form `"input" -> "output"`:

```
"1"                  ->  "1"
"1 + 2"              ->  "1 2 +"
" 001  +  02 "       ->  "1 2 +"
"(((((1))) + (2)))"  ->  "1 2 +"
"1+2"                ->  "1 2 +"
"1 + 2 + 3"          ->  "1 2 + 3 +"
"1 + (2 + 3)"        ->  "1 2 3 + +"
"1 + 2 * 3"          ->  "1 2 3 * +"
"1 / 2 * 3"          ->  "1 2 / 3 *"
"0102 + 0000"        ->  "102 0 +"
"0-1+(2-3)*4-5*(6-(7+8)/9+10)" -> "0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -"

```

(At least, I *hope* all these are correct; I did the conversion by hand, so mistakes might have crept in.)

Just to be clear, the following inputs are all invalid; it does *not* matter what your solution does if given them (although, of course, e.g. returning an error message is nicer than, say, consuming an infinite amount of memory):

```
""
"x"
"1 2"
"1 + + 2"
"-1"
"3.141592653589793"
"10,000,000,001"
"(1 + 2"
"(1 + 2)) * (3 / (4)"

```

# Answer
## Shell utils -- 60 chars

```
bc -c|sed -re's/[@iK:Wr]+/ /g;s/[^0-9]/ &/g;s/ +/ /g;s/^ //'

```

Fixed the various problems, but it got a lot longer :(
> 9 votes

# Answer
## C, 250 245 236 193 185 chars

```
char*p,b[99];f(char*s){int t=0;for(;*p-32?
*p>47?printf("%d ",strtol(p,&p,10)):*p==40?f(p++),++p:
t&&s[t]%5==2|*p%5-2?printf("%c ",s[t--]):*p>41?s[++t]=*p++:0:++p;);}
main(){f(p=gets(b));}

```

Here's a readable version of the ungolfed source, that still reflects the basic logic. It's actually a rather straightforward program. The only real work it has to do is to push a low-associativity operator onto a stack when a high-associativity operator is encountered, and then pop it back off at the "end" of that subexpression.

```
#include <stdio.h>
#include <stdlib.h>

static char buf[256], stack[256];
static char *p = buf;

static char *fix(char *ops)
{
    int sp = 0;

    for ( ; *p && *p != '\n' && *p != ')' ; ++p) {
        if (*p == ' ') {
            continue;
        } else if (*p >= '0') {
            printf("%ld ", strtol(p, &p, 10));
            --p;
        } else if (*p == '(') {
            ++p;
            fix(ops + sp);
        } else {
            while (sp) {
                if ((ops[sp] == '+' || ops[sp] == '-') &&
                        (*p == '*' || *p == '/')) {
                    break;
                } else {
                    printf("%c ", ops[sp--]);
                }
            }
            ops[++sp] = *p;
        }
    }
    while (sp)
        printf("%c ", ops[sp--]);
    return p;
}

int main(void)
{
    fgets(buf, sizeof buf, stdin);
    fix(stack);
    return 0;
}

```
> 4 votes

# Answer
# Python 2, ~~290~~ ~~272~~ ~~268~~ ~~250~~ ~~243~~ 238 bytes

Now finally shorter than the JS answer!

This is a full program which uses a basic implementation of the shunting yard algorithm. Input is given as a quoted string, and the result is printed to `STDOUT`.

```
import re
O=[];B=[]
for t in re.findall('\d+|\S',input()):exec("O=[t]+O","i=O.index('(');B+=O[:i];O=O[i+1:]","while O and'('<O[0]and(t in'*/')<=(O[0]in'*/'):B+=O.pop(0)\nO=[t]+O","B+=`int(t)`,")[(t>'/')+(t>')')+(t>'(')]
print' '.join(B+O)

```

### **Try it online!**

---

**Explanation:**

The first thing we need to do is convert the input into tokens. We do this using by finding all matches of the regex `\d+|\S`, roughly translated to "any group of digits, and any non-space character". This removes whitespace, parses adjacent digits as single tokens, and parses operators seperately.

For the shunting yard algorithm, there are 4 distinct token types we need to handle:

* `(` \- Left parenthesis
* `)` \- Right parenthesis
* `+-*/` \- Operators
* `9876543210` \- Numeric literals

Thankfully, the ASCII codes of these are all grouped in the order shown, so we can use the expression `(t>'/')+(t>')')+(t>'(')` to calculate the token type. This results in **3** for digits, **2** for operators, **1** for a right parenthesis and **0** for a left parenthesis.

Using these values, we index into the large tuple after `exec` to get the corresponding snippet to execute, based on the token type. This is different for each token and is the backbone of the shunting yard algorithm. Two lists are used (as stacks): `O` (operation stack) and `B` (output buffer). After all the tokens have been run, the remaining operators on the `O` stack are concatenated with the output buffer, and the result is printed.
> 3 votes

# Answer
## Bash w/ Haskell w/ ~~C preprocessor~~ sed, 180 ~~195~~ ~~198~~ ~~275~~

```
echo 'CNumO+O-O*fromInteger=show
CFractionalO/
main=putStr$'$*|sed 's/C\([^O]*\)/instance \1 String where /g
s/O\(.\?\)/a\1b=unwords\[a,b,\"\1\"];/g'|runghc -XFlexibleInstances 2>w

```

At last, it's not longer than the C solution anymore. The crucial Haskell part is almost as lazy as the bc solution...

Takes input as command-line parameters. A file `w` with some ghc warning messages will be created, if you don't like this change to `runghc 2>/dev/null`.
> 2 votes

# Answer
# Prolog (SWI-Prolog), 113 bytes

```
c(Z,Q):-Z=..[A,B,C],c(B,S),c(C,T),concat_atom([S,T,A],' ',Q);term_to_atom(Z,Q).
p(X,Q):-term_to_atom(Z,X),c(Z,Q).

```

Try it online!

SWI Prolog has a much better set of builtins for this than GNU Prolog does, but it's still held back somewhat by the verbosity of Prolog's syntax.

## Explanation

`term_to_atom` will, if run backwards, parse an infix-notation expression (stored as an atom) into a parse tree (obeying the usual precedence rules, and deleting leading zeroes and whitespace). We then use the helper predicate `c` to do a structural recursion over the parse tree, converting into postfix notation in a depth-first way.
> 2 votes

# Answer
## Javascript (ES6), 244 bytes

```
f=(s,o={'+':1,'-':1,'*':2,'/':2},a=[],p='',g=c=>o[l=a.pop()]>=o[c]?g(c,p+=l+' '):a.push(l||'',c))=>(s.match(/[)(+*/-]|\d+/g).map(c=>o[c]?g(c):(c==')'?eval(`for(;(i=a.pop())&&i!='(';)p+=i+' '`):c=='('?a.push(c):p+=+c+' ')),p+a.reverse().join` `)

```

**Example:**
Call: `f('0-1+(2-3)*4-5*(6-(7+8)/9+10)')`
Output: `0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -`  (with a trailing space)

**Explanation:**

```
f=(s,                                                     //Input string
    o={'+':1,'-':1,'*':2,'/':2},                          //Object used to compare precedence between operators
    a=[],                                                 //Array used to stack operators
    p='',                                                 //String used to store the result
    g=c=>                                                 //Function to manage operator stack
        o[l=a.pop()]>=o[c]?                               //  If the last stacked operator has the same or higher precedence
            g(c,p+=l+' '):                                //  Then adds it to the result and call g(c) again
            a.push(l||'',c)                               //  Else restack the last operator and adds the current one, ends the recursion.
)=>
    (s.match(/[)(+*/-]|\d+/g)                             //Getting all operands and operators
    .map(c=>                                              //for each operands or operators
        o[c]?                                             //If it's an operator defined in the object o
            g(c)                                          //Then manage the stack
            :(c==')'?                                     //Else if it's a closing parenthese
                eval(`                                    //Then
                    for(;(i=a.pop())&&i!='(';)            //  Until it's an opening parenthese
                        p+=i+' '                          //  Adds the last operator to the result
                `)
                :c=='('?                                  //Else if it's an opening parenthese
                    a.push(c)                             //Then push it on the stack
                    :p+=+c+' '                            //Else it's an operand: adds it to the result (+c removes the leading 0s)
        )
    )
    ,p+a.reverse().join` `)                               //Adds the last operators on the stack to get the final result

```
> 1 votes

# Answer
# R, 142 bytes

R is able to parse itself, so rather than re-invent the wheel, we just put the parser to work, which outputs prefix notation, and use a recursive function to switch it to postfix notation.

```
f=function(x,p=1){
if(p)x=match.call()[[2]]
if((l=length(x))>1){
f(x[[2]],0)
if(l>2)f(x[[3]],0)
if((z=x[[1]])!="(")cat(z,"")
}else cat(x,"")
}

```

The `p` argument is to control the use of non-standard evaluation (the bane of R programmers everywhere), and there are a few extra `if`s in there to control the outputting of brackets (which we want to avoid).

Input: `(0-1+(2-3)*4-5*(6-(7+8)/9+10))`

Output: `0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -`

Input: `(((((1))) + (2)))`

Output: `1 2 +`

As a bonus, it works with arbitrary symbols, and any pre-defined functions with up to two arguments:

### Euler's identity

Input: `e^(i*pi)-1`

Output: `e i pi * ^ 1 -`

### Dividends of 13 between 1 and 100

Input: `which(1:100 %% 13 == 0)`

Output: `1 100 : 13 %% 0 == which`

### Linear regression of baby chicken weight as a function of time

Input: `summary(lm(weight~Time, data=ChickWeight))`

Output: `weight Time ~ ChickWeight lm summary`

The last example is perhaps a little outside the scope of the OP, but it does use postfix notation, so...
> 1 votes

# Answer
# Perl 5, 177 bytes

Exploiting Perl operator overloading:

```
sub{use overload nomethod=>sub{bless[@_[3,0,1]]};sub new{shift;bless[0,@_]}sub p{$_[0][0]?join$",(map$_[0][$_]->p,1,2),$_[0][0]:$_[0][1]}eval(pop=~s/0*(\d+)/new main($1)/gr)->p}

```

Try it online!
> 1 votes

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


# Question
Title: Find the absolute minimum difference between 2 divided numbers from n
## Input:

An integer `n`

## Output:

A string `A * B`

## Example

`12`

Possible 2 divisible numbers: `12 * 1`, `6 * 2`, `4 * 3`

```
12-1 = 11

6-2 = 4

4-3 = 1

```

4 and 3 has the minimal absolute difference of 1

Therefore, Output:

`4 * 3`

*Order of the numbers does **not** matter*

*This challenge idea was taken from a puzzle in Clash of Code in https://www.codingame.com*

This is , so shortest answer in bytes wins!

# Answer
# Vyxal, 11 bytes

```
KḂZµƒε;h×YṄ

```

Try it Online!

-2 thanks to lyxal

```
K           # Factors
 ḂZ         # Zipped with reverse
   µ  ;h    # Minimum by
    ƒε      # Reduced by abs. diff.
        ×Y  # Interleave with '*'
          Ṅ # Join by spaces

```
> 2 votes

# Answer
# Python 2, 74 bytes

```
def f(x):q=[i for i in range(1,1+x)if x%i<1];q=q[len(q)/2];print q,"*",x/q

```

Try it online!
> 3 votes

# Answer
# Python 2, 55 bytes

```
f=lambda n,m=1:n%m|(m*m<n)and f(n,m+1)or`n/m`+" * "+`m`
```

Attempt This Online!
> 3 votes

# Answer
# Jelly, 13 bytes

```
ÆDżU$ạ/ÞḢj”*K

```

Try It Online!

-1 byte thanks to a golf from lyxal ported by emanresu A
-1 byte thanks to emanresu A

```
ÆDżU$ạ/ÞḢj”*K  Main Link
ÆD             Divisor List
  żU$          Interleaved with its reverse
       Þ       Sorted by
     ạ/        Absolute Difference
        Ḣ      Get the first one
         j”*   Join on "*"
            K  Join on spaces

```
> 2 votes

# Answer
# Python, 104 bytes

```
lambda n:'%d * %d'%min([(x,n/x)for x in[i for i in range(1,n)if(n/i)%1==0]],key=lambda x:abs(x[0]-x[1]))

```

Try it Online!
> 1 votes

# Answer
# Python, 96 bytes

```
f=lambda x:(lambda y:str(z:=y[len(y)//2])+" * "+str(x//z))([i for i in range(1,x) if x/i==x//i])

```
> 0 votes

# Answer
# JavaScript (Node.js), 52 bytes

```
f=(n,i=n**.5|(-n)**.5)=>n%i?f(n,i+1):i+' * '+(n/i|0)

```

Try it online!

---

# JavaScript (Node.js), 41 bytes

```
f=(n,i=n**.5|0)=>n%i?f(n,i+1):i+' * '+n/i

```

Try it online!

For positive number only.
> 0 votes

# Answer
# Factor \+ `math.primes.factors`, 73 bytes

```
[ divisors dup reverse zip [ first2 - abs ] infimum-by "%d * %d"vprintf ]

```

Try it online!

```
                            ! 12
divisors                    ! { 1 2 3 4 6 12 }
dup                         ! { 1 2 3 4 6 12 } { 1 2 3 4 6 12 }
reverse                     ! { 1 2 3 4 6 12 } { 12 6 4 3 2 1 }
zip                         ! { { 1 12 } { 2 6 } { 3 4 } { 4 3 } { 6 2 } { 12 1 } }
[ first2 - abs ] infimum-by ! { 3 4 }
"%d * %d"vprintf            !

```
> 0 votes

# Answer
# Pari/GP, 38 bytes

```
n->vecmin([abs(d-n/d)|d<-divisors(n)])

```

Try it online!
> 0 votes

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


title: Morse code translator

text:
# Question
Title: Morse code translator
Write the shortest program to transform the standard input into Morse code. Characters not in the table should be printed as they are.

# Answer
> 12 votes
## Golfscript - 74 chars

This answer supports only uppercase and digits. The letters are separated by newlines and words are separated by 2 newlines

```
{." ETIANMSURWDKGOHVF L PJBXCYZQ"?)"?/'#! 08<>"@))10%=or 2base(;{!45+}%n}%

```

Analysis

```
    { }%          as usual works like a map over the array
    .             push a copy of the char onto the stack
    " ETIAN..."   this is a lookup table for the uppercase characters
    ?             like a string.find returns the index of the char in the string
                  or -1 if it is not found (ie it's a digit)
    )             increment that index so E=>2 T=>3 I=>4 etc. notice that if the
                  char is not an uppercase letter or space this is now 0 (False)
    "?/'#!..."    this is a lookup table for the digits. it will be used in the
                  reverse way to the other lookup table.
    @             pull that copy we made of the char to the top of the stack
    ))%10         convert ascii digit to a number by adding 2 and taking mod 10.
                  It's important to do it this way because all the uppercase
                  letters hit this code too, and we need to make sure they fall
                  in the range 0..9 or the next step will fail.
    =             pull the nth char from the string eg "Hello"1= gives "e"
    or            remember if the uppercase lookup fails we have a 0 result, so
                  the digit lookup will be used
    2base         convert to base 2 so E=>[1 0], T=>[1 1], I=>[1 0 0] etc.
    (;            pop the front of the list and throw it away so E=>[0], T=>[1]
    {!45+}%       negate each bit and add 45, this gives ascii value of . and -
    n             newline separates each word. this could be 32 if you wanted to
                  separate the words with spaces for a cost of 1 stroke

```

**Golfscript - 85 chars**

This is shorter than my SO answer due to the relaxed requirements here The input must be uppercase/digits and the punctuation characters ".,?"

```
{." ETIANMSURWDKGOHVF!L!PJBXCYZQ"?)"UsL?/'#! 08<>"@".,?"58,48>+?=or
2base(;{!45+}%n}%

```

Since the punctuation is not even required here, I may shorten the answer even more

My answer from SO
**Golfscript - 107 chars**

newline at the end of the input is not supported, so use something like this

`echo -n Hello, Codegolfers| ../golfscript.rb morse.gs`

Letters are a special case and converted to lowercase and ordered in their binary positions. Everything else is done by a translation table

```
' '/{{.32|"!etianmsurwdkgohvf!l!pjbxcyzq"?)"UsL?/'#! 08<>"@".,?0123456789"?=or
2base(;>{'.-'\=}%' '}%}%'/'*

```

# Answer
> 21 votes
**C# (213 characters)**

I'm sure this wont stand long, but at least I got the technique here first!

```
class P{static void Main(string[] a){foreach(var t in a[0]){var c="";for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;System.Console.Write(c+"  ");}}}

```

And in readable format:

```
class P
{
    static void Main(string[] a)
    {
        foreach(var t in a[0])
        {
            var c="";
            for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;
            System.Console.Write(c+" ");
        }
    }
}

```

For a brief explanation, the string of characters is a heap in which the left child is a dot and the right child is a dash. To build the letter, you traverse back up and reverse the order.

# Answer
> 9 votes
### tr + sed (347)

```
tr a-z A-Z | sed 's/0/--O/g;s/1/.-O/g;s/2/.J/g;s/3/..W/g;s/4/.V/g;s/5/.H/g;
 s/6/-.H/g;s/7/-B/g;s/8/-Z/g;s/9/--G/g;s/X/-U/g;s/V/.U/g;s/U/.A/g;
 s/Q/-K/g;s/K/-A/g;s/A/.T/g;s/J/.O/g;s/O/-M/g;s/Y/-W/g;s/W/.M/g;
 s/M/-T/g;s/T/- /g;s/H/.S/g;s/B/-S/g;s/S/.I/g;s/L/.D/g;s/Z/-D/g;
 s/D/-I/g;s/I/.E/g;s/C/-R/g;s/F/.R/g;s/R/.N/g;s/P/.G/g;s/G/-N/g;
 s/N/-E/g;s/E/. /g'

```

# Answer
> 6 votes
## Haskell — ~~314~~ ~~292~~ 291 characters

```
import Data.List
i=intercalate
m=i"       ".map(i" ".map(\c->words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."!!(head.findIndices(==c)$['a'..'z']++['0'..'9']))).words

```

---

A more user readable form:

```
tbl :: [String]
tbl = words ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."

lookupChar :: Char -> String
lookupChar c = tbl !! (fromJust . elemIndex c $ ['a'..'z'] ++ ['0'..'9'])

encWord :: String -> String
encWord = intercalate " " . map lookupChar

encSent :: String -> String
encSent = intercalate "       " . map encWord . words

```

Sample run:

```
*Main> m "welcome humans"
".-- . .-.. -.-. --- -- .       .... ..- -- .- -. ..."

```

There's a single whitespace between two letters, and seven whitespaces between two words.

# Answer
> 5 votes
## VB.NET, 233 bytes

```
Module Module1
 Sub Main(a$())
   For Each c In a(0)
     Dim i = "ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(c)
     If c <> " " And i >= 0 Then
       Console.Write("{0} ", Morse(i))
     Else
       Console.Write(c)
     End If
   Next
End Sub

Function Morse(i) As String
  Dim b = Math.Log(i) / Math.Log(2)
  Return (From m In MorseSeq(If(Double.IsInfinity(b), 0, b)) Order By m.Length)(i)
End Function

Function MorseSeq(i) As IEnumerable(Of String)
  Return If(i < 0, {}, From n In ".-" From m In MorseSeq(i - 1).DefaultIfEmpty
                       Select n & m)
End Function
End Module

```

That last function is evil.

**edit** A couple of improvements.

```
Function Morse(i) As String
  Return (From m In MorseSeq(i) Order By m.Length)(i)
End Function

Function MorseSeq(i) As IEnumerable(Of String)
  Return If(i=0,{".","-"},From n In".-"From m In MorseSeq(i>>1) Select n & m)
End Function

```

# Answer
> 4 votes
## Ruby, 161

```
d=proc{|x|x>1?d[x/2]+".-"[x&1]:' '}
$><<$<.gets.bytes.map{|i|
e=i>64?"-@B4*:68,?5</.7>E20+193ACD"[(i&95)-65]:i>47?"gWOKIHX`df"[i-48]:nil
e ?d[e.ord-40]:i.chr}*''

```

Encodes each digit into a single char, where 1 is dash, 0 is dot, with a leading 1 as a marker bit (plus an offset to keep it printable. Uses ASCII math to use the input chars as lookup indices.

# Answer
> 4 votes
**Postscript ~~(310)~~ ~~(462)~~ ~~(414)~~ (319)** including **(46)** for the table.

Combined numbers and letters with a ternary encoding. 5 ternary digits fit in a byte! This eliminates those silly difference loops, and special-casing numbers entirely.

ASCII85 cuts 1/3 of each table. And simplifying the code (finally!) gets back under 400!

```
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put<</*{{[exch/@ cvx]cvx 1
index 1 add}forall pop}def/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def/#{load
exec}/P{print}0{}1{(.)P}2{(---)P}/S{( )P}48<~o'u/0b'A;]L7n~>* 65 C 97 C/@{5{dup
3 mod # S 3 idiv}repeat # S S S}>>begin{(%stdin)(r)file read not{exit}if #}loop

```

Sample output

```
Luser Dr00g!
. --- . .     . . ---      . . .      .        . --- .          --- . .      . --- .      --- --- --- --- ---    --- --- --- --- ---    --- --- .      !

```

Ungolfed and commented. I'm very proud of this one. I feel it's *elegant,* making the numbers do the work. :)

```
%!
%Morse Code Translator (Simplified)

%if `load` signals /undefined in /#{load exec},
%  pop --load--,
%  print the char,
%  leave dummy object for `exec` to find
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put

<<
%create int->proc pairs
%from initial int and string values
/*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def

%the alpha map is applied to Upper and Lower case
/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def
65 C 97 C

%the number map
48<~o'u/0b'A;]L7n~>*

/#{load exec}  %execute a number
/P{print}

0{}       % 0: nop
1{(.)P}   % 1: '.' dit
2{(---)P} % 2: '---' dah
/S{( )P}  % S: space

%execute a morse sequence, from the table
/@{5{dup 3 mod # S 3 idiv}repeat # S S S}
>>begin

%read and execute each char from stdin
{(%stdin)(r)file read not{exit}if #}loop

```

**The tables (33)+(13)=(46)**

Here's how the strings encode the table. Each byte represents a 5-digit ternary number. And the bytes are further encoded in ASCII85 (which postscript can automagically decode).

```
%The Morse Table in Ternary Encoding
% 3  ^4 ^3 ^2 ^1 ^0
%    81 27  9  3  1                 Dec  Hex  dc ->ASCII85
%   ---------------                 ---  ---  ---
% A            2  1            6+1    7    7  7 256*41+256*50+256*14+
% B      1  1  1  2      27+ 9+3+2   41   29  d85%n85/d85%n85/d85%n85/d85%n85/n
% C      1  2  1  2      27+18+3+2   50   32  2 25 53 35 27  chr(x+33)
% D         1  1  2          9+3+2   14    E  #  :  V  D  <
% E               1              1    1    1
% F      1  2  1  1      27+18+3+1   49   31
% G         1  2  2          9+6+2   17   11  0 32 47 15 22
% H      1  1  1  1      27+ 9+3+1   40   28  !  A  P  0  7
% I            1  1            3+1    4    4
% J      2  2  2  1      54+18+6+1   79   4F
% K         2  1  2         18+3+2   23   17  1 32 60 70 64
% L      1  1  2  1      27+ 9+6+1   43   2B  "  A  ]  g  a
% M            2  2            6+2    8    8
% N            1  2            3+2    5    5
% O         2  2  2         18+6+2   26   1A  2 49 8 11 6
% P      1  2  2  1      27+18+6+1   52   34  #  R )  , '
% Q      2  1  2  2      54+ 9+6+2   71   47
% R         1  2  1          9+6+1   16   10
% S         1  1  1          9+3+1   13    D  22 71 30 10 17
% T               2              2    2    2   7  h  ?  +  2
% U         2  1  1         18+3+1   22   16
% V      2  1  1  1      54+ 9+3+1   67   43
% W         2  2  1         18+6+1   25   19  7 13 14 82 12
% X      2  1  1  2      54+ 9+3+2   68   44  (  .  /  s  -
% Y      2  2  1  2      54+18+3+2   77   4D  77 256*44+256*256*
% Z      1  1  2  2      27+ 9+6+2   44   2C  24 68 21 [23 36]
%                                              9  e  6 [ 8  E] (omit final 2)
% 0   2  2  2  2  2  162+54+18+6+2  242   F2
% 1   2  2  2  2  1  162+54+18+6+1  241   F1
% 2   2  2  2  1  1  162+54+18+3+1  238   EE  78 6 84 14 15
% 3   2  2  1  1  1  162+54+ 9+3+1  229   E5   o '  u  /  0
% 4   2  1  1  1  1  162+27+ 9+3+1  202   CA
% 5   1  1  1  1  1   81+27+ 9+3+1  121   79
% 6   1  1  1  1  2   81+27+ 9+3+2  122   7A  65 6 32 26 60
% 7   1  1  1  2  2   81+27+ 9+6+2  125   7D   b '  A  ;  ]
% 8   1  1  2  2  2   81+27+18+6+2  134   86  134 256*161+256*256*
% 9   1  2  2  2  2   81+54+18+6+2  161   A1  43 22 77 [50 40]
%                                              L  7  n [ S  I] (omit final 2)

```

# Answer
> 4 votes
# Python 3, 99 Characters

```
lambda a:print(*[str(ord('ӆҼzࢤpࢮ࠿yࡊoࡀѡÔÞÝࢭÓӅһѢ'[ord(c)%32])).translate(' -.'*18)for c in a])

```

Works on upper and lowercase.

# Answer
> 3 votes
**Lisp (532 466 chars)**

```
(loop(princ(let((c(read-char)))(case 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"--.. ")(#\1".---- ")(#\2"..--- ")(#\3"...-- ")(#\4"....- ")(#\5"..... ")(#\6"-.... ")(#\7"--... ")(#\8"---.. ")(#\9"----. ")(#\0"----- ")(t c)))))

```

This encodes lower case letters, and morse code sequences are printed with a trailing space

# Answer
> 3 votes
**In Java, 475 characters.**

```
    import java.io.*;class M{public static void main(String[]b){String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}}

```

Translates a-z, A-Z and 0-9.

Edit:

Or in **447** characters, if you don't mind Java throwing an error after the translation.

```
    import java.io.*;class M{static{String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}}

```

# Answer
> 3 votes
Perl6 (238)

```
my%h="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--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.".split(/<wb>/)[1..72];while$*IN.getc ->$c{print %h{$c.uc}||$c}

```

Readable version

```
# Split string on word breaks to create a hash
# I get an extra token at the beginning and end for some reason
# [1..72] is a slice without the extra pieces
my %h = "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--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----."
    .split(/<wb>/)[1..72];

# For each character in STDIN, print either the looked up value, or itself
while $*IN.getc -> $c {
    print %h{$c.uc} || $c;
}

```

# Answer
> 2 votes
## C, ~~162~~ 160 chars

```
char M[256] = "_^\\XP@ACGO       &15)\"4+0$>-2'%/6;*(#,8.9=3", v;
main(c) {
  for (;
         c = getchar(), v = M[c + 208 & 255] - 32, ~c;
         putchar(v-1? c : 32))
    for (; v > 1; v /= 2) putchar(".-"[v & 1]);
}

```

(With non-significant whitespace stripped, no trailing newline)

```
char M[256]="_^\\XP@ACGO       &15)\"4+0$>-2'%/6;*(#,8.9=3",v;main(c){for(;c=getchar(),v=M[c+208&255]-32,~c;putchar(v-1?c:32))for(;v>1;v/=2)putchar(".-"[v&1]);}

```

`M` is a lookup table where the characters' bitpatterns correspond to dots and dashes in the morse code. Characters `[0-9A-Z]` are decoded to morse using this table (with a space appended after the morse code), other characters are simply passed through unchanged.

Sample run:

```
HELLO WORLD
.... . .-.. .-.. ---  .-- --- .-. .-.. -..
hello world
hello world
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----.

```

# Answer
> 2 votes
# sed, 159 bytes

```
s/.*/\L&/
s/[02]/&-/g
s/[89]/&./g
:
s/[b-ilnprsz5-9]/&./g
s/[ajkmoqt-y0-4]/&-/g
y/abcdefghijklmnopqrstuvwxyz0123456789/edri umsewnrttmwkai isadkgojuvhhbzoo/
t

```

We start by downcasing the entire line (because `y` can't do case-insensitive conversions); subtract 10 bytes if we are to only handle lower-case input. Then we preprocess the digits `0`, `2`, `8` and `9` to emit their final symbols.

The loop generates the final symbol for each input character, then translates each character for the next iteration. This is equivalent to walking up the dichotomic search table shown in the Wikipedia article; the digits that needed special treatment can be seen to have parents that are not in our ASCII alphanumerics.

The loop terminates when all characters have reached the terminating space (after 'e' or 't').

For example, the letter `k` is transformed in three passes:

1. `k` =\> `k-` =\> `n-`
2. `n-` =\> `n.-` =\> `t.-`
3. `t.-` =\> `t-.-` =\>  `-.-`

# Answer
> 2 votes
# Powershell, 142 bytes

```
-join($args|% t*y|%{if($_-match'\w'){for($d='ihfbZJKMQY+mazzy+0;?3,>5:.H7<1/9@E42-6B8CG='[$_-48]-42;$d-1){'.-'[$d%2]
$d=$d-shr1}' '}else{$_}})

```

Less golfed test script:

```
$f = {

-join(
    $args|% toCharArray|%{
        if($_-match'\w'){
            for($d='ihfbZJKMQY+mazzy+0;?3,>5:.H7<1/9@E42-6B8CG='[$_-48]-42;$d-1){
                '.-'[$d%2]
                $d=$d-shr1
            }
            ' '
        }else{
            $_
        }
    }
)

}

@(
    ,("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. ")
    ,("HELLO WORLD", ".... . .-.. .-.. ---  .-- --- .-. .-.. -.. ")
    ,("#$%^&","#$%^&")
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----.
True: .... . .-.. .-.. ---  .-- --- .-. .-.. -..
True: #$%^&

```

Note: The output contains trailing spaces.

# Answer
> 2 votes
# JavaScript (ES6), 184 bytes

For both of these versions, they will put spaces between any characters. Converts 0-9 and a-z(case insensitive) are converted. A space is converted to 3.

```
s=>s.split("").map(e=>isNaN(d=parseInt(e.toLowerCase(),36))?e:`_OGCA@PX\\^\r\n  `.charCodeAt(d).toString(2).substr(1).split("").map(e=>".-"[e]).join("")).join(" ")

```

Replace `\n` with a newline character(`0x0a`). It is not showing a couple of nonprintable characters because of SE. Going into edit mode shows it.

Here is the hex:

```
73 3d 3e 73 2e 73 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 65 3d 3e 69 73 4e 61 4e 28 64 3d 70 61 72 73 65 49 6e 74 28 65 2e 74 6f 4c 6f 77 65 72 43 61 73 65 28 29 2c 33 36 29 29 3f 65 3a 60 5f 4f 47 43 41 40 50 58 5c 5c 5e 05 18 1a 0c 02 12 0e 10 04 17 5c 72 14 07 06 0f 16 1d 0a 08 03 09 11 0b 19 1b 1c 60 2e 63 68 61 72 43 6f 64 65 41 74 28 64 29 2e 74 6f 53 74 72 69 6e 67 28 32 29 2e 73 75 62 73 74 72 28 31 29 2e 73 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 65 3d 3e 22 2e 2d 22 5b 65 5d 29 2e 6a 6f 69 6e 28 22 22 29 29 2e 6a 6f 69 6e 28 22 20 22 29

```

### Ungolfed

```
s=>            //declare anonymous function
s.split("")    //split into array of characters
.map(          //for each character
e=>            //declare anonymous function
 isNaN(        //is the character not in range 0-9a-zA-Z
  d=parseInt(e.toLowerCase(),36)
               //take it as base 36(digits are 0-9a-z) and assign to d
 )?e:          //if outside range, return as is
 `_OGCA@PX\\^\r\n  `
               //table of the morse code as binary as code point with leading 1
 .charCodeAt(d)//get the corresponding code
 .toString(2)  //convert to binary, 0=., 1=-, with an extra 1 bit
 .substr(1)    //remove the extra 1 bit
 .split("")    //split into each bit
 .map(         //for each bit
  e=>          //declare anonymous function
  ".-"         //the corresponding symbol for bits
  [e]          //get it
 )
 .join("")     //join the bits
)
.join(" ")     //join the characters with a space between each character

```

## Readable version, 234 bytes

```
s=>s.split("").map(e=>isNaN(d=parseInt(e.toLowerCase(),36))?e:[95,79,71,67,65,64,80,88,92,94,5,24,26,12,2,18,14,16,4,23,13,20,7,6,15,22,29,10,8,3,9,17,11,25,27,28][d].toString(2).substr(1).split("").map(e=>".-"[e]).join("")).join(" ")

```

### Ungolfed

```
s=>            //declare anonymous function
s.split("")    //split into array of characters
.map(          //for each character
e=>            //declare anonymous function
 isNaN(        //is the character not in range 0-9a-zA-Z
  d=parseInt(e.toLowerCase(),36)
               //take it as base 36(digits are 0-9a-z) and assign to d
 )?e:          //if outside range, return as is
 [95,79,71,67,65,64,80,88,92,94,
   5,24,26,12, 2,18,14,16, 4,23,
  13,20, 7, 6,15,22,29,10, 8, 3,
   9,17,11,25,27,28]
               //table of the morse code as binary with leading 1
 [d]           //get the corresponding code
 .toString(2)  //convert to binary, 0=., 1=-, with an extra 1 bit
 .substr(1)    //remove the extra 1 bit
 .split("")    //split into each bit
 .map(         //for each bit
  e=>          //declare anonymous function
  ".-"         //the corresponding symbol for bits
  [e]          //get it
 )
 .join("")     //join the bits
)
.join(" ")     //join the characters with a space between each character

```

# Answer
> 1 votes
## Perl (489 chars)

```
%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"=>"--..",1=>".----",2=>"..---",3=>"...--",4=>"..---",5=>".....",6=>"-....",7=>"--...",8=>"---..",9=>"----.",0=>"-----");while(<>){foreach(split(//)){if(exists($c{$_})){printf"%s ",$c{$_}}else{print"$_"}}}

```

Can be executed via command line like so.

```
$ perl -e '$CODE' < textfile

```

Edit: Thanks @tobyodavies for pointing out that my original solution had the translation backwards!

# Answer
> 1 votes
## PHP, 474 characters

```
<?$a=strtoupper(fgets(STDIN));$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])];

```

Its 462 characters if all input is in uppercase:

```
<?$a=fgets(STDIN);$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])];

```

# Answer
> 1 votes
# 05AB1E, 81 bytes (Non-competing)

```
Çvy©58‹i®58-•6V%·,Õo•2B5ôsè}®64›i®64-•4…·]ÑUZ“×\ó$9™¹“ÌLÈÎ%´•3B4ôsè}"012"".- "‡})

```

Try it online!

Convert letter patterns to base-3, number patterns to base-2, use zero indexed ascii transliteration to get to periods and hyphens. Does not work on lowercase.

# Answer
> 1 votes
# Jelly, 50 bytes

```
“¤⁵©ḤọḌṄ’B‘s5;“ḄẇɗÞI/QẊṂjỵr’Œ?ḃ2¤ṖṖƊ⁺ị⁾.-;
ØBiịÇ)K

```

A full program accepting a Python formatted string as a command line argument which prints space delimited output.

**Try it online!**

# Answer
> 1 votes
# APL(NARS), 71 chars, 142 bytes

```
{36≥y←⍵⍳⍨⎕A,⎕D:'•-'[0∼⍨⌽(5⍴3)⊤y⊃∊(2⍴256)∘⊤¨⎕AV⍳'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠']⋄⍵}

```

test:

```
  q←{36≥y←⍵⍳⍨⎕A,⎕D:'•-'[0∼⍨⌽(5⍴3)⊤y⊃∊(2⍴256)∘⊤¨⎕AV⍳'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠']⋄⍵}
  q¨'0123456789'
----- •---- ••--- •••-- ••••- ••••• -•••• --••• ---•• ----•
  q¨"HELLO WORLD"
•••• • •-•• •-•• ---   •-- --- •-• •-•• -••

```

each letter is separated from one space, each word would be separated from 3 spaces. The table is build on alphanumeric string `⎕A,⎕D` and 16bit characters `'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠'` they split in 8bit characters each converted in base 3 with reversed digits.

# Answer
> 1 votes
# 05AB1E, 52 bytes

```
Ažh«•1Ju&àøΘn₆δβαLmSÂZΘ=+BD1
 ÷ΓùwÒмVšh•… .-ÅвJ#ðδJ‡

```

Try it online!

```
    •1Ju&àøΘn₆δβαLmSÂZΘ=+BD1
    ÷ΓùwÒмVšh•                push compressed number
              … .-ÅвJ#        convert to custom base " .-"
                      ðδJ     append a space to each morse code
Ažh«                     ‡    transliterate

```

# Answer
> 1 votes
# Vyxal, 56 bytes

```
ka»ƛ[¬τ*‹∧□C‛Ṡḣ6ƒO⌈=gṫO=D»`-.,`τ⌐Ŀkd5ɾ\.*5ʁṘ-:ƛ‛.-ḂĿ;JĿṄ

```

Try it Online!

```
  »...»                               # Base-256 compressed integer
       `-.,`τ⌐                        # Decompressed with the key `-.,`and split on commas
ka            Ŀ                       # Replace letters with those
                 5ɾ\.*                # 1..5 .
                      5ʁṘ-            # With 4..0 - appended
                          :ƛ‛.-ḂĿ;J   # Make a copy with `.-` swapped
               kd                  Ŀ  # Replace digits with those
                                    Ṅ # Join on spaces and implicitly output

```

# Answer
> 0 votes
# Python 2, ~~283~~ 274 Bytes

I created a string of alphanumerics such that their placement in the string describes their Morse code representation. Originally I was going to use binary, but `01` would be the same as `1`. So I used ternary with `- = 1` and `. = 2`. Thus is character `c` is at index `1121` in this string, its Morse code representation is `--.-`.

* To save bytes, I created variables for space, dash and dot.
* Then I hard coded the 'decoder' string using a couple replace statements to reduce whitespace.
* The part of the function converts an index into an array of the ternary digits
* The other part function takes an string and converts each character into Morse code with 3 spaces after letters and 7 (4 extra) between words

```
q,d,D=" .-"
s=" TE MN AI.OG KD.WR US-.QZ.YC XB- JP  L. F VH---.09  8..7--  6---.1--  2..3  45".replace(D,d*3).replace(d,q*4)
lambda n:''.join(''.join([0,D,d][i]for i in [s.index(c)//3**i%3 for i in range(5)if s.index(c)//3**i!=0][::-1])+q*3 if c!=q else q*4for c in n.upper())

```

**Test Harness**

```
print(f("Hi")=="....   ..   ")
print(f("Hello")=="....   .   .-..   .-..   ---   ")
print(f("Hello World")=="....   .   .-..   .-..   ---       .--   ---   .-.   .-..   -..   ")
print(f("To be or not to be")=="-   ---       -...   .       ---   .-.       -.   ---   -       -   ---       -...   .   ")
print(f("3 14 15")=="...--       .----   ....-       .----   .....   ")

```

**Update**

* **-9** \[16-05-09\] Incorporated the ternary calculating function into the main function

**\[NOTE:** There is always trailing white space but white space represents a pause, so I guest that is ok **\]**

# Answer
> 0 votes
# PHP, ~~157~~ ~~150~~ 157 bytes

```
for(;$d=ord($c=$argv[1][$i++]);)echo ctype_alnum($c)?strtr(substr(decbin(ord($d>64?".CTRH@ZF\DUGXABEVOJL?K[ISQP"[$d&31]:"]muy{|ld`^"[$c])-48),1),10,".-"):$c;

```

takes input from first command line argument. no pause between letters. Run with `-nr`.

**breakdown**

```
for(;$d=ord($c=$argv[1][$i++]);)    # loop through input characters
    echo                                # print ...
    ctype_alnum($c)                     # if char is alphanumeric:
    ?   strtr(
        substr(
        decbin(
            ord($d>64                   # 1. map char to char-encoded morse
            ?".CTRH@ZF\DUGXABEVOJL?K[ISQP"[$d&31]
            :"]muy{|ld`^"[$c]
            )-60                        # 2. subtract 60 from ordinal value
        )                               # 3. decbin: convert to base 2
        ,1)                             # 4. substr: skip leading `1`
        ,10,".-")                       # 5. strtr: translate binary digits to dash/dot
    :$c;                                # not alphanumeric: no conversion

```

Beating JavaScript, Python2, C, Ruby and sed. I´m happy.

4th step: un-merged the mapping to handle lowercase characters without using `strtoupper`.

**previous versions:**

fail for lowercase letters; +12 bytes to fix: Replace `$argv[1]` with `strtoupper($argv[1])`.

**simple string translation, 254 bytes**

```
<?=strtr($argv[1],["-----",".----","..---","...--","....-",".....","-....","--...","---..","----.",A=>".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]);

```

straight forward: translates the whole string at once, character to morse code.
Save to file to execute or replace `<?=` with `echo` and run with `-r`.

**decimal interpretation of morse codes, 184 bytes** (-70)

```
for(;""<$c=$argv[1][$i++];)echo($m=[32,48,56,60,62,63,47,39,35,33,A=>6,23,21,11,3,29,9,31,7,24,10,27,4,5,8,25,18,13,15,2,14,30,12,22,20,19][$c])?strtr(substr(decbin($m),1),10,".-"):$c;

```

first golfing step: morse codes encoded to binary with an additional leading `1` to preserve leading zeroes. Loops through characters and translates them one by one. Run with `-nr`.

**decimals encoded to character, 157 bytes** (-27)

```
for(;""<$c=$argv[1][$i++];)echo ctype_alnum($c)?strtr(substr(decbin(ord("@"<$c?"CTRH@ZF\DUGXABEVOJL?K[ISQP"[ord($c)-65]:"]muy{|ld`^"[$c])-60),1),10,".-"):$c;

```

second golfing: added 60 to the decimal value and encoded to character.

**merged mapping, 150 bytes** (-7)

```
for(;""<$c=$argv[1][$i++];)echo ctype_alnum($c)?strtr(substr(decbin(ord("]muy{|ld`^8901234CTRH@ZF\DUGXABEVOJL?K[ISQP"[ord($c)-48])-60),1),10,".-"):$c;

```

third golfing: merged mapping for digits and letters to a single string.

# Answer
> 0 votes
# SmileBASIC, ~~194~~ 190 bytes

```
INPUT S$WHILE""<S$B=INSTR(" ETIANMSURWDKGOHVFLPJBXCYZQ  54 3   2       16       7   8 90",S$[0])+1IF B THEN S=LOG(B,2)FOR I=0TO S-1?"._"[B-(1<<S)AND S>>I||0];:NEXT?" ";
?SHIFT(S$)*!B;
WEND

```

# Answer
> 0 votes
# JavaScript (Node.js), 143 bytes

```
s=>[...s].map(t=>`?/'#! 08<>

	`.charCodeAt(parseInt(t,36)+1).toString(2).slice(1).replace(/./g,e=>'.-'[e])||t).join` `

```

Try it online!

---
Tags: code-golf, morse
---


title: 90° Self-Rotating Program

text:
# Question
Title: 90° Self-Rotating Program
# Introduction

Write a complete program that rotates a rectangular block of ASCII characters 90 degrees clockwise. When the program itself is rotated 90 degrees clockwise, it rotates a block of ASCII characters 90 counterclockwise.

# Rules

* You many not use built-ins that rotate or transpose matrices. For example, in MATLAB/Octave `rot90` and the transpose operator `'` are not allowed.
* You must write a complete program that uses STDIN and STDOUT or the closest equivalent.
* Your program must be rectangular and assume the input is also rectangular.
* The input and output are a newline separated strings and will not have trailing newlines.

When run with its source code as input, your program must rotate itself 90 degrees clockwise. The output must be a second program in the same language that rotates its input 90 degrees counterclockwise. When the rotated program is given its source code as input, it should output the source code of the original program.

**Note:** Both programs must work for *any* input, not just their own source code, so a one character quine is not allowed.

# Example

Say the following is a valid program that rotates its input 90 degrees in a hypothetical language ExampleLang.

```
^f a2% 3
lk (^_^&
       v
D8 $4  /

```

When run with itself as input, it outputs another valid program that rotates its input counterclockwise:

```
D l^
8 kf

$ (a
4 ^2
  _%
  ^
/v&3

```

This second program, when given to itself as input, outputs the original program. Note that the blank line should have four spaces and there is a trailing space on the second to last line that cannot be rendered in markdown. To clarify:

```
$ examplelang program < program > rotProg
$ examplelang rotProg < rotProg > program1
$ diff -s program program1
Files program and program1 are identical

```

Shortest program wins. Standard loopholes are banned.

# Answer
# CJam, ~~26~~ ~~25~~ 21 bytes

```
WqN/":.+""\%"(~+N-~N*

```

*Thanks to @MartinBüttner for golfing off 4 bytes!*

Try it online in the CJam interpreter: original program | rotated program

This is the rotated program:

```
W
q
N
/
"
:
.
+
"
"
\
%
"
(
~
+
N
-
~
N
*

```

### Idea

We can rotate the input a quarter turn clockwise by splitting it at linefeeds, reversing the order of the resulting rows, transposing rows with columns, and finally joining the rows, separated by linefeeds.

Likewise, we can rotate counterclockwise by transposing first, then reversing the rows.

Since the transposition built-in `z` is forbidden, we can use `:.+` (reduce by vectorized character or string-character concatenation) to achieve the same effect.

`:.+` is the only part of the source code that cannot be broken up. We push the strings `"W%"` and `":.+"`, conditionally reverse them if the second string contains a linefeed, concatenate, remove all linefeeds, and evaluate the result.

### Code

```
W     e# Push -1.
qN/   e# Read all input at split it at linefeeds.
":.+" e# Push a string that, when evaluated, transposes rows and columns.
      e# As explained in the previous section, this does NOT use a built-in
      e# for matrix transposition.
"\%"  e# Push a string that, when evaluated, reverses the rows.
(~    e# Shift out the first character and evaluate it.
      e# For the original code, this evaluates '\', swapping the strings on
      e# the stack. For the rotated code, this evaluates `\n', doing nothing.
+N-   e# Concatenate and remove linefeeds.
      e# The stack now contains:   -1 input "%:.+"   or   -1 input ":.+\%"
~     e# Evaluate the string on top of the stack.
N*    e# Join the resulting array, separating by linefeeds.

```
> 17 votes

# Answer
# C (gcc), ~~1420~~ ~~1399~~ 463 bytes

Ah... the joy of strings of undetermined length!

Assumes `sizeof(char*) == sizeof(int)` and `sizeof(char**) <= 16`.

## The new approach

```
char**L,*r;n,i//j=>]l n}q((
,j,q;R(l){for(//,l)l, +;;rr
r=l=0;(j=     //i=)[r +))oa
getchar())>10;//,r(r( *l(fh}
r[l++]=j,r[l]=//n(r,c=6=R)c;
0)r=realloc(r,//;rajoL1q()t)
l+2);l&&R((L= //roh=l(,,r"u)
realloc(L,++n*//*fc]l(Lro"p]
16))[n-1]=r,q=//,{t+aR(=f(;q
l);}main(){for//L)e+e&c]{sn[
(R();i<q;i++, //*lglr&o1)t<]
puts(""))for(j//*(=[=ll-(uj+
=n;j--;putchar//rRjrr;lnnp;+
(L[j][i]));}  //a;(;))a[i;0j
////////////////hq;002e)a-=[
////////////////c,01=+r)m-jL

```

Try it online!

Output of the above

The solution was embarrassingly easy in the end. You make one program A that rotates things clockwise, and one program B that rotates counter-clockwise:

### A

```
char**L,*r;n,i,j,q;R(l){for(r=l=0;(j=getchar())>10;r[l++]=j,r[l]=0)r=realloc(r,l+2);l&&R((L=realloc(L,16*++n))[n-1]=r,q=l);}main(){for(R();i<q;i++,puts(""))for(j=n;j--;)putchar(L[j][i]);}

```

### B

```
char**L,*r;n,i,j,q;R(l){for(r=l=0;(j=getchar())>10;r[l++]=j,r[l]=0)r=realloc(r,l+2);l&&R((L=realloc(L,16*++n))[n-1]=r,q=l);}main(){for(R();q--;puts(""))for(j=0;j<n;j++)putchar(L[j][q]);}

```

Make a rectangle of reasonable proportions and confine A to that, and put guards of comments around it:

```
char**L,*r;n,i//
,j,q;R(l){for(//
r=l=0;(j=     //
getchar())>10;//
r[l++]=j,r[l]=//
0)r=realloc(r,//
l+2);l&&R((L= //
realloc(L,++n*//
16))[n-1]=r,q=//
l);}main(){for//
(R();i<q;i++, //
puts(""))for(j//
=n;j--;putchar//
(L[j][i]));}  //
////////////////
////////////////

```

Confine program B to a square that is the same width as the one for A plus two (for the extra lines of comments at the bottom edge), rotate it CCW and slap it to the right of program A and you get the solution above.

## The old approach

```
 /*                                       r                               c                                                         c                                                  r
r                                         a                               o                         n                               o                          s                       a
a                          r              h                               l                         i       r                       l             r      -     t        r  =    +      h         q
h                          o              c        0     +                l                         a       o             +         l       6     o      -     u    "   o  j<   +      c  */
char**L,*s,*r;n,i,q;R(l,c){for(r=l=0;(c=getchar())>10;r[l++]=c,r[l]=0)r=realloc(r,l+2);q=l?l:q;l=r;}main(j){for(;s=R();L[n++]=s)L=realloc(L,16*n);for(;i<q;i++,puts(""))for(j=n;j--;)putchar(L[j][i]);}
 ///                        //          //e////     /     /             //e////                      ///     //            /      //e////    /     //  //  //// ///  /   // ;/   /// //u////      /
 ///                        //          //g////     /     /             //r////                      ///     //            /      //r////    /     //  //  //// ///  /   // 0/   /// //p////      /

```

Try it online!

Output of the above
> 8 votes

# Answer
# Python 3, 119 bytes

```
[print(*i[# "i  0:
::-1],sep#t " **(:
="")for i#n,=r[(n[]
in zip(* #iiponpe]]
open(0))]#r*efiip)1
#########[p(s) zo)-

```

Try it online!

rotated :

```
#oi=:[
#pn":p
#e "-r
#nz)1i
#(if]n
#0po,t
#)(rs(
#)* e*
#] ipi
[####[
print#
(*i,
sep=""
)for i
 in[*
zip(*
open(0
))][::
-1]]

```

Try it online!

## How it works :

The code is coposed of 2 parts separed by comments :

```
1111111111#22222222
111111111#222222222
111111111#222222222
111111111#222222222
111111111#222222222
#########2222222222

```

The first code rotates cockwise :

```
[print(*i[::-1],sep="")for i in zip(*open(0))]

```

Try it online!

The second rotates counter clockwise

```
[print(*i,sep="")for i in[*zip(*open(0))][::-1]]

```

Try it online!
> 1 votes

---
Tags: code-golf, restricted-source, array, source-layout
---


title: One More Program and I'm Out!

text:
# Question
Title: One More Program and I'm Out!
Given a positive integer nesting level `n` and string `s` of printable ascii characters( to `~`, output a program which, when run in the same language, outputs a program which outputs a program . . . which outputs the string `s`.

A total of `n` programs should be generated, all of which should be run in the same language as your answer.

Note: you may output programs or functions -- anything you are allowed by default as a submission.

You may input `s` with escaped characters, how a program or function in your language would usually input a string.

---

# Example

For example, given `n=1` and `s="recursion"`, a Python 2 program might output:

```
print "recursion"

```

Running this would output:

```
recursion

```

---

Given `n=2` and s="PPCG", a Python 2 program might output:

```
print "print \"PPCG\" "

```

Running this outputs:

```
print "PPCG"

```

Running this outputs:

```
PPCG

```

Related (+title inspiration): One more LUL and I'm out

Also Related (in sandbox - now deleted, but can still be viewed with enough reputation): Source Code Recursion

# Test Cases

Make sure that your code works for the following test cases (one per line):

```
n s
2 PPCG
4 Robert'); DROP TABLE Students;--
17 Deep
2 Spaces In Here
3 "Don't forget quotes!"
5 'Backt`cks might be a h`tch'
6 5%s
8 [Brackets]<Are>(Great){Usually}
3 !"#$%&'()*+,-./ 0123456789:;<=>?@ABCDEFGHIJKLMN
6 OPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
7 THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
3 the quick brown fox jumps over the lazy dog

```

# Answer
# Jelly, 2 bytes

```
Ṿ¡

```

Try it online!

```
Ṿ¡  Main link; left argument (text) is x, right argument (repetitions) is y
 ¡  Repeat y times:
Ṿ   Uneval x; produce code that outputs x

```

hehe builtins
> 19 votes

# Answer
# JavaScript (ES6), ~~47~~ 44 bytes

*Saved 3 bytes thanks to @HermanLauenstein*

Takes input in currying syntax `(n)(s)`.

```
n=>g=s=>`alert(atob("${btoa(--n?g(s):s)}"))`

```

### Example

```
f(2)('PPCG')

```

Will output:

```
'alert(atob("YWxlcnQoYXRvYigiVUZCRFJ3PT0iKSk="))'

```

Which will print:

```
'alert(atob("UFBDRw=="))'

```

Which will print:

```
'PPCG'

```

### Demo

A more complex example where `alert()` has been overridden so that intermediate results are printed to the console and automatically executed.

```
let f =

n=>g=s=>`alert(atob("${btoa(--n?g(s):s)}"))`

alert = s => { console.log(s); try { eval(s); } catch(e) {} }

alert(f(5)("'Backt`cks might be a h`tch'"));
```

---

# Alternate version, 40 bytes

*Suggested by @Shaggy*

This one returns an anonymous function instead of a full program.

```
n=>g=s=>`_=>atob("${btoa(--n?g(s):s)}")`

```
> 19 votes

# Answer
## sh + coreutils, 31 bytes

```
yes exec sed 1d \$0|sed $1q;cat

```

Takes `n` as a command-line parameter and `s` on STDIN.
> 10 votes

# Answer
# Python 2, 40 bytes

```
f=lambda r,t:r and"print%r"%f(r-1,t)or t

```

Try it online!

-4 bytes thanks to xnor
> 5 votes

# Answer
# Haskell, 17 bytes

As of when I write this, this is the shortest answer for a *non-golfing-specific* language.

It is a function which takes `s` and `n` in that order, and returns the result or the source code of an expression which, when evaluated, returns the next source code.

```
(!!).iterate show

```

Argument for why this counts:

1. Solutions are allowed to be functions.
2. Their outputs are allowed to be functions.
3. Those functions have no parameters.
4. In Haskell, since it is lazy and everything-is-curried, the most natural — for practical programming purposes — definition of a 0-parameter function is the same as its result; the closest alternative, a 1-parameter function which ignores the parameter, is silly.

If `f` is given `PPCG` and `2` as its parameters, the result is the text `"\"PPCG\""` (first generated function), which when evaluated returns the text `"PPCG"` (second generated funtion), and when that is evaluated it returns `PPCG`.

Thanks to nimi for suggesting a shortening.
> 5 votes

# Answer
# APL (Dyalog), ~~24~~ 23 bytes

-1 thanks to ngn.

This is a full program which prompts for `s` and then for `n` and prints to STDOUT.

```
''''{⍺,⍨⍺,⍵/⍨1+⍵=⍺}⍣⎕⊢⍞

```

Try it online! (the 17 Deep case is omitted as it exceeds TIO's output limit – works offline)

prompt for `s`

yield that (to separate  and )

`''''{``}⍣⎕` prompt for `n` and apply this lambda with a single quote as left argument that many times.  stands for the left argument (the quote) and  is stands for the right argument (the input text):

`⍵=⍺` Boolean where the text is equal to a quote

`1+` add one

`⍵/⍨` replicate each character of the argument the corresponding number of times

`⍺,` prepend a quote

`⍺,⍨` append a quote

This works because strings in APL are `'` delimited and single-quotes in strings are doubled, while no other characters need escaping.

---

Dyalog APL also ships with a utility (`⎕SE.Dyalog.Utils.repObj`) that generates an APL expression which evaluates to its argument (similar to Jelly's uneval). The following program is therefore equivalent to the above, but works for *all* arrays:

```
⎕SE.Dyalog.Utils.repObj⍣⎕⊢⎕

```

Try it online!
> 3 votes

# Answer
# Java 8, ~~95~~ 93 bytes

```
String c(String s,int n){return"v->\""+(n-->1?c(s,n).replaceAll("[\\\\\"]","\\\\$0"):s)+'"';}

```

-2 bytes thanks to *@Lynn*.

Escaping special characters is so annoying in Java..

Try it here and try the resulting method here.

**Explanation:**

```
String c(String s,int n){  // Method with String and int parameters and String return-type
  return"v->\""+           //  Return literal "v->" + a leading double-quote +
   (n-->1?                 //   If `n` is larger than 1:
     c(s,n)                //    Recursive-call,
      .replaceAll("[\\\\\"]","\\\\$0")
                           //    with all double-quotes ('"') and slashes ('\') escaped
    :                      //   Else:
     s)                    //    The input String
   +'"';                   //   + a trailing double quote
}                          // End of method

```

Additional explanation for the regex replacement:

```
.replaceAll("[\\\\\"]","\\\\$0")
.replaceAll("        ","      ")  // Replace the match of the 1st String, with the 2nd
             [      ]             //  One of these inner characters:
              \\\\                //   Escaped slash ('\')
                  \"              //   Escaped double-quote ('"')
                                  //  And replace them with:
                        \\\\      //   Escaped slash ('\'),
                            $0    //   plus found match

```

Why all these slashes?

```
\   →  \\       // Escapes a single slash for the regex
\\  →  \\\\     // Escapes both regex-escaped slashes for the String
"   →  \"       // Escapes a double-quote for the String

```
> 2 votes

# Answer
# Firefox JavaScript, ~~41~~ 35 bytes

```
f=(s,n)=>"_=>"+uneval(--n?f(s,n):s)

```

Firefox has a nice `uneval`, which does what it sounds like - unevals a given object, in this case - string.
> 2 votes

# Answer
# Underload, 11 bytes

```
(a(S)*)~^^S

```

Try it online!

Input needs to start on the stack, with the number on top in the form of a church numeral. I don't know if this is a valid input method, but the specification has no input, and placing input to the top of the stack seems like a stranded method used in such languages.
> 2 votes

# Answer
# , 62 bytes

```
f=function(n,s){"if"(n,{formals(f)$n=n-1;formals(f)$s=s;f},s)}

```

Try it online!

Call it like so: `f(n,s)` followed by `n` copies of `()`

A named function; returns an anonymous function. All it does is modify the default values of the `formals` of `f`, allowing the resulting function to be called (and then the result of that called, `n` times). when `n` reaches `0`, it returns `s`.

R is actually not too bad at escaping! It uses C-style escaping, so you just have to take the input, replace `"` with `\"` and `\` with `\\`, and then wrap the whole thing in `" "`.
> 2 votes

# Answer
# GolfScript, 5 bytes

```
~{`}*

```

Try it online!
> 1 votes

# Answer
# QuadR, 8 bytes

Simple translation of ngn's answer.

Takes `n` as argument and `s` as Input.

```
^|'|$
'&

```

Try it online!

PCRE **R**eplace all instances of

`^|'|$` Beginning of line OR Quote OR End of line

`'&` with a Quote and the entire match

The Argument specifies how many times to repeat the transformation.
> 1 votes

# Answer
# Excel VBA (32-Bit), 67 Bytes

*Version Restricted to 32-Bit Excel VBA because `2^i` evaluates without error in 32-Bit VBA, but not in 64-Bit VBA*

Anonymous VBE immediate window function that takes inputs `n` and `s` from from ranges `[A1]` and `[B1]` and outputs an anonymous function that when evaluated down to only a terminal (after `n` iterations) outputs only `s` as that terminal

```
For i=0To[A1-1]:q=q+"?"+String(2^i,34):Next:?q[B1]Replace(q,"?","")

```

### Sample Input / Output

```
[A1:B1]=Array(7, "PPCG")
For i=0To[A1-1]:q=q+"?"+String(2^i,34):Next:?q[B1]Replace(q,"?","")
?"?""?""""?""""""""?""""""""""""""""?""""""""""""""""""""""""""""""""?""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""PPCG"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
?"?""?""""?""""""""?""""""""""""""""?""""""""""""""""""""""""""""""""PPCG"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
?"?""?""""?""""""""?""""""""""""""""PPCG"""""""""""""""""""""""""""""""
?"?""?""""?""""""""PPCG"""""""""""""""
?"?""?""""PPCG"""""""
?"?""PPCG"""
?"PPCG"
PPCG

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
(q

```

Try it Online!

N times, uneval the string.
> 1 votes

# Answer
# Pyth, 21 bytes

```
L++NsXbJ,N\\+L\\JNyFz

```

Try it here.

Unfortunately the recursive function (not full program as above) is longer (24 bytes):

```
M?GgtG++NsXHJ,N\\+L\\JNH

```
> 0 votes

# Answer
# APL (Dyalog Classic), 19 bytes

```
'^|''|$'⎕r'''&'⍣⎕⊢⍞

```

Try it online!
> 0 votes

# Answer
# Ruby, 34 bytes

`%p` is a Ruby-specific printf flag that gets the `inspect` value of its argument, similar to `%r` in Python. `$><<` means print.

```
f=->n,s{"$><<%p"%(n>1?f[n-1,s]:s)}

```

Try it online!
> 0 votes

---
Tags: code-golf, recursion
---


title: Is this number random?

text:
# Question
Title: Is this number random?
I asked random.org for 128 random integers between 0 and 232 \- 1. Since the random number generator was so eager to give the first 64 numbers first, they're obviously *more random* than the other 64.

Write a full program or function that returns a truthy result when one of the following 64 integers is input:

```
[1386551069, 1721125688, 871749537, 3410748801, 2935589455, 1885865030, 776296760, 614705581, 3841106923, 434616334, 1891651756, 1128215653, 256582433, 310780133, 3971028567, 2349690078, 489992769, 493183796, 3073937100, 3968540100, 777207799, 515453341, 487926468, 2597442171, 950819523, 1881247391, 3676486536, 3852572850, 3498953201, 2544525180, 297297258, 3783570310, 2485456860, 2866433205, 2638825384, 2405115019, 2734986756, 3237895121, 1560255677, 4228599165, 3106247743, 742719206, 2409129909, 3008020402, 328113612, 1081997633, 1583987616, 1029888552, 1375524867, 3913611859, 3488464791, 732377595, 431649729, 2105108903, 1454214821, 997975981, 1764756211, 2921737100, 754705833, 1823274447, 450215579, 976175934, 1991260870, 710069849]

```

And a falsey result for the other 64 numbers:

```
[28051484, 408224582, 1157838297, 3470985950, 1310525292, 2739928315, 3565721638, 3568607641, 3857889210, 682782262, 2845913801, 2625196544, 1036650602, 3890793110, 4276552453, 2017874229, 3935199786, 1136100076, 2406566087, 496970764, 2945538435, 2830207175, 4028712507, 2557754740, 572724662, 2854602512, 736902285, 3612716287, 2528051536, 3801506272, 164986382, 1757334153, 979200654, 1377646057, 1003603763, 4217274922, 3804763169, 2502416106, 698611315, 3586620445, 2343814657, 3220493083, 3505829324, 4268209107, 1798630324, 1932820146, 2356679271, 1883645842, 2495921085, 2912113431, 1519642783, 924263219, 3506109843, 2916121049, 4060307069, 1470129930, 4014068841, 1755190161, 311339709, 473039620, 2530217749, 1297591604, 3269125607, 2834128510]

```

Any input other than one of these 128 numbers is undefined behavior.

If your solution is found programmatically, please also share the code used to generate it!

This is , so the shortest solution in bytes wins.

# Answer
## CJam, ~~53~~ ~~52~~ 47 bytes

```
l~"X    0'ò"2/Dfb+:%"gÇâì6Ô¡÷Ç8nèS¡a"312b2b=

```

There's unprintables, but the two strings can be obtained by

```
[88 9 48 5 39 5 29 1 242]:c
[8 103 199 226 236 54 212 15 161 247 199 56 110 232 83 161 97]:c

```

respectively. This also shows that the code points are below 256.

This is a modulo chain answer, where we apply the following modulos to the input integer, in order:

```
[1153 629 512 378 242 136]

```

Since this list contains integers greater than 255, the list is encoded using two chars each. The decoding is done by `2/Dfb`, which splits the string into chunks of length two and converts each from a base 13 number (e.g. `88*13 + 9 = 1153`). However, there are two exceptions to the decoding:

* The last number (`136`) is not included (see below),
* The second-last number is represented by a single char, since the number (`242`) is less than 256 and splitting an odd-length array into chunks of size 2 will leave a size 1 array at the end. Thanks to @MartinBüttner for this tip!

Once the modulos have reduced the input integer to a relatively small number, we perform a lookup from a table. This table is encoded via the second string, which is converted to a base `312` number then decoded to base 2, which we index. Since CJam's array indexing wraps, we can leave out the final modulo as mentioned earlier.

Try it online | Test suite
> 12 votes

# Answer
# Retina, 117 bytes

```
([023]3|[067]0|[1289]1|5[5689]|67|96|88|77|65|05)$|^(8|4[358]|7[147]|51|37|30)|865|349|2.{5}5|761|74[348]|728|811|990

```

A regex golf answer, outputting a positive integer for truthy and zero for falsy.

Try it online! | Test suite - truthy | Test suite - falsy | Regex101
> 5 votes

# Answer
# Jelly, 30 bytes

```
ȷ;€ȷḥ€⁸ḋ“¡`Ṿc-MrKṪZiṣ$Ṅ(ṀQ’B¤Ḃ

```

Try it online!

This answer was almost entirely automatically generated, using this automated encoder (which I wrote myself, and have previously used in another challenge); here's where the original algorithm (which I created myself) comes from. Because Jelly isn't so great at interprocess communication, the encoder generates a Sage program that generates a Jelly program that prints the final golfed program.

There were three manual tweaks to the automated result: two were golfing uses of base-generic builtins that dealt with base 2 into the (shorter) versions that are specific to binary, and one was to change the program from a full program into a function (so that I could easily test it on every test case – the byte count is the same either way, you just need to change the way it takes input from  (function argument) into, e.g., `³` (command-line argument)).

The generator has a couple of deficiencies that mean that it randomly fails sometimes; for a (and therefore only two outputs), this chance is much higher than normal (hard to estimate exactly, but likely above 50%). Fortunately, it randomly happened to work first time

## Explanation

```
ȷ;€ȷḥ€⁸ḋ“¡`Ṿc-MrKṪZiṣ$Ṅ(ṀQ’B¤Ḃ
 ;                              Form a pair of
  €                               each number from 1 to
ȷ                                   1000
   ȷ                              and 1000
     €                          and use each pair as
    ḥ                             a hash configuration, to hash
      ⁸                             this function's argument.
       ḋ                        Take the dot product {of the list of hashes}
                            ¤     and a constant determined by
                           B        taking the list of binary digits of
        “¡`Ṿc-MrKṪZiṣ$Ṅ(ṀQ’           [a magic constant]
                             Ḃ  {Output} its least significant bit.

```

As usual, the algorithm is to pass the inputs we're given through a list of hash functions to create a list of hashes (the list created this way is longer than it needs to be, to save bytes specifying how long it needs to be), then take the dot product of the list of hashes and a magic constant calculated by the program I linked above.

The reason this works is that each input/output pair that we need to set effectively corresponds to a requirement on the parity of the number of set bits in certain positions in the magic constant, e.g. the requirement that 1386551069 maps to 1 means that out of the bit positions in the magic constant that correspond to hash functions that hash 1386551069 to an odd number, an odd number of them need to be a 1 bit in order for the program to give the correct output in that case. This sort of requirement can be expressed as a linear equation in the finite field GF(2), making it possible to calculate what the magic constant should be simply via writing down all the equations (which is what the first stage of the generator program does) and solving them (which is what the Sage program that it outputs does). There might not be a solution, of course, but given an entirely randomly chosen set of simultaneous equations (i.e. each variable has a random coefficient in every equation), if the number of equations is no greater than the number of variables, the odds that they turn out to be solvable are actually pretty high, and they were here.

I did end up with a bit of luck converting the resulting equations to Jelly – the first bit of the list that needs to be encoded in the magic constant happens to be a 1, so it's possible to compress it by base-converting it into a number (which couldn't be done if it had a leading zero, as the leading zero would then be missing upon base-converting back). This is only a problem because Jelly base conversions are big-endian (extra trailing zeroes past the last useful hash function wouldn't have an effect), so wouldn't affect a golfing language that had this generic algorithm available as a builtin. Fortunately, this particular set of inputs and outputs managed to dodge the issue (and it's a deficiency with the decompressor that sits around the magic constant, rather than the technique for finding the magic constant itself).

As a side note, the magic constant is 17 bytes long (not 16, the theoretical minimum for 128 input → output pairs) because not all of the 256 bytes of the Jelly codepage are able to appear in a compressed literal – 6 of them are quotes (which can't appear unescaped because they'd be interpreted as ending the string, and there isn't an escape syntax), so only 250 of them are actually available, and that makes string literals a little longer than they would be in base 256.
> 4 votes

# Answer
# JavaScript (ES6) 233

An anonymous function returning 0 as `falsy` and nonzero as `truthy`

```
x=>~"lnhp2wm8x6m9vbjmrqqew9v192jc3ynu4krpg9t3hhx930gu8u9n1w51ol509djycdyh077fd1fnrzv6008ipkh0704161jayscm0l6p4ymj9acbv5ozhjzxo3j1t20j9beam30yptco033c9s3a8jwnre63r29sfbvc5371ulvyrwyqx3kfokbu66mpy9eh" // newline added for readability
.search((x.toString(36)).slice(-3))

```

Checking the last 3 digits in the number representation in base 36.

The check string is built so:

```
a=[1386551069, 1721125688, ... ]
H=x=>(x.toString(36)).slice(-3)
Q=a.map(x=>H(x)).join('')

```

**Test**

```
f=x=>~"lnhp2wm8x6m9vbjmrqqew9v192jc3ynu4krpg9t3hhx930gu8u9n1w51ol509djycdyh077fd1fnrzv6008ipkh0704161jayscm0l6p4ymj9acbv5ozhjzxo3j1t20j9beam30yptco033c9s3a8jwnre63r29sfbvc5371ulvyrwyqx3kfokbu66mpy9eh"
.search((x.toString(36)).slice(-3))

a=[1386551069, 1721125688, 871749537, 3410748801, 2935589455, 1885865030, 776296760, 614705581, 3841106923, 434616334, 1891651756, 1128215653, 256582433, 310780133, 3971028567, 2349690078, 489992769, 493183796, 3073937100, 3968540100, 777207799, 515453341, 487926468, 2597442171, 950819523, 1881247391, 3676486536, 3852572850, 3498953201, 2544525180, 297297258, 3783570310, 2485456860, 2866433205, 2638825384, 2405115019, 2734986756, 3237895121, 1560255677, 4228599165, 3106247743, 742719206, 2409129909, 3008020402, 328113612, 1081997633, 1583987616, 1029888552, 1375524867, 3913611859, 3488464791, 732377595, 431649729, 2105108903, 1454214821, 997975981, 1764756211, 2921737100, 754705833, 1823274447, 450215579, 976175934, 1991260870, 710069849]
b=[28051484, 408224582, 1157838297, 3470985950, 1310525292, 2739928315, 3565721638, 3568607641, 3857889210, 682782262, 2845913801, 2625196544, 1036650602, 3890793110, 4276552453, 2017874229, 3935199786, 1136100076, 2406566087, 496970764, 2945538435, 2830207175, 4028712507, 2557754740, 572724662, 2854602512, 736902285, 3612716287, 2528051536, 3801506272, 164986382, 1757334153, 979200654, 1377646057, 1003603763, 4217274922, 3804763169, 2502416106, 698611315, 3586620445, 2343814657, 3220493083, 3505829324, 4268209107, 1798630324, 1932820146, 2356679271, 1883645842, 2495921085, 2912113431, 1519642783, 924263219, 3506109843, 2916121049, 4060307069, 1470129930, 4014068841, 1755190161, 311339709, 473039620, 2530217749, 1297591604, 3269125607, 2834128510]

A.textContent=a.map(x=>f(x))
B.textContent=b.map(x=>f(x))
```

```
<table>
  <tr><th>first 64 - truthy</th></tr><tr><td id=A></td></tr>
  <tr><th>other 64 - falsy</th></tr><tr><td id=B></td></tr>
</table>
```
> 3 votes

# Answer
# Mathematica, ~~218~~ 217 bytes

```
Fold[Mod,#,{834,551,418,266,228,216,215,209,205,199,198,195,178,171,166,162,154,151,146,144,139,137,122,120,117,114,110,106,101,98,95,88,84,67,63,61,60,57,55,51,45,44,43,41,40,35,34,30,27,26,25,23,20,14,13,11,10,9}]<1

```

For whatever reason, a set of moduli exists that allows us to distinguish two sets just by whether or not, after applying the moduli, the result is zero or not. The long list of moduli was generated by this program:

```
Block[{data1, data2, n, mods},
 data1 = {1386551069, 1721125688, 871749537, 3410748801, 2935589455,
   1885865030, 776296760, 614705581, 3841106923, 434616334,
   1891651756, 1128215653, 256582433, 310780133, 3971028567,
   2349690078, 489992769, 493183796, 3073937100, 3968540100,
   777207799, 515453341, 487926468, 2597442171, 950819523, 1881247391,
    3676486536, 3852572850, 3498953201, 2544525180, 297297258,
   3783570310, 2485456860, 2866433205, 2638825384, 2405115019,
   2734986756, 3237895121, 1560255677, 4228599165, 3106247743,
   742719206, 2409129909, 3008020402, 328113612, 1081997633,
   1583987616, 1029888552, 1375524867, 3913611859, 3488464791,
   732377595, 431649729, 2105108903, 1454214821, 997975981,
   1764756211, 2921737100, 754705833, 1823274447, 450215579,
   976175934, 1991260870, 710069849};
 data2 = {28051484, 408224582, 1157838297, 3470985950, 1310525292,
   2739928315, 3565721638, 3568607641, 3857889210, 682782262,
   2845913801, 2625196544, 1036650602, 3890793110, 4276552453,
   2017874229, 3935199786, 1136100076, 2406566087, 496970764,
   2945538435, 2830207175, 4028712507, 2557754740, 572724662,
   2854602512, 736902285, 3612716287, 2528051536, 3801506272,
   164986382, 1757334153, 979200654, 1377646057, 1003603763,
   4217274922, 3804763169, 2502416106, 698611315, 3586620445,
   2343814657, 3220493083, 3505829324, 4268209107, 1798630324,
   1932820146, 2356679271, 1883645842, 2495921085, 2912113431,
   1519642783, 924263219, 3506109843, 2916121049, 4060307069,
   1470129930, 4014068841, 1755190161, 311339709, 473039620,
   2530217749, 1297591604, 3269125607, 2834128510};
 n = 1;
 mods = {};
 While[Intersection[Mod[data1, n], Mod[data2, n]] != {}, n++];
 FixedPoint[
  (mods = Append[mods, n]; data1 = Mod[data1, n];
    data2 = Mod[data2, n]; n = 1;
    While[Intersection[Mod[data1, n], Mod[data2, n]] != {}, n++];
    n) &
  , n];
 {mods, {Fold[Mod, data1, mods], Fold[Mod, data2, mods]}}
 ]

```

First output is the moduli, second and third outputs are the two lists, having applied the moduli. The two long lists are the sets.
> 2 votes

# Answer
## PowerShell, v3+ 194 bytes

```
$args[0]%834%653-in(40..45+4,8,12,51,60,64,69,76,84,86,93,97,103,117+137..149+160,162,178+195..209+215..227+255,263+300..329+354,361,386,398,417,443,444+469..506+516,519,535,565,581,586,606,618)

```

A little bit of a different approach, so I figured I would post it. It's not going to win shortest, but it may give someone else ideas to shorten their code.

We're still taking the input integer `$args[0]` and applying modulo operations to it, so nothing different there. In the above, we're using the `-in` operator (hence v3+ requirement) so this will output `True` for values that are in the truthy test case.

However, I'm attempting to find resultant arrays where we can leverage the `..` range function to shorten the byte count, yet still have distinct arrays between the truthy and falsey values. We can do this since behavior other than the truthy/falsey input is undefined, so if the range catches values outside of the truthy/falsey input, it doesn't matter the output.

It's a pretty manual process so far, as the goal is to try and find the modulo where one of truthy or falsey arrays has large gap(s) between numbers and the other array has large amounts of numbers in that gap. I've mostly been going by intuition and gut feel so far, but I may eventually write a brute-forcer to solve this. The above is the shortest I've (mostly manually) found so far.
> 2 votes

---
Tags: code-golf, number, random, classification, decision-problem
---


title: Twins' complements

text:
# Question
Title: Twins' complements
Consider a length-\\$n\\$ array of positive integers.

* The **complement** of the element with index \\$i\\$ is the element with index \\$n - i - 1\\$.
* The **twin** of an element \\$a\\$ is its complement after removing all elements not equal to \\$a\\$.

For example, in the array `[1, 2, 3, 4, 2, 1, 3, 2]`, the complement of the first `2` is the last `3`, and the twin of the first `2` is the last `2`. (In general, the twin of the first \\$a\\$ is the last \\$a\\$, the twin of the second \\$a\\$ is the second-to-last \\$a\\$, etc.)

Given a non-empty array of positive integers, replace each element with the complement of its twin.

```
[1, 2, 3, 4, 2, 1, 3, 2] -> [3, 1, 2, 2, 4, 2, 1, 3]
[1, 2, 1, 3] -> [2, 1, 3, 1]
[10] -> [10]
[8, 3, 1, 8, 1, 8, 3, 10, 3, 8, 10, 8] -> [8, 8, 10, 1, 8, 3, 8, 3, 10, 3, 1, 8]

```

# Answer
> 7 votes
# , ~~65~~ ~~59~~ ~~50~~ ~~41~~ 36 bytes

```
function(x,`!`=order)x[!rev(x)][!!x]

```

Try it online!

**How?**

First, a couple of tricks used:

1. Re-assign the `!` operator to become the `order` function,
2. Notice that `rank(x)` is equivalent to `order(order(x))`, with tied ranks broken by first occurrence.

So, ungolfed:

```
twin_complement=
function(x){
 o=order(rev(x))        # get the order of reversed values of x,
                        # breaking ties in reverse order-of-first-occurrence in x;
 t=o[rank(x,            # use this to get the twin index for each index of reversed x
  ties.method="first")] # = the element at the rank position of each x value,
                        # now breaking ties in order-of-first-occurrence in x;
 x[t]                   # finally, return the complement of x
                        # at each twin position in reversed x.
}

```

# Answer
> 7 votes
# Jelly, 8 bytes

```
ĠUFỤịỤịU

```

Try it online!

Port of Jonah's J answer:

```
Ġ          Group indices
 U         Reverse each group
  F        Flatten
   Ụ       Grade up
    ịỤ     Index into graded-up original list
      ịU   Index into reversed list

           e.g. input: “XYXZYY” (needn't be integers!)
        Ġ: [[1,3],[2,5,6],[4]]
        U: [[3,1],[6,5,2],[4]]
        F: [ 3,1,  6,5,2,  4 ]
        Ụ: [2,5,1,6,4,3]

           This is a "rank" of the input, breaking ties backwards:
            X Y X Z Y Y
            2   1          rank Xs backwards
              5     4 3    rank Ys backwards
                  6        rank Zs backwards
         → [2,5,1,6,4,3].

           Meanwhile, Ụ is [1,3,2,5,6,4] (equiv. to ĠF),
           indices that sort the input:

           [X,Y,X,Z,Y,Y]
           [1,  3,         indices of Xs
              2,    5,6,   indices of Ys
                  4]       indices of Zs

           Now ịỤ permutes one list by the other,
           mapping each element to its twin's index:
       ịỤ: [3,6,1,4,5,2]

            X Y X Z Y Y
            3   1          Twin indices of Xs
              6     5 2    Twin indices of Ys
                  4        Twin indices of Zs

           And we only have to index into the backwards input:
       ịU: “ZXYXYY”

```

# Answer
> 7 votes
# Minipyth, 30 bytes (17.7 bytes if encoded)

```
mhoithzsmqmscbnqgihcmmzsbbnlis

```

Minipyth is a new minimalist language I've designed. It only uses lowercase letters, and it doesn't have things like variables, arity 2 functions, etc.

Because Minipyth only uses lowercase letters, it could be re-encoded to be much shorter. I'm therefore also listing its information-theoretic length, which shorter by a factor of $$\log(26)/\log(256) \approxeq 59\\%.$$

Minipyth doesn't have an online executor yet, but it can be used offline through the repository linked above.

It's executed from right to left, in function application order.

I'll break it down into several pieces to show what's going on.

First, we prepare a list consisting of elements of the form \[complement, index, value\], where value is an element of the input, index is its position in the input, and complement is its complement.

```
cmmzsbbnlis
     b         Bifurcate: make a list by applying two functions to the input
      b        Function 1: Bifurcate on
       n       negate, reversing the input,
        l      length, the length of the input
         is    inverse sum, wrap the input in a list.
    s          sum, concatenate into a single list of 3 elements
 m             map on
  mz           the default map, identify on lists, casts int x to [0, ..., x-1]
c              chop, transpose the three lists to form lists of 3 elements.

```

Next, we group these elements by their values. This is simply `gih`, group by inverse head (last element).

Now, we need to form the twins.

```
smqmscbnq
 m           Map over the groups.
      bn     Bifurcate on n, reversing the group.
     c       Chop, forming pairs.
   ms        Sum the pairs, concatenating into one list
s            Sum, concatenating the lists back into one

```

z and q just make everything parse correctly.

Now, our elements are six element lists: \[twin's complement, twin's index, twin's value, complement, index, value\].

We just need to put things back into their original order using the index, then extract the twin's complement.

```
 mhoithz
   o         Order by
    i        Inverse of
     t       Tail
      h      Head
             The inverse of tail removes the final element,
             then the inverse of head returns the second-to-last
 mh          Map to head

```

One note, at the time of this writing (commit 4436b81a3), inverse reverses the order of application of its arguments. This was to mimic inverse functions, but I've decided I don't like it, and I will undo that. In the future, the equivalent program will have h and t swapped:

```
mhoithzsmqmscbnqgihcmmzsbbnlis

```

# Answer
> 5 votes
# Jelly, 9 bytes

```
ĠUF,ỤyJịU

```

Try It Online!

```
ĠUF,ỤyJịU  Main Link
Ġ          Group indices by equal elements
 U         Reverse each block
  F        Flatten
   ,Ụ      Pair with the grade of the original list
     yJ    Apply this as a translation to the indices of the list
       ịU  Index that into the reverse of the original list

```

-1 byte thanks to Lynn with the grading up trick. Grading up a list sorts the indices by their corresponding values.

# Answer
> 4 votes
# Jelly, 7 bytes

```
ỤỤịUỤ$ị

```

Try it online!

Port of my R answer.

Pseudocode: `x [ order of reverse of x ] [ order of order of x ]`

Jelly explanation:

```
ỤỤ        # get the order of the order of the input;
  ị       # use this to index into...
     $    # (previous two links together)
   U      # ...reverse of
    Ụ     # ...order of the input;
      ị   # finally use this to index into the input

```

# Answer
> 3 votes
# Charcoal, ~~18~~ 17 bytes

```
ＩＥθ§θ§⌕Ａ⮌θι⌕⌕Ａθικ

```

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

```
  θ                 Input array
 Ｅ                  Map over elements
    θ               Input array
   §                Indexed by
         θ          Input array
        ⮌           Reversed
      ⌕Ａ            Find all occurrences of
          ι         Current value
     §              Indexed by
              θ     Input array
            ⌕Ａ      Find all occurrences of
               ι    Current value
           ⌕        Find index of
                κ   Current index
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 3 votes
# Jelly, 10 bytes

```
ĠżṚ$€ẎḢÞịṚ

```

A full program that accepts the list and prints the result.

**Try it online!**

### How?

```
ĠżṚ$€ẎḢÞịṚ - Main Link: list, A
Ġ          - group indices by their element's values
   $€      - for each:
  Ṛ        -   reverse that list of indices having equal values
 ż         -   zip the two together
     Ẏ     - tighten (to a list of [index, twin index] pairs)
       Þ   - sort by:
      Ḣ    -   pop head from the pair being inspected
         Ṛ - reverse A
        ị  - use the (remaining) twin indices to index into the reversed copy of A
           - implicit, smashing print

```

# Answer
> 3 votes
# , ~~41~~ ~~39~~ 32 bytes

```
function(x)ave(rev(x),x,FUN=rev)

```

Try it online!

I thought of this as a `split %>% lapply %>% unsplit` before remembering that `ave` does the same thing for fewer bytes.

Test harness taken from Dominic van Essen's answer.

Explanation to follow.

# Answer
> 3 votes
# BQN, 9 bytesSBCS

Port of Dominic van Essen's R answer.

```
⍋∘⍋⊏⍋∘⌽⊏⊢

```

Run online!

---

# BQN, ~~17~~ 13 bytesSBCS

~~My own attempt that ended up being similar to~~ Based on Lynn's Jelly answer that is a port of Jonah's J answer.

```
⌽⊏˜{⍋∾⌽¨⊔}⊏⍋

```

Run online!

# Answer
> 2 votes
# Vyxal, 19 bytes

```
ƛ?=TḂZ;UÞfµh;vt?Ṙ$İ

```

Try it Online!

A clumsy port of Jonathan Allan's answer.

```
ƛ     ;             # Map input to...
 ?=T                # Indices of that element
    ḂZ              # Zipped with its reverse
       UÞf          # Uniquify and flatten to a list of [index, pair index] pairs
          µh;       # Sort by first item
             vt     # Get second item of each
                  İ # Use those to index into
               ?Ṙ$  # Input reversed

```

# Answer
> 2 votes
# , 24 bytes

```
|.{~[:(/:&;~|.&.>)<@I.@=

```

Try it online!

# Answer
> 2 votes
# Python/NumPy, 60 bytes

```
def f(a):
 b=a*0
 for S in a:b[a==S]=a[a[::-1]==S]
 return b
```

Attempt This Online!

Expects and returns numpy arrays.

# Answer
> 1 votes
# JavaScript (ES6), 56 bytes

```
a=>a.map(v=>a[b[j=b.indexOf(v)]=0,j],b=[...a].reverse())

```

Try it online!

### Commented

```
a =>                // a[] = input array
a.map(v =>          // for each value v in a[]:
  a[                //   lookup in a[]:
    b[ j =          //     get the position j
       b.indexOf(v) //     of the 1st occurrence of v in b[]
    ] = 0,          //     and clear it
    j               //     get a[j]
  ],                //   end of lookup
  b = [...a]        //   start with b[] initialized to
      .reverse()    //   a copy of a[] in reverse order
)                   // end of map()

```

# Answer
> 1 votes
# JavaScript (ES2022), 48 bytes

```
a=>a.map(g=n=>a.at(g[n]=~-g[n])-n?g(n):a[~g[n]])

```

```
f=

a=>a.map(g=n=>a.at(g[n]=~-g[n])-n?g(n):a[~g[n]])

console.log(f([1, 2, 3, 4, 2, 1, 3, 2]) + ''); // [3, 1, 2, 2, 4, 2, 1, 3]
console.log(f([1, 2, 1, 3]) + ''); // [2, 1, 3, 1]
console.log(f([10]) + ''); // [10]
console.log(f([8, 3, 1, 8, 1, 8, 3, 10, 3, 8, 10, 8]) + ''); // [8, 8, 10, 1, 8, 3, 8, 3, 10, 3, 1, 8]
```

# Answer
> 1 votes
# 05AB1E, 18 bytes

```
ÙvIIyQƶ0K©RIgαè®<ǝ

```

Try it online or verify all test cases.

**Explanation:**

```
Ù                   # Uniquify the (implicit) input-list
 v                  # Loop over each unique value `y`:
   IyQ              #  Check for each value in the input-list if it's equal to `y`
                    #  (1 if truthy; 0 if falsey)
      ƶ             #  Multiply each by its 1-based index
       0K           #  Remove all 0s
         ©          #  Store this list in variable `®` (without popping)
          R         #  Reverse it
             α      #  Get the absolute difference between each 1-based index
           Ig       #  and the input-length
  I           è     #  Use that to (0-based) index into the input-list
               ®<   #  Push `®` and decrease each by 1 to make them 0-based
                 ǝ  #  Insert the values at those indices into the list
                    #  (which will be the implicit input-list in the first iteration)
                    # (after the loop, the result is output implicitly)

```

# Answer
> 1 votes
# C (gcc), ~~131~~ 127 bytes

```
c;j;i;*w;*f(a,n)int*a;{for(w=calloc(i=n,4);i--;w[i]=a[n+~j]){for(j=c=0;j<=i;)c+=a[i]==a[j++];for(j=n;c;)c-=a[i]==a[--j];}a=w;};

```

Try it online!

*Saved 4 bytes thanks to ceilingcat!!!*

Inputs a pointer to an array (\\$a\\$) of integers and its length (because pointers in C carry no length info).
Returns a pointer to an array of all of \\$a\\$'s elements' twins' complements.

# Answer
> 0 votes
# Vyxal, 6 bytes

```
⇧₌Ṙ⇧İİ

```

Try it Online!

Port of Dominic's Jelly answer.

```
⇧      # Gradeup
 ₌Ṙ⇧   # Push ^ reversed, ^ gradeup'd
    İ  # Use the reversed copy to index into the double-gradeup'd
     İ # Use those indicies to index into the input.

```

---
Tags: code-golf, array
---


# Question
Title: Compute the specificity of a CSS selector
Today, your task is to write a program (or a function) that accepts a string and outputs (or returns) four integers.

**Input**

The input string is a CSS3 selector, and can contain basically any Unicode character.

**Output**

The output represents the CSS specificity of this selector.

* The first number is always 0 (because it's used for inline styles, and this exercise doesn't apply to inline styles)
* The second number is the number of ids (`#foo`) present in the selector.
* The third number is the number of classes (`.foo`), attributes (`[bar]`) and pseudo-classes present in the selector.
* The fourth number is the number of elements (`biz`) and pseudo-elements present in the selector.

**Notes:**

* Universal selector (\*) isn't counted anywhere
* The pseudo-elements `::before` and `::after` can also be written with a single ":" (legacy notation)
* Input can use the `:not(selector)` pseudo-class. The selector inside doesn't count, even if it contains ids, classes, elements, ...)
* The "bricks" of the selector are separated by combinators (spaces/tabs, `+`, `>`, `~`, ex: `body > div+a ~*`), but they can also be cumulated (ex: `div#foo.bar[baz]:hover::before`)
* You also have to handle CSS escape sequences ( `\` followed by 1 to 6 hexadecimal numbers, followed by a space), and escaped special characters (`\` followed by any of these: `!"#$%&'()*+,-./:;<=>?@[\]^`{|}~`) properly. Those escapes can be part of any brick of the selector (id, class, etc).
* You don't need to do anything particular if you receive an invalid selector or a CSS4 selector. Don't bother implementing a CSS3 selector validator.
* Here are a few links to learn more about CSS specificiy:

**Examples**

```

// Universal

*                       => 0,0,0,0

// ID

#id                     => 0,1,0,0

// Class

.class                  => 0,0,1,0

// Attributes

[foo]                   => 0,0,1,0
[foo="bar"]             => 0,0,1,0
[foo~="bar"]            => 0,0,1,0
[foo^="bar"]            => 0,0,1,0
[foo$="bar"]            => 0,0,1,0
[foo*="bar"]            => 0,0,1,0
[foo|="bar"]            => 0,0,1,0
[ foo  =  bar ]         => 0,0,1,0
[foo  =  'bar']         => 0,0,1,0

(NB: brackets [] can contain anything except an unescaped "]")

// Pseudo-classes

:root                   => 0,0,1,0
:nth-child(n)           => 0,0,1,0
:nth-last-child(n)      => 0,0,1,0
:nth-of-type(n)         => 0,0,1,0
:nth-last-of-type(n)    => 0,0,1,0
:first-child            => 0,0,1,0
:last-child             => 0,0,1,0
:first-of-type          => 0,0,1,0
:last-of-type           => 0,0,1,0
:only-child             => 0,0,1,0
:only-of-type           => 0,0,1,0
:empty                  => 0,0,1,0
:link                   => 0,0,1,0
:visited                => 0,0,1,0
:active                 => 0,0,1,0
:hover                  => 0,0,1,0
:focus                  => 0,0,1,0
:target                 => 0,0,1,0
:lang(fr)               => 0,0,1,0
:enabled                => 0,0,1,0
:disabled               => 0,0,1,0
:checked                => 0,0,1,0
:not(selector)          => 0,0,1,0

(NB: the keyword after ":" can be anything except a pseudo-element)

// Elements

body                    => 0,0,0,1

// Pseudo-elements

:before                 => 0,0,0,1
:after                  => 0,0,0,1
::before                => 0,0,0,1
::after                 => 0,0,0,1
::first-line            => 0,0,0,1
::first-letter          => 0,0,0,1

(NB: parenthesis () can contain anything except an unescaped ")" )

```

(to be continued)

If you have questions or need examples or test data, please ask in the comments.

Shortest code (in bytes) wins.

Good luck!

# Answer
> 2 votes
# JavaScript ES6 ~~453~~ 430 bytes

```
a=>(s){var n=z=[],c=[0,0,0,0],e=s.split(/[\s\+\>\~]+/);return e.forEach((s)=>{n=n.concat(s.replace(/\((.*)\)/,"").split(/(?=\[|::|\.)/))}),n.forEach((s)=>{if(0==s.indexOf("::"))return z.push(s);var n=s.split(/(?=:)/);z=z.concat(n[0].split(/(?=[\#])/)),/before|after/.test(n[1])?z.push(":"+n[1]):n[1]&&z.push(n[1])}),z.forEach((s)=>{/^[a-z]+$/gi.test(s)||"::"==s[0]+s[1]?c[3]++:-1!=":.[".indexOf(s[0])?c[2]++:"#"==s[0]&&c[1]++}),c}

```

**Update:** improved code, now it handles `:not` and `:before`/`:after` selectors better, nevertheless haven't tested CSS escape sequences.

# Answer
> 0 votes
# Python3, 226 bytes:

```
lambda s:[0,(c:=(x:=sub('(?<=\:not)\(.*?\)|\\.*?\\\\|(?<=\[).*?(?=\])','',s)).count)('#'),c('.')+c('[')+sub('::|(?:\:after)|(?:\:before)','',x).count(':'),len(findall('^\w+|[\s\>\+,]\w+|::|\:after|:before',x))]
from re import*

```

The test cases included in the link below are derived from the sample selectors in the original question along with the most complex selectors from Code Golf's own source.

Try it online!

---
Tags: code-golf, css
---