title: Letters to numbers to letters (poorly)

text:
# Question
Title: Letters to numbers to letters (poorly)
Every now and again, I'll encounter a large string of alphabetical text encoded as numbers from 1-26. Before I knew that I could just google a translator online, I had to personally, painstakingly copy and paste the entirety of the encoded text into a text document and translate it myself.

Thankfully, I did know about find-and-replace features, which I used to search for all copies of each number and convert them to their corresponding characters. Only one problem... If you do this in numerical order, it will come out garbled.

This is because the single digit numbers used to encode a-i also appear as part of the remaining two digit numbers encoding j-z. For example, `26` *should* decode to `z`, but since both 2 and 6 are less than 26, we decode those first. `2` becomes `b`, and `6` becomes `f`, so `26` becomes `bf`.

Note also that for `10` and `20`, there is no conversion for `0`, so we end up with `a0` and `b0` respectively.

## Challenge

Given a string of alphabetical characters (`abcdefghijklmnopqrstuvwxyz`), output the result of converting to numbers and back again using the algorithm described above. You may assume input is all lowercase or all uppercase. This is , so shortest code in bytes wins.

Important: You may *not* zero index.

Full conversion list:

```
a: a
b: b
c: c
d: d
e: e
f: f
g: g
h: h
i: i
j: a0
k: aa
l: ab
m: ac
n: ad
o: ae
p: af
q: ag
r: ah
s: ai
t: b0
u: ba
v: bb
w: bc
x: bd
y: be
z: bf

```

## Examples

```
xyzzy => bdbebfbfbe
caged => caged
jobat => a0aebab0
swagless => aibcagabeaiai

```

# Answer
> 5 votes
# Retina 0.8.2, 32 bytes

```
[j-s]
a$&
[t-z]
b$&
T`j-z`0a-i0l

```

Try it online! Link includes test cases. Explanation:

```
[j-s]
a$&
[t-z]
b$&

```

Precede the letters `j-z` with an `a` or `b` as appropriate.

```
T`j-z`0a-i0l

```

Translate them to `0` or `a-i` as appropriate. (`l` expands to `a-z` but only `a-f` get used as the replacement list gets truncated to the length of the translation list.)

# Answer
> 5 votes
# Vyxal, 8 bytes

```
øAṅ₄ɾkaĿ

```

Try it Online!

# Answer
> 4 votes
# JavaScript (Node.js), 70 bytes

```
s=>s.replace(r=/./g,c=>parseInt(c,36)-9).replace(r,i=>'0abcdefghi'[i])

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~10~~ 8 bytes

```
A0ìDIkSè

```

I/O as lowercase list of characters.

-2 bytes thanks to *@CommandMaster*

Try it online or verify all test cases.

**Explanation:**

```
A         # Push the lowercase alphabet
 0ì       # Prepend a leading "0"
   D      # Duplicate it
    I     # Push the input character-list
     k    # Get the (0-based) index of each character in the "0abc...xyz" string
      S   # Convert it to a flattened list of digits
       è  # (0-based) index each into the "0abc...xyz" string
          # (after which the result is output implicitly)

```

If `None` is a valid output for `0`, builtin `.b` could be used for an alternative 8-byter in the legacy version of 05AB1E, with uppercase character-lists as I/O: try it online. (The `.b` results in `"@"` in the new version of 05AB1E for `0`: try it online.)

# Answer
> 4 votes
# C (clang), ~~74~~ 67 bytes

* -6 bytes thanks to @jdt.

```
p(c){c&&putchar(c^96);}c;f(*s){for(;c=*s++%96;p(c%10?:80))p(c/10);}

```

Try it online!

# Answer
> 4 votes
# \>\<\>, 35 bytes

```
i"`":@-:9)?\+o
"*-$a,"`"+o\:a%:0="0

```

Try it online

**Explanation**

```
i"`":@-               # get input and subtract 96 from it to convert letters to
                        1-indexed numbers and save a copy of 96 for reverse
                        conversion later
       :9)?\+o        # if number is > 9 move down, else print with saved 96 added
           \:a%       # mod a copy of the number by 10
"*-            :0="0  # if the result is 0, subtract 48
   $a,"`"+o           # divide the other copy by 10 and print with 96 added
           \          # handle the print of the mod copy on the first row

```

# Answer
> 3 votes
# , 75 bytes

```
\(s,`[`=gsub)chartr("j-z","0a-i0a-i","([j-s])"["a\\1","([t-z])"["b\\1",s]])
```

Attempt This Online!

Straightforward replacement.

---

### , ~~84~~ 81 bytes

*Edit: -3 bytes thanks to @Dominic van Essen.*

```
\(s)gsub("`",0,intToUtf8(strtoi(unlist(strsplit(paste(utf8ToInt(s)-96),"")))+96))
```

Attempt This Online!

Going with the algorithm.

# Answer
> 3 votes
# lin, 41 bytes

```
$a0`,.+10`t2`/\"`rev `_`"`' , `,*10`d tro

```

Try it here!

Decided to go for a different non-regex approach, which came out quite nicely. Turns out that `tro` surprisingly accepts an iterator of iterators, which saved quite a few bytes.

For testing purposes:

```
"jobat" ; outln
$a0`,.+10`t2`/\"`rev `_`"`' , `,*10`d tro

```

## Explanation

Prettified code:

```
$a 0`, dup 10`t 2`/\ ( `rev `_` ) `' , `,* 10`d tro

```
* `$a 0`,` alphabet with 0 in front as *a*
* `$a 0`,.+ 10`t` duplicate and create `0abcdefghi`
* `2`/\ ( `rev `_` ) `'` 2-digit pairs (`00 0a 0b ... ig ih ii`)
* `, `,* 10`d` zip with *a* and remove first 10 pairs (`[j a0] [k aa] [l ab] ... [x bd] [y be] [z bf]`)
* `tro` transliterate

# Answer
> 3 votes
# Husk, 14 bytes

```
m!₁ṁod€₁
…"az0

```

Try it online!

Inspired by Kevin Cruijssen's approach, although comes-out a bit longer in Husk...

```
…               # Fill-in the gaps with character ranges
 "az0           # in the string "az0"
                # (fill-in works both backwards & forwards, resulting in:
                # "abcde...vwxyzyxwv...edcba`_^]\...43210")
                # = assign this as '₁'
   ṁo           # Now, for each input letter
      €₁        # get the index of first occurence in ₁ (=index in alphabet)
     d          # and split the decimal digits;
m               # Then, for each digit
 !₁             # retrieve the element in ₁ using modular 1-based indexing
                # (so zero retrieves the last element)

```

# Answer
> 3 votes
# Perl 5, 27 bytes

```
s/./-96+ord$&/ge;y/1-9/a-i/

```

Try it online!

# Answer
> 3 votes
# Lexurgy, 92 bytes

```
a:
{j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}=>{a\0,aa,ab,ac,ad,ae,af,ag,ah,ai,b\0,ba,bb,bc,bd,be,bf}

```

Naive 1-1 substitution.

# Answer
> 3 votes
# Piet \+ ascii-piet, 129 bytes (5×27=135 codels)

```
uqijsvudnbddt   feussskiu L?q   sa   dttlvqfeumdctss?Lr????saa???????????????s  Lkjftrqavqcefcnbftmnkss K                    ssvc

```

Try Piet online!

Input the string in upper-case with the sentinel value `@`.

**Explanation**

Read char from input, subtract 64 and check if it is greater than 9.

If c\<=9: check if its check if it is greater than 0 (else terminate).

Add 64, print char and start over.

If c\>9: duplicate, push 10 on stack, duplicate, roll, divide, print char, modulo and check if it is greater than 0.

If c\>0: print char (as above) and start over.

If c=0: print number and start over.

# Answer
> 3 votes
# Japt, 13 bytes

```
;£ÒCaXÃ®°gCi0

```

Try it

```
;£ÒCaXÃ®°gCi0
;             # C = "abcdefghijklmnopqrstuvwxyz"
 £            # For each letter in the input:
   CaX        #  Find its 0-based index in C
  Ò           #  Add 1
      Ã       #  Join to a string
       ®      # For each character in the new string
        °     #  Coerce to a number
         g    #  Get the character at that index in:
          Ci0 #   C with a 0 added to the front

```

# Answer
> 2 votes
# Charcoal, 13 bytes

```
⭆⭆Ｓ⊕⌕βι§⁺β0⊖ι

```

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

```
  Ｓ             Input string
 ⭆              Map over characters and join
    ⌕           Index of
      ι         Current character
     β          In lowercase alphabet
   ⊕            Incremented
⭆               Map over characters and join
         β      Lowercase alphabet
        ⁺       Concatenated with
          0     Literal string `0`
       §        Indexed by
            ι   Current character
           ⊖    Decremented (auto-casts to integer)

```

# Answer
> 2 votes
# Factor, 53 bytes

```
[ 96 v-n [ >dec ] map-concat 48 v+n "`" "0" replace ]

```

Needs modern Factor for \>dec but here's a version that works on TIO for +1 byte:

Try it online!

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

```
s=>s.replace(/[j-z]/g,c=>"ab"[c>'s'|0]+"abcdefghi0"[parseInt(c,36)%10])

```

Try it online!

# Answer
> 2 votes
# Bash, 74 47 bytes

```
sed "s/[j-s]/a&/g;s/[t-z]/b&/g"|tr j-z 0a-i0a-i

```

Try it online!

*-27 thanks to Neil's idea*

# first approach, 74 bytes

```
sed "s/./\"'&\"/g"|xargs printf '%d-96\n'|bc|sed '/../s/./&\n/'|tr 1-9 a-j

```

Try it online!

# Answer
> 2 votes
# Burlesque, 25 bytes

```
)**96?-imXX@azr@'0+]jsi\[

```

Try it online!

```
)**   # Map ord(a)
96?-  # Subtract 96 (get index into alphabet)
imXX  # Concat and separate by digit
@azr@ # Alphabet [a,b,..,z]
'0+]  # Prepend [0,a,b,..,z]
jsi   # Select indices
\[    # Concat

```

# Answer
> 2 votes
# Python 3, 79 bytes

```
lambda s:s.translate({n:'AB'[n>83]+'0ABCDEFGHI'[n%74%10]for n in range(74,91)})

```

Try it online!

# Answer
> 2 votes
# Pyth, 16 bytes

```
sm@+G0tsdjkmhxGd

```

Try it online!

# Answer
> 2 votes
# , 68 bytes

```
\(x,y=utf8ToInt(x)-96)intToUtf8(rbind(y/10+96*(y>9),48--y%%10%%-58))
```

Attempt This Online!

Calculates 2 decimal digits for each letter, and then calculates the corresponding codepoint values, setting unused values (leading zeros) to zero, which is not output by the `intToUtf8` function.

---

# , 54 bytes

```
\(x)chartr('1-9','a-i',Reduce(paste0,utf8ToInt(x)-96))
```

Attempt This Online!

Port of Kjetil S's Perl answer.

# Answer
> 2 votes
# Python 3.8 (pre-release), 76 bytes

```
f=lambda s:s and'ba'[2-(q:=ord(s[0])%32)//10::2]+'0abcdefghi'[q%10]+f(s[1:])

```

Try it online!

# Answer
> 2 votes
# C (GCC), ~~101~~ ~~88~~ 87 bytes

```
f(char*s){for(char*x;*s;)for(asprintf(&x,"%d",*s++-64);*x;)putchar(*x+(*x++^48?16:0));}

```

Attempt This Online!

Prints to standard out. Uses `asprintf`, which is a GNU-specific function and may or may not require a definition in the header, so I don't know if it's okay.

This is basically the first C function I've ever written, so there are almost certainly ways this can be improved.

---

-13 bytes from @c-- by iterating one character at a time, removing parens, and changing the ternary
-1 bytes from @ceilingcat by moving the `char*x` declaration into the for statement

# Answer
> 2 votes
# Dyalog APL, 32 bytes

```
{(⎕A,'0')[27@(0∘=)⍎¨∊⍕¨⎕A⍳⍥⎕C⍵]}

```

Attempt This Online!

```
                       ⎕A⍳   ⍵  find each character's index in the alphabet
                          ⍥⎕C   case insensitively (casefold both arguments first)
                     ⍕¨         turn each number into string
                    ∊           flatten nested array to get the individual digits
                  ⍎¨            turn each digit back into a number
          27@(0∘=)              turn 0s into 27s
         [                    ] index into
  ⎕A                            the alphabet
    ,'0'                        with a 0 at the end at the 27th position

```

# Answer
> 2 votes
# J-uby, 43 bytes

```
~(:gsub+(:ord|:+&-96))&/./|~:tr&"a-i"&"1-9"

```

Attempt This Online!

# Answer
> 2 votes
# Julia 1.7, 52 bytes

```
!x=replace(join([x...].-'`'),('1':'9'.=>'a':'i')...)

```

Attempt This Online!

* `replace` supports multiple patterns as of Julia 1.7

# Julia 1.0, ~~66~~ 65 bytes

```
~x=join(get.([Dict('1':'9'.=>'a':'i')],[join([x...].-'`')...],0))

```

Try it online!

# Answer
> 2 votes
# Japt, 12 bytes

```
c_uH sAÇ©d96

```

Try it (Includes all test cases)

```
c_uH sAÇ©d96     :Implicit input of string
c_               :Map codepoints
  u              :  Modulo
   H             :    32
     s           :  Convert to string in base
      A          :    10
       Ç         :    Map the range [0,A)
        ©        :      Logical AND with
         d96     :      Add 96 and get character at that codepoint

```

# Answer
> 2 votes
# Knight (v2), ~~49~~ 46 bytes

```
;=y,=xP;Wx;=y+y-Ax 96=x]x;W=y]y=x+x&[yA+96[yOx

```

Try it online!

This uses the quirky nature of `+(List, Number)`. It acts similarly to appending to a String where it will append individual digits, with the exception that the elements will be Number instead of String.

So for example, `+ @ 42` will result in `[4, 2]`, compared to `+ "" 42` which will be `"42"` or `+ @ "42"` which will be `["4", "2"]`.

This has a bunch of perks:

* Creating a list is only one char (`@` for empty, `,` with an existing expression), compared to empty string which is 2 (`""`)
* The digits will be a Number, so there is no need to convert from ASCII to do char math. I can therefore use the `&` operator to both test if the digit is 0 without a compare, and append that `0` if it is due to coercion rules.

```
; = y ,                             # Set y to a list with one dummy argument (which is x)
        : = x PROMPT()              # Read a string into x

# Convert to a list of numbers containing each digit (with a preceeding dummy value)
; WHILE (x)                         # While x is not empty
    ; = y + y (- ASCII (x) 96)      # Push DIGITS of x[0] - 'a' - 1 as Number to y
    : = x ] x                       # Pop front char from x
# Convert back
# x = "", y = [ dummy, digit, digit ]
; WHILE (= y ] y)                   # While y is not empty, popping front beforehand
    : = x + x (                     # Append to x...
       & [ y                        #   Either y[0] if it is zero (which is coerced to '0')
       : ASCII (+ 96 ([ y))         #   or y[0] + 'a' - 1 converted to ASCII
    : )
: OUTPUT x                          # Output the string in x

```
* -3 bytes for taking Samp's advice and making `y` for `WHILE(= y ] y)`

# Answer
> 1 votes
# , 34 32 bytes

```
"."0@(,&":/)&.:(('0',97}.a.)&i.)

```

Try it online!

# Answer
> 0 votes
# Batch, 432 Bytes

```
SETLOCAL ENABLEDELAYEDEXPANSION&(CMD /U /C^"<NUL SET /P=abcdefghijklmnopqrstuvwxyz^"|FIND /V ""|FINDSTR /N "^")>a&(CMD /U /C^"<NUL SET /P=%s%^"|FIND /V "")>t&FOR /F %%Q in (t)DO (FOR /F "tokens=1-2 delims=:" %%A in ('FINDSTR /RC:"%%Q" a')DO (IF %%A GEQ 20 (SET /Ad=%%A+76&CMD /CEXIT !d:96=48!&<NUL SET /P=b!=exitcodeAscii!) else IF %%A GEQ 10 (SET /Ad=%%A+86&CMD /CEXIT !d:96=48!&<NUL SET /P=a!=exitcodeAscii!) else <NUL SET /P=%%B))

```

Assuming @ECHO OFF and passing it as

```
CALL golf.bat swagless

```

produces

```
aibcagabeaiai

```

This can probably not the best way, but I thought that this was a pretty cool way to do it. Ungolfed:

```
(CMD /U /C^"<NUL SET /P=abcdefghijklmnopqrstuvwxyz^"|FIND /V ""|FINDSTR /N "^")>a
(CMD /U /C^"<NUL SET /P=%1^"|FIND /V "")>t

FOR /F %%Q in (t) DO (
    FOR /F "tokens=1-2 delims=:" %%A in ('FINDSTR /RC:"%%Q" a') DO (
        IF %%A GEQ 20 (
            SET /Ad=%%A+76
            CMD /CEXIT !d:96=48!
            <NUL SET /P=b!=exitcodeAscii!
        ) else IF %%A GEQ 10 (
            SET /Ad=%%A+86
            CMD /CEXIT !d:96=48!
            <NUL SET /P=a!=exitcodeAscii!
        ) else <NUL SET /P=%%B
    )
)

```

# Answer
> 0 votes
# Pip, 20 bytes

```
C(96+^J A*a-96)R"`"0

```

Try It Online!

How?

```
C(96+^J A*a-96)R"`"0 : One arg, [String]
          a          : First input(string)
        A*           : Cast each char to an ordinal
           -96       : Subtract 96(lower to range of the alphabet indexed by one)
      J              : Join iterable
     ^               : Split into list of characters
  96+                : Add 96(raise to ASCII range)
C                    : Cast to characters
               R"`"0 : Replace substring "`" with zero

```

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


title: Ah, why is there a bug in my program?

text:
# Question
Title: Ah, why is there a bug in my program?
This challenge is inspired by @LuisMendo's MATL answer to my "binary multiples" challenge.

# Task

Pick a challenge that is *open* and that has been posted *before* this one; let me call it the *"linked challenge"*. The *linked challenge* must be a challenge whose task involves producing output.

Write the shortest code possible that satisfies the following restrictions:

* Your code must contain the characters `b`, `u` and `g` in your program, in this order and consecutively (case-insensitive, so "bug", "BUG", "Bug", "bUg", ... are all fair game.);
* Your code must *not* contain the letters `b`, `u` and `g` more than once (case-insensitive);
* Your code should be a valid submission for the *linked challenge*;
* When any subset of the (case-insensitive) characters `bug` are removed, your program no longer fulfils the task of the *linked challenge*. This may happen because your program now produces the wrong output (i.e. fails test cases), because it halted with an error, because it runs indefinitely and never returns (if this is the case, be prepared to prove your program runs indefinitely), etc.
* Your code should not be an integral copy - nor a trivial modification* \- of a submission that already exists in the *linked challenge* (for example, you may not copy @LuisMendo's MATL answer to my "binary multiples" challenge);

# Input

Your program takes input as per the specs of the *linked challenge* you choose.

# Output

Your program, in its correct state (i.e. with a bug\**), must abide by the output specs of the *linked challenge* you choose.

* This is subjective so I appeal to your common sense; any imaginative modification should be fair game, even if in retrospective it is "trivial". This "no trivial modifications" rule will be "enforced" by me downvoting answers I think disrespect this...

\** Sit down, take a moment to let this sink in. Your program has a bug. And yet your program is correct.

# Posting an answer

When you post your answer, please provide a link to your *linked challenge*.

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your written feedback. Happy golfing!

# Answer
# Japt, 4 bytes

Challenge: Output with the same length as the code

```
BUG³

```

Test it

## Explanation

`B`, `U`, and `G` are variables for 11, the input, and 16 respectively.

When applied to a number, `³` brings it to the third power.

In Japt, only the last expression is outputted, so only \\$16^3 = 4096\\$ is outputted, which is the same length as the code (4).

Since `B` and `U` are ignored, removing them have no effect on the output. However, their removal changes the length of the program, making it invalid. Removing `G` raises either the input (`U`) or 11 (`B`) to the third power. While \\$11^3 = 1331\\$ is 4 bytes, the program  is only two bytes, making the output invalid. The variable `U` defaults to 0 when there is no input given, and \\$0^3 = 0\\$, which is only one byte long.
> 19 votes

# Answer
# Polyglot, 31 bytes

Linked challenge: “Hello, World!”

This is a full program, as per the original challenge requirements.

```
print('Hello, World'+'bug!'[3])

```

Try it in JavaScript (V8)!

Try it in Python!

Try it in Ruby! (thanks to @Steffan for pointing this out)
> 10 votes

# Answer
# JavaScript (ES7), 47 bytes

Linked challenge: How many petals around the rose

```
a=>a.map(n=>t+=n**3&parseInt('bug',35)%9,t=0)|t

```

Try it online!

### How?

This is a port of my Python answer to the linked challenge. This answer requires a bitwise AND with a constant, which happens to be \\$6\\$.

This \\$6\\$ is obtained with the cumbersome `parseInt('bug',35)%9` and removing any subset of characters from `bug` would produce a different (and therefore invalid) constant.

```
   s   | parseInt(s, 35) | mod 9
-------+-----------------+-------
 'bug' |      14541      |   6
 'ug'  |       1066      |   4
 'bg'  |        401      |   5
 'bu'  |        415      |   1
 'g'   |         16      |   7
 'b'   |         11      |   2
 'u'   |         30      |   3
 ''    |        NaN      |  NaN

```
> 9 votes

# Answer
# C (gcc), 156 bytes

Answer to 99 bugs in the code. Not competitive, but funny.

```
#define S"%d bugs in the code\n"
d;f(i){for(i=99;i;i=d)printf(S S"Take one down and patch it aro\x75nd\n"S"\n",i,i,d=(d=i+rand()%21-16)<0?0:d);printf(S,0);}

```

Also beats the C solution there.

Try it online!
> 9 votes

# Answer
# Triangular, 6 bytes

Linked to Challenge: Shortest code to produce infinite output

```
bug>%<

```

Try it online!
> 5 votes

# Answer
# PHP, 16 bytes

Solving Output programming language name

```
echo'2=7'^'bug';

```

Try it online!

Omitting any of the letters in `bug` outputs a wrong string. However, it won't cause any errors so that error messages containing `PHP` can never be outputted. All PHP answers in that challenge exploit either PHP flags, which cannot contain the word `bug`, or PHP errors, which omitting a letter from `bug` could still result in an output that fulfils the requirements.
> 5 votes

# Answer
# Python 3, 24 bytes

```
while __debug__:print(1)

```

Try it online!

*Linked challenge: Shortest infinite loop producing output*

Uses the fact pointed out by @Bubbler:

> Python has a built-in constant called `__debug__` which is True by default. Removing some of its bug will obviously be an error. Though I can't find a suitable challenge for that...
> 4 votes

# Answer
# Lua and perhaps a polyglot in concept, ~~25~~ ~~28~~ 32 bytes

Along the lines of Arnauld's answer, linked to challenge Output programming language name.

```
print('\076\117\097 5.'..#'bUg')

```

Try it online!

*Added 3 bytes Thanks to @RGS spotting the 'u' in 'Lua'*
*Added 4 bytes Thanks to @MariaMiller for the 'L' and the 'a' as well*
> 3 votes

# Answer
# APL (Dyalog Extended), 6 bytes

Solves Output with the same length as the code.

```
×'BUG'

```

Try it online!

Prints `1 1 1\n`, 6 bytes in total.

In regular APL, monadic `×` is Signum for numbers (-1 if negative, 1 if positive, 0 if zero). Extended provides an extended (no pun intended) definition for characters (-1 for lowercase, 1 for uppercase).

Because numeric arrays are printed with a space between items, deleting one char out of `BUG` will remove two bytes (`<space>1`) from the output, thus failing to solve the challenge. Deleting two chars will remove four output bytes, and deleting all of them gives only a single newline.
> 3 votes

# Answer
# Zsh/Bash/others, 15 bytes

Challenge: Output with same length as code

```
echo BUG{1..3}

```

Try it online (Zsh)! Try it online (Bash)!
> 3 votes

# Answer
# CJam, 4 bytes

Challenge: Output with the same length as the code

It's working. But I still didn't manage a 3-byte solution.

```
BUG^

```

Try it online!

# Why it works

```
B    "Constant for 11";
 U   "Constant for 0";
  G  "Constant for 16";
   ^ "Bitwise XOR";

```

0 XOR 16 is 16, therefore it outputs `1116`.

# Removing a single character

```
UG^

```

It just outputs `16` without other calculations.

```
BG^

```

It outputs `27` because 11 XOR 16 is 27.

```
BU^

```

It outputs `11` because 11 XOR 0 is 0.

## Removing 2 characters

CJam doesn't have implicit input, so all these programs would throw an error.
> 3 votes

# Answer
Create output twice the length of the code

# MathGolf, 6 bytes

```
╘╘BUG]

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 4 bytes

Linked challenge: Output with same length as the code.

*Port of Embodiment of Ignorance's Japt answer.*

```
bugт

```

Try it online!
> 2 votes

# Answer
# C (gcc), 24 bytes

This one for real.

Answer to Swap the parity.

```
f(x){x=-(-x^!"bug"[3]);}

```

Try it online!
> 2 votes

# Answer
# C (gcc), 26 bytes

Answer to Shortest code to produce infinite output

```
f(){printf("bug"+2)&&f();}

```

Try it online!
> 2 votes

# Answer
## Javascript, 8 characters

Linked question: Output with the same length as the code

```
bug=>1e7

```

Outputs `10000000`, which has the same length as the program. Removing 1 or 2 characters would make it print the same thing, but wouldn't match the length of the program anymore. Removing all 3 is a syntax error.
> 2 votes

# Answer
# Jelly, 8 bytes

**Reverse Bit Order of 32-bit Integers**

```
%Ø%BUGƇḄ

```

Try it online!

I managed to find a challenge that actually uses two of the letters in a productive way.

There's no Jelly answer to the challenge at the time of writing this answer.

## Explanation

```
%Ø%BUGƇḄ Main monadic link
%        Modulo
 Ø%        2^32
   B     Convert to binary
    U    Reverse
      Ƈ  Filter by
     G   Format as a grid
       Ḅ Convert from binary

```
> 2 votes

# Answer
Linked to challenge: Find the number of integers in the range from 1 to N that ends with 2

# Python 2, ~~95~~ \\$\cdots\\$ ~~39~~ 35 bytes

Saved a byte (in a previous version) thanks to Maria Miller!!!
Saved a byte (in an other previous version) thanks to Surculose Sputum!!!

```
def f(n):print((n+len("bug")+5)/10)

```

Try it online!
> 1 votes

# Answer
# Ruby, 24 bytes

Linked to Find the number of integers in the range from 1 to N that ends with 2

```
->n{(n+5+"bug".size)/10}

```

Try it online!
> 1 votes

# Answer
Linked to challenge: Find the number of integers in the range from 1 to N that ends with 2

# C (gcc), ~~51~~ ~~42~~ 40 bytes

```
i;f(n){for(i=0;n+=2,"bug"[i++];);n/=10;}

```

Try it online!
> 1 votes

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

Linked Challenge: How many petals around the rose

```
a=>a.map(n=>t+=n**3&!!'bug'[2]*6,t=0)|t

```

Try it online!

Originally posted as a golf to Arnauld's answer.
> 1 votes

# Answer
# Python 2, 13 bytes

Solves Output with the same length as the code.

```
print 'bug'*4

```

Try it online!

Prints `bugbugbugbug\n`.

---

# Python 2, 27 bytes

Solves Hello, World!

```
print'bugHello, World!'[3:]

```

Try it online!

Removing some of `bug` will chop off characters from the beginning of `'Hello, World!'`.
> 1 votes

# Answer
# , 6 bytes

Challenge: Output the same length as code

```
BUG"2*

```

Repeats the string "BUG" multiple times.
> 1 votes

# Answer
# Io, 18 bytes

Challenge: Output programming language name

(Joke ruiner over here, never mind.)

This errors (outputting the language name) when the bug is inside, and it doesn't error when any part of the bug is removed.

If you think that this uses the `i` character (taken from the question):

> Note that this is case sensitive. I can still use the char 'b' because it's different from 'B'.

```
if("bug"size>2,iO)

```

Try it online!

## Explanation

```
        size       // Is the length of
   "bug"           // the string "bug"
            >2     // larger than 2?
if(           ,    // If so,
               iO  // Access an undefined variable
                 ) // Otherwise, do nothing

```

# Io, 19 bytes

Challenge: Output with the same length as the code

```
"bug"at(2)cos print

```

Try it online!

# Explanation

```
"bug"               // The sequence "bug"
     at(2)          // The 3rd index of that
                    // (Out-of-bounds indexing returns nil)
                    // This returns an integer for an in-bound index
          cos       // Find the cosine of that
                    // (Cosine over nil throws an error)
              print // Print that value to STDOUT. (WITHOUT a newline)

```

# Io, 19 bytes

Challenge:Shortest infinite loop producing no output

```
while("bug"at(2),0)

```

Try it online!

# Explanation

```
      "bug"         // Base string "Bug"
           at(2)    // Try to access the 3rd item of the string
                    // (Out-of-bounds returns nil)
while(          ,   // While that's true:
                    // (So a string is always true and nil is always false)
                 0) // No action needed

```
> 1 votes

# Answer
# , 7 bytes

Solves I double the source, you double the output!

```
>:Debug

```

Try it online! Try it online!Try it online!

Prints 1 as given, 2 doubled.

### How it works

Monadic `>:` is "increment" (add 1), dyadic `>:` is "greater or equal" (`x >= y`).

```
>:Debug    NB. increment 0; gives 1

>:Debug>:Debug
  Debug>:Debug    NB. 0 >= 0; gives 1
>:                NB. increment it; gives 2

```

---

# , 12 bytes

Solves Output with the same length as code.

```
echo 6#Debug

```

Try it online!

Somewhat similar to Python, J has a stdlib variable `Debug` which is initialized to the number 0. `6#` replicates the zero 6 times, and `echo` prints it. The output formatting is identical to APL's (space-separated numbers), so the output is `0 0 0 0 0 0\n`.

Being a terse language, I suspect there could be a more suitable challenge for J which gives a shorter solution using `Debug`.
> 1 votes

# Answer
# Java 8, ~~88~~ 87 bytes

Linked challenge: Is this number a prime?
Given a number, outputs truthy/falsey depending on whether it is a prime number.

```
n->{int i="BUG".charAt(2)-70;for(;n%++i%n>0;);System.console().printf("%s",""+(n==i));}

```

Try it online (Note: `System.console()` is `System.out` on TIO, since TIO doesn't support console).

**Explanation:**

```
n->{                // Method with integer parameter and no return-type
  int i=            //  Integer `i`, starting at:
    "BUG".charAt(3) //  Get the third character from String `"BUG"` as unicode value
     -70;           //  and subtract 70 from it, so it'll become 1
  for(;n%++i        //  Increase `i` by 1 first before every iteration with `++i`
            %n>0;); //  And loop as long as `n` modulo-`i` is not 0
                    //  NOTE: The second `%n` is to stop the loop for input n=1
  System.console().printf("%s",
                    //  Print to STDOUT with String format:
    ""+(            //   Convert the following boolean to String:
        n==i));}    //   Check if `n` and `i` are equal

```

Prime checker credit goes to *@SaraJ*'s answer here, which is rather ingenious.

Things I had to do to comply to the challenge:

1. The challenge description mentions program (and technically the linked challenge as well), but this isn't possible in Java. I know five different ways of creating a full program in Java, but each of them requires at least one of the letters `bgu`. Usually I can get past source-restrictions by using `\u`-unicode escapes, but since `u` is one of the restricted characters that's also not an option here. Luckily OP allowed functions as well, which is (much) shorter anyway.
2. I couldn't use `return` since it contains an `u`. And I also couldn't use `System.out.print(...)`, since it contains an `u` as well. So instead, I use `System.console().printf("format",...)`
3. Since I wanted to print a boolean, the format to use in the `printf` would be `"%b"`. Unfortunately, `b` is blocked, so instead I use `"%s"` and convert the boolean to a string.
4. And last thing to tackle was of course sneaking `bug` in, so it works with it, but doesn't work anymore without it. I've done this by changing the `int i=1;` to `int i="BUG".charAt(2)-31;`, which grabs the third character in the String (the `'G'`) as unicode value (`71`), and subtracts 70 from it to make it `1`. If any of the `B`, `U`, and/or `G` is removed, the `.charAt(2)` will fail with a `StringIndexOutOfBoundsException`.
> 1 votes

# Answer
# , 15 bytes

Linked challenge: Output with the same length as the code

```
strrep("bug",5)

```

Try it online!

(or 18 bytes if we include the default `[1] ""` formatting with which  surrounds its ouput, but this restriction did not seem to be applied to the original linked challenge).
> 1 votes

# Answer
# Batch, 11 bytes

Linked challenge: Output with the same length as the code

```
@echo %bug%

```

Outputs `ECHO is on.` when run regularly or when some of `bug` is removed, and outputs `%` when all of `bug` is removed.
> 1 votes

# Answer
## Javascript (82 characters)

Linked challenge: Integer lists of Noah

```
c=>eval('O\x62ject').keys(x={},c.map(a=>x[a]=(x[a]||0)+1)).some(z=>x[z]!=2)&&'bug'

```

It's a bit lame, but I'm defining my outputs as producing 'bug' when input list is not a Noah list, and `false` when it is.

I love this challenge though. Maybe I can find a better solution. :)
> 0 votes

# Answer
# TI-Basic, 6 bytes

Linked challenge: Output with the same length as the code

```
BUG
ᴇ5

```
> 0 votes

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


title: String.prototype.isRepeated

text:
# Question
Title: String.prototype.isRepeated
**UPDATE** : isaacg's Pyth submission is the winner!

---

Many of you must have heard that there is a cooler version of JavaScript in town (read ES6) which has a method `String.prototype.repeat` so that you can do

```
"Hello, World!".repeat(3)

```

and get

```
"Hello, World!Hello, World!Hello, World!"

```

as the output.

Your job is to write a function or a program in a **language of your choice** which detects if a string has been gone under such transformation.

i.e. The input string can be represented as an exact `n` times repetition of a smaller string. The output (as function's return statement or STDOUT) should be truthy if the string can be or falsy if the string cannot be represented as a repetition of smaller string.

Some sample input:

```
"asdfasdfasdf"  // true
"asdfasdfa"     // false
"ĴĴĴĴĴĴĴĴĴ"     // true
"ĴĴĴ123ĴĴĴ123"  // true
"abcdefgh"      // false

```

Note that the last input is false, thus **`n` should be greater than `1`**

**Complete rules**

* Write a function/program in any language to input (via function argument/command line args/STDIN) a string
* Return/Print truthy value if the given string is formed via an exact repetition of a smaller string, repeating at least twice.
* Maximum size of the input string is ideally Infinity
* String can have all possible ASCII characters
* This is a so smallest code in characters wins.

# Answer
# Pyth, 9

```
/:+zz1_1z

```

Or

```
}z:+zz1_1

```

These are both close translations of @xnor's python answer, except that they take input from STDIN and print it. The first is equivalent to:

```
z = input()
print((z+z)[1:-1].count(z))

```

0 for False, 1 for True.

The second line is equivalent to:

```
z = input()
print(z in (z+z)[1:-1])

```

False for False, True for True.

Pyth's official compiler had a bug related to the second one, which I just patched, so the first is my official submission.
> 16 votes

# Answer
## Python (24)

```
lambda s:s in(s+s)[1:-1]

```

Checks if the string is a substring of itself concatenated twice, eliminating the first and last characters to avoid trivial matches. If it is, it must be a nontrivial cyclic permutation of itself, and thus the sum of repeated segments.
> 86 votes

# Answer
## Regex (ECMAScript flavour), 11 bytes

Sounds like a job for regex!

```
^([^]+)\1+$

```

Test it here.

I've chosen ECMAScript, because it's the only flavour (I know) in which `[^]` matches any character. In all others, I'd either need a flag to change the behaviour of `.` or use `[\s\S]` which is three characters longer.

Depending on how we're counting the flag, that *could* of course be a byte shorter. E.g. if we're counting pattern + flags (e.g. ignoring delimiters), the PCRE/Perl equivalent would be

```
/^(.+)\1+$/s

```

Which is 10 bytes, ignoring the delimiters.

Test it here.

This matches only strings which consist of at least two repetitions of some substring.

Here is a full 26-byte ES6 function, but I maintain that regular expression submissions are generally valid:

```
f=s->/^([^]+)\1+$/.test(s)

```
> 30 votes

# Answer
# CJam, 9

```
q__+)@+#)

```

Similar to xnor's idea.

```
q      " Read input. ";
__+    " Duplicate twice and concatenate them together. ";
)      " Remove the last character of the longer string. ";
@+     " Insert that character at the beginning of the shorter string. ";
#)     " Find the shorter string in the longer string, and increase by one. ";

```
> 12 votes

# Answer
## APL, 11

```
2<+/x⍷,⍨x←⍞

```

**Explanation**
takes string input from screen
`x←` assigns to variable `x`
`,⍨` concatenates the string with itself
`x⍷` searches for `x` in the resulting string. Returns an array consisting of 1's in the starting position of a match and 0's elsewhere.
`+/` sums the array
`2<` check if the sum is greater than 2 (as there will be 2 trivial matches)
> 8 votes

# Answer
# CJam, 10 bytes

I caught the CJam bug. My first answer, so probably can be golfed some more:

```
q__+(;);\#

```

Outputs -1 for FALSE and a number \>=0 for TRUE
> 7 votes

# Answer
# GolfScript, 10 bytes

```
..+(;);\?)

```

Yet another implementation of xnor's clever idea.
> 5 votes

# Answer
# Python - ~~59~~ 57

```
lambda s:any([s*n==s[:n]*len(s)for n in range(2,len(s))])

```
> 4 votes

# Answer
# Pure bash, 30 bytes

Simple port of @xnor's clever answer:

```
[[ ${1:1}${1:0: -1} =~ "$1" ]]

```

Exit code is 0 for TRUE and 1 for FALSE:

```
$ for s in 'Hello, World!Hello, World!Hello, World!' 'asdfasdfasdf' 'asdfasdfa' 'ĴĴĴĴĴĴĴĴĴ' 'ĴĴĴ123ĴĴĴ123' 'abcdefgh'; do echo "./isrepeated.sh "\"$s\"" returns $(./isrepeated.sh "$s"; echo $?)"; done
./isrepeated.sh "Hello, World!Hello, World!Hello, World!" returns 0
./isrepeated.sh "asdfasdfasdf" returns 0
./isrepeated.sh "asdfasdfa" returns 1
./isrepeated.sh "ĴĴĴĴĴĴĴĴĴ" returns 0
./isrepeated.sh "ĴĴĴ123ĴĴĴ123" returns 0
./isrepeated.sh "abcdefgh" returns 1
$

```

Note `=~` within `[[ ... ]]` is the regex operator in bash. However *"Any part of the pattern may be quoted to force it to be matched as a string"*. So as ai often the case with bash, getting quoting right is very important - here we just want to check for a string submatch and not a regex match.
> 4 votes

# Answer
## TI-BASIC - 32

I thought I'd try a tokenized language. Run with the string in Ans, returns 0 if false and the length of the repeated string if true.

```
inString(sub(Ans+Ans,1,2length(Ans)-1),sub(Ans,length(Ans),1)+Ans

```

Amazing how it's a one-liner.
> 3 votes

# Answer
# ECMAScript 6 (189)

```
(function(){var S=String.prototype,r=S.repeat;S.isRepeated=function(){return!1};S.repeat=function(c){var s=new String(r.call(this,c));if(c>1)s.isRepeated=function(){return!0};return s}}());

```

```
< console.log("abc".isRepeated(),"abc".repeat(10).isRepeated());
> false true

```

Surely this is the only valid solution? For example, the word (string) `nana` isn't necessarily created from `"na".repeat(2)`
> 3 votes

# Answer
# ECMAScript 6 (34 ~~36~~)

Another ES6 answer, but without using `repeat` and using xnor's trick:

```
f=i=>(i+i).slice(1,-1).contains(i)

```

Must be run in the console of a ES6-capable browser such as Firefox.
> 2 votes

# Answer
# C 85

```
l,d;f(s){return l=strlen(s),strstr(d,strcpy(strcpy(d=alloca(l*2+1),s)+l,s)-1)-d-l+1;}

```

It turned out to be quite long but external functions are always like that. It came to my mind that I could rewrite every string function replacing them by a loop or a recursive one. But in my experience it would turn out longer and frankly I don't want to try that out.

After some research I saw solutions on high performance but not as clever (and short) as xnor's one. just to be original... i rewrote the same idea in c.

explanation:

```
int length,
    duplicate;
int is_repetition(char *input)
{
    // length = "abc" -> 3
    length = strlen(input);
    // alloca because the function name is as long as "malloc"
    // but you don't have to call free() because it uses the stack
    // to allocate memory
    // duplicate = x x x x x x + x
    duplicate = alloca(length*2 + 1);
    // duplicate = a b c 0 x x + x
    strcpy(duplicate, input);
    // duplicate = a b c a b c + 0
    strcpy(duplicate + length, input);
    if (strstr(duplicate,duplicate + length - 1) != duplicate + length - 1)
        // repetition
        // e.g. abab -> abababab -> aba[babab]
        // -> first occurence of [babab] is not aba[babab]
        // but a[babab]ab -> this is a repetition
        return 1;
    else
        // not repetition
        // e.g. abc -> abcabc -> ab[cabc]
        // -> first occurence of [cabc] is ab[cabc]
        // it matches the last "cabc"
        return 0;
}

```
> 2 votes

# Answer
# Jelly, 3 bytes

```
ṙJċ

```

Try it online!

Same as this answer (maybe the later challenge is a generalization of this one?).
> 2 votes

# Answer
# ECMAScript 6 (59 ~~62~~ ~~67~~ ~~73~~)

Not a winner, but seems like there should at least be one answer actually in ES6 for this question that actually uses the `repeat` function:

```
f=i=>[...i].some((_,j)=>i.slice(0,j).repeat(i.length/j)==i)

```

Must be run in the console of a ES6-capable browser such as Firefox.

It does a lot of unnecessary iterations, but why make it longer just to avoid that, right?

* *Edit #1:* Saved a few bytes by converting it into a function. Thanks to Optimizer!
* *Edit #2:* Thanks to hsl for the spread operator trick to save more bytes!
* *Edit #3:* And thanks to Rob W. for another 3 bytes!
> 1 votes

# Answer
# Java 8, 28 bytes

```
s->s.matches("(?s)(.+)\\1+")

```

Try it online.

**Explanation:**

Checks if the input-String matches the regex, where `String#matches` implicitly adds `^...$` to match the entire String.
Explanation of the regex itself:

```
^(s?)(.+)\1+$
^                Begin of the string
 (s?)            Enable DOTALL-mode, where `.` also matches new-lines
     (           Open capture group 1
      .+          One or more characters
        )        Close capture group 1
         \1+     Plus the match of the capture group 1, one or more times
            $    End of the string

```

So it basically checks if a substring is repeated two or more times (supporting new-lines).
> 1 votes

# Answer
# Vyxal, 6 bytes

```
żḢ/v≈a

```

Try it Online!

## Explained

```
żḢ/v≈a
  /    # Split the input string into pieces of
żḢ     # range [2, len(input)]
   v≈a # do any of those have all the same item

```
> 1 votes

# Answer
# J-uby, ~~51~~ ~~36~~ 25 bytes

Based on my Ruby answer. Returns the string for truthy and `nil` for falsy.

```
~:[]%(~:*&2|~:[]&(1..-2))

```

Attempt This Online!

This is equivalent to the lambda `->s{ (s*2)[1..-2][s] }`.
> 1 votes

# Answer
# Ruby `-nl`, 19 bytes

Another port of xnor's answer. Takes input on stdin; prints the string if it's repeated and `nil` otherwise.

```
p ($_*2)[1..-2][$_]

```

Attempt This Online!
> 0 votes

# Answer
# Japt, 6 bytes

```
²é ¤øU

```

Try it

Boring copy of the common logic from other answers:

```
²é ¤øU
²      # Duplicate the input
 é     # Move the last character to the front
   ¤   # Remove the first two characters
    øU # Return true if it still contains the input

```

# Japt, 6 bytes

```
¬x@¥éY

```

Try it

More interesting, but has a weirder output; `1` means `false`, any other output means `true`. Identical to this answer on a different challenge, but discovered separately.

Explanation:

```
¬x@¥éY
¬      # Convert input to an array of characters
 x@    # Apply a function to each one, then sum the results:
    éY #  Rotate the input string a number of times equal to the current index
   ¥   #  Return 1 if it's still equal to the input, 0 otherwise

```
> 0 votes

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


title: Minimal Fresh Substrings

text:
# Question
Title: Minimal Fresh Substrings
Thanks @NathanMerrill for allowing me to post this! The following is entirely his wording from this sandbox post (deleted):

---

We define a "Fresh" substring as a substring that is different from any other substring that starts earlier.

For example, if I take the string `"abababc"` and split it: `["ab","ab","a","bc"`\], the first and the last substring are fresh, but the middle two are not, because they can be found earlier in the string.

For this challenge, you need create a list of the smallest possible fresh substrings for each position in the string. If there are no fresh substrings, output and empty list or empty string, etc.

For example, if you were passed `"ABABCBA"`, you should return `["A","B","ABC","BC","C"]`.

Test Cases:

```
ABABCBA          A,B,ABC,BC,C,   // ABC instead of AB because there is an AB earlier in the string
AAAAAAA          A,,,,,,
ABCDEFG          A,B,C,D,E,F,G
ABDBABDAB        A,B,D,BA,ABDA,BDA,DA,,
ACABCACBDDABADD  A,C,AB,B,CAC,ACB,CB,BD,D,DA,ABA,BA,AD,,

```

The empty items are not mandatory.

# Answer
# PHP, 141 bytes

```
for($r=[];$i<$l=strlen($a=$argn);$i++)for($t=1;$t;$t*=$t<$l)in_array($s=substr($a,$i,$t),$r)|strpos($a,$s)<$i?$t++:$r[]=$s.$t="";print_r($r);

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~105 103 88 81~~ 79 bytes

-~~15~~ 24 bytes (!) thanks to user1502040

```
import Data.List
f s=[a|a:_<-zipWith(\\)<*>scanl(++)[]$map(tail.inits)$tails s]

```

Try it online!

`t` gets a list of lists of all of the substrings starting from each position.

`f` builds up that list using scanl, so at index i we have a list of all of the substrings possible before index i. At each index, we take the set difference between the substrings calculated in `t` and those made illegal by `f`, to get the legal substrings at that index.

The lists are guaranteed to be sorted by length, so we can finally just take the first item if it exists. It skips empty items, as they are "not mandatory" per the spec.

Still learning Haskell, so I'm sure I've done something odd somewhere. The `map head(filter(>[])` seems especially verbose to say "take the first item if exists, else nothing."
> 3 votes

# Answer
# C#, ~~175~~ 158 bytes

```
s=>{int i=0,j,l=s.Length;var a=new string[l];for(;i<l;++i)for(j=0;j<l-i;){var t=s.Substring(i,++j);if(!s.Substring(0,i).Contains(t)){a[i]=t;break;}}return a;}

```

Full/Formatted Version:

```
using System;

class P
{
    static void Main()
    {
        Func<string, string[]> f = s =>
        {
            int i = 0, j, l = s.Length;
            var a = new string[l];

            for (; i < l; ++i)
                for (j = 0; j < l - i;)
                {
                    var t = s.Substring(i, ++j);
                    if (!s.Substring(0, i).Contains(t))
                    {
                        a[i] = t;
                        break;
                    }
                }

            return a;
        };

        Console.WriteLine(string.Join(",", f("ABABCBA")));
        Console.WriteLine(string.Join(",", f("AAAAAAA")));
        Console.WriteLine(string.Join(",", f("ABCDEFG")));
        Console.WriteLine(string.Join(",", f("ABDBABDAB")));
        Console.WriteLine(string.Join(",", f("ACABCACBDDABADD")));

        Console.ReadLine();
    }
}

```
> 2 votes

# Answer
# Python 3, 136 bytes

```
l=[];n=input();a=len(n)
for x in range(a):
 i=x+1
 while n[x:i]in l or n[x:i]in n[:i-1]:
  i+=1
  if i>a:x=i;break
 l+=[n[x:i]]
print(l)

```

Try it online!

Includes the empty items
> 2 votes

# Answer
# Jelly,  ~~19~~  17 bytes

```
;\0;Ṗ
ṫJ;\€µḟ"ÇZḢ

```

A monadic link accepting a list of characters and returning a list of lists of characters.

**Try it online!** (the footer formats the list separating it with commas so it does not get implicitly printed as the representation would be smashed together).

### How?

```
;\0;Ṗ - Link 1, offset prefixes: list  e.g. [["x","xy","xyz"],["y","yz"],["z"]]
 \    - cumulative reduction with:
;     -   concatenation                     [["x","xy","xyz"],["x","xy","xyz","y","yz"],["x","xy","xyz","y","yz","z"]]
  0;  - prepend a zero                    [0,["x","xy","xyz"],["x","xy","xyz","y","yz"],["x","xy","xyz","y","yz","z"]]
    Ṗ - pop (head to penultimate)         [0,["x","xy","xyz"],["x","xy","xyz","y","yz"]]

ṫJ;\€µḟ"ÇZḢ - Main link: list of characters  e.g. "ABABC"
 J          - range of length                     [1,2,3,4,5]
ṫ           - tail                                ["ABABC","BABC","ABC","BC","C"]
   \€       - cumulative reduction for €ach with:
  ;         -   concatenation                    [["A","AB","ABA","ABAB","ABABC"],["B","BA","BAB","BABC"],["A","AB","ABC"],["B","BC"],["C"]]
     µ      - monadic chain separation, call that p
        Ç   - call last link as a monad with p - gets relevant substrings to not use (with a zero in place of an empty list for the first index)
            -                      ... that is:  [0,["A","AB","ABA","ABAB","ABABC"],["A","AB","ABA","ABAB","ABABC","B","BA","BAB","BABC"],["A","AB","ABA","ABAB","ABABC","B","BA","BAB","BABC","A","AB","ABC"],["A","AB","ABA","ABAB","ABABC","B","BA","BAB","BABC","A","AB","ABC","B","BC"]]
       "    - zip with:
      ḟ     -   filter discard                   [["A","AB","ABA","ABAB","ABABC"],["B","BA","BAB","BABC"],["ABC"],["BC"],["C"]]
         Z  - transpose                         [["A","B","ABC","BC","C"],["AB","BA"],["ABA"],["ABAB"],["ABABC"]]
          Ḣ - head                               ["A","B","ABC","BC","C"]

```
> 2 votes

# Answer
## JavaScript (ES6), 81 bytes

```
f=(s,t=0,u=t+1,v=s.slice(t,u))=>s.indexOf(v)<t?s[u]?f(s,t,u+1):[]:[v,...f(s,t+1)]
```

```
<input oninput=o.textContent=f(this.value).join`\n`><pre id=o>
```
> 2 votes

# Answer
# Retina, ~~19~~ 18 bytes

*-1 byte because empty items can be ommitted*

```
!&`(.+?)(?<!\1.+)

```

Try it online!

Explanation:

```
!                   Print matches as newline separated list
 &`                 Consider overlapping matches
   (.+?)            Capture the shortest possible substring
        (?<!\1.+)   Enforce freshness
              .+    Scan backwards
            \1      Fail if the match appears earlier in the string
                    If matching is impossible, skip this element

```
> 1 votes

# Answer
# Ruby, 77 bytes

```
->s,*a{s.scan(""){a<<(1..$'.size).map{$'[..._1]}.find{!($`+_1)[..-2][_1]}}
a}

```

Attempt This Online!
> 0 votes

# Answer
# Japt, 18 bytes

```
¬ËUsE å+ k@bX <EÃg

```

Try it

Outputs `null` when there are no fresh substrings

Explanation:

```
¬ËUsE å+ k@bX <EÃg
¬                  # Split the input into an array of characters
 Ë                 # For each index E:
  UsE              #  Get the suffix of the input with length E
      å+           #  Get all prefixes of that suffix
         k@     Ã  #  Remove the ones where:
           bX      #   The first time it appears in the input
              <E   #   Is before E
                 g #  Return the shortest one remaining

```
> 0 votes

# Answer
# Japt, 9 bytes

```
ã ü@bXÃmg

```

Try it

```
ã ü@bXÃmg     :Implicit input of string U
ã             :Substrings
  ü           :Sort and group by
   @          :Passing each X through the following function
    bX        :  First index of X in U
      Ã       :End grouping
       m      :Map
        g     :  First element

```
> 0 votes

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


title: Find the Translation Table

text:
# Question
Title: Find the Translation Table
Given two strings, find the translation table (substitution cipher) between the two, if the translation is not possible, output false. The answer must be minimized and created from left-to-right. The first character to be translated between words must be the first in the translation table. In addition to this, any letter that is not translated (in the same place as it was originally), should NOT be in the translation table.

Probably most easily defined through examples:

# Valid Cases

```
"bat", "sap" => ["bt","sp"]

```

Notice the ordering, an output of `["tb","ps"]` is not valid for this challenge.

```
"sense", "12n12" => ["se","12"]

```

Notice how the `n` isn't translated because it is a 1 to 1 relation.

```
"rabid", "snail" => ["rabd","snal"]

```

Notice how the `i` isn't translated because it is a 1 to 1 relation.

```
"ass", "all" => ["s","l"]

```

A is not included, it stays the same, `s` can map to `l` due to pattern match.

```
"3121212", "ABLBLBL" => ["312","ABL"]

```

Matches pattern perfectly.

# Falsy Cases

```
"banana", "angular" => false

```

(not the same length, impossible).

```
"animal", "snails" => false

```

(each character can only be used ONCE on each side of the translation).

```
"can","cnn" => false

```

(n is implicitly used in translation, therefore, defining a translation table with n-\>a would be invalid)

Thusly, `[aimal,sails]` is an invalid answer, making this falsy.

```
"a1", "22" => false

```

See "caveats", this is listed as falsy. In this case, it's because `a` and `1` cannot both map to `2`. (Each character can only be used ONCE on each side of the translation).

---

This answer seems to be a good benchmark: https://codegolf.stackexchange.com/a/116807/59376

If you have questions about the functionality of two unlisted word pairs, defer to this implementation.

---

# I/O rules

* Input may be as a 2 element array or as 2 separate inputs.
* Output can be as an array or newline/space delimited, similar to how I have it shown.
* False output may be 0, -1 or false. Erroring/Empty output is also fine.
* You are guaranteed that `a` will not equal `b` and neither `a` nor `b` will be empty.
* `a` and `b` are printable-ASCII-only sequences of letters.

# Caveats

* Translations must occur from left to right, see example 1.
* You must not output characters that remain the same.
* Your program may only take in two strings `a` and `b`.
* Each character can only be used ONCE on each side of the translation. This is what makes the translation from `snails` to `animals` impossible.
* Recursive replaces should not occur. Example of recursive replace: `"a1","22"->[a1,12]` where a is first replaced by a 1, then both resultant 1's are replaced with 2's. This is not correct, assume all translations occur independent of each other, meaning this is falsy. Meaning: ***"a1" with translation table of \[a1,12\] evaluates to 12 (not 22)***

# Answer
> 7 votes
# PHP \>=7.1, 130 Bytes

18 Bytes saved by @Titus

```
for([,$x,$y]=$argv;a&$o=$y[$i];)$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p;echo$y==strtr($x,$c)&$x==strtr($y,$k)?join($k)." ".join($c):0;

```

Testcases

Expanded

```
for([,$x,$y]=$argv;a&$o=$y[$i];)
$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p; # if char string 1 not equal char string 2 make key=char1 value=char2 and key array
echo$y==strtr($x,$c) # boolean replacement string 1 equal to string 2
    &$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

```

# PHP \>=7.1, 148 Bytes

prints 0 for false Output true as string

```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;echo$y==strtr($x,($f=array_flip)($k=$f($c)))&$x==strtr($y,$k)?join($k)." ".join($c):0;

```

Testcases

Expanded

```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
$x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo$y==strtr($x,($f=array_flip)($k=$f($c))) # boolean replacement string 1 equal to string 2
&$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

```

## PHP \>=7.1, 131 Bytes

The second answer can be shorted to this if associative arrays are allowed

prints 0 for false Output true as associative array instead of string

```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;print_r($y==strtr($x,($f=array_flip)($f($c)))&$x==strtr($y,$k)?$c:0);

```

Testcases

## PHP \>=7.1, 227 Bytes

prints 0 for false

```
[,$x,$y]=$argv;echo strlen($x)==strlen($y)?strtr($x,$c=array_filter(($f=array_flip)($z=$f(array_combine(($p=str_split)($x),$p($y)))),function($v,$k){return$k!=$v;},1))==$y&$x==strtr($y,$z)?join(array_keys($c))." ".join($c):0:0;

```

Testcases

Expanded

```
[,$x,$y]=$argv; #
echo strlen($x)==strlen($y) #compare string lengths
?strtr($x,  # replace function
$c=array_filter( # filter
($f=array_flip)($z=$f( # # remove doubles like in testcase: a1 => 22
    array_combine(($p=str_split)($x),$p($y))  # replacement array keys string 1 values string 2
))
    ,function($v,$k){return$k!=$v;},1)) # remove all keys that equal to values in array
    ==$y # boolean replacement string 1 equal to string 2
&$x==strtr($y,$z) # boolean replacement string 2 equal to string 1
?join(array_keys($c))." ".join($c) # output for true cases
    :0 # Output if replacement from string 1 is not equal to string 2
:0; #Output for different lengths

```

# Answer
> 7 votes
## JavaScript (ES6), 128 bytes

```
f=
(s,t)=>!t[s.length]&&[...s].every((c,i)=>n[d=t[i]]==c||d&&!m[c]&&!n[d]&&(n[m[c]=d]=c,c==d||(a+=c,b+=d)),m={},n={},a=b='')&&[a,b]
```

```
<div oninput=o.textContent=f(s.value,t.value)><input id=s><input id=t><pre id=o>
```

# Answer
> 7 votes
## JavaScript (ES6), ~~108~~ ~~107~~ ~~105~~ 106 bytes

***Edit****: Fixed to support inputs such as `"22" / "a1"` that should be falsy.*

---

Returns either `0` or an array of two strings.

```
f=(a,b,x)=>[...a].some((c,i)=>d[C=b[i]]?d[C]!=c:(d[C]=c)!=C&&(s+=c,t+=C,!C),s=t='',d=[])?0:x||f(b,a,[s,t])

```

### Formatted and commented

```
f = (                       // given:
  a,                        // - a = first string
  b,                        // - b = second string
  x                         // - x = reference result from previous iteration,
) =>                        //       or undefined
  [...a].some((c, i) =>     // for each character c at position i in a:
    d[                      //   if we already have a translation
      C = b[i]              //   of the character C at the same position in b,
    ] ?                     //   then:
      d[C] != c             //     return true if it doesn't equal c
    :                       //   else:
      (d[C] = c) != C &&    //     store the translation C -> c in the dictionary
      (                     //     if the characters are different:
        s += c, t += C,     //       append them to the translation strings s and t
        !C                  //       return true if C is undefined
      ),                    //
    s = t = '', d = []      //   initialize s, t and d
  ) ?                       // if some() returns true:
    0                       //   there was a translation error: abort
  :                         // else:
    x ||                    //   if this is the 2nd iteration, return x
    f(b, a, [s, t])         //   else do a recursive call with (b, a)

```

### Test cases

```
f=(a,b,x)=>[...a].some((c,i)=>d[C=b[i]]?d[C]!=c:(d[C]=c)!=C&&(s+=c,t+=C,!C),s=t='',d=[])?0:x||f(b,a,[s,t])

// truthy
console.log(f('bat','sap'))
console.log(f('sense','12n12'))
console.log(f('rabid','snail'))
console.log(f('ass','all'))
console.log(f('3121212','ABLBLBL'))

// falsy
console.log(f('banana','angular'))
console.log(f('animal','snails'))
console.log(f('a1','22'))
console.log(f('22','a1'))
console.log(f('aaa','bab'))
console.log(f('abc','abcd'))
console.log(f('abcd','abc'))
```

# Answer
> 5 votes
# Retina, ~~194~~ ~~191~~ ~~185~~ ~~229~~ ~~225~~ 241 bytes

```
.+
$&;$&
+`^\w(\w*;)\w
$1
^;\w.*|.+;;.*|;;

^((.)*)(.)(.*;(?<-2>.)*(?(2)(?!)))\3
$1$4
+`((.)(.)*)\2((.)*;.*(.)(?<-3>.)*(?(3)(?!)))\6((?<-5>.)*(?(5)(?!)))$
$1$4$7
^(.)*(.)(.)*(\2)?.*;(?<-1>.)*(?(1)(?!))(.)(?<-3>.)*(?(3)(?!))(?(4)(?!\5)|\5).*

```

Try it online!

Takes input `;`-separated. Output is also `;` separated. False inputs are signified by empty outputs.

I know this is painfully verbose, I am still trying to cut down bytes. Most of these bytes go into deleting false inputs.

### Edits

* It turns out that I had a significant flaw with my program. It's fixed now, but at the cost of over 40 bytes.
* Another mistake was found where my program did not declare the input `a1;22` false, but I was able to keep the program under 250 bytes after fixing it

### Explanation

(a more detailed explanation will be coming shortly)

First we have to check if the lengths of strings `a` and `b` are the same or not. If they are not, we delete everything.

Duplicates the input to preserve it while we do some length-testing.

```
.+                      Matches everything
$&;$&                   $& indicates the match, so $&;$& will duplicate the match and separate it with a semi-colon

```

Now in a loop, we delete the first character of `a` and the first character of `b` until one of the strings become empty.

```
+`                     Repeatedly (until no more substitutions could be made) replace
  ^\w                   A word character (letter or number) at the beginning
     (\w*;)             Capture Group 1: matches any number of word characters and a semicolon
           \w           And a word character after the semi-colon
                       with
$1                      The result of the first capture group

```

Now there are there possibilities for the "pattern space".

* `;;abc` Both strings are of equal length
* `def;;abc` `a` is longer than `b`
* `;def;abc` `b` is longer than `a`

Now we have to empty the input if the strings are not of the same length (scenarios 2 and 3). This is what this substitution below does. It removes text that matches scenarios 2 and 3.

```
^;\w.*|.+;;.*|;;

```

This removes characters that are not transliterated in strings `a` and `b`. `abc;1b2` =\> `ac;12`

```
^((.)*)(.)(.*;(?<-2>.)*(?(2)(?!)))\3
$1$4

```

After that, we have to remove duplicate characters. `sese;1212` =\> `se;12`, but this preserves inputs like `aba;123`

```
+`((.)(.)*)\2((.)*;.*(.)(?<-3>.)*(?(3)(?!)))\6((?<-5>.)*(?(5)(?!)))$
$1$4$7

```

Finally, we delete the input if there are duplicate characters that map to different characters like `aba;123` or `a1;22`.

```
^(.)*(.)(.)*(\2)?.*;(?.)*(?(1)(?!))(.)(?.)*(?(3)(?!))(?(4)(?!\5)|\5).*

```

And finally, remove duplicate characters.

# Answer
> 5 votes
# Jelly, 18 bytes

```
ẠaQ⁼µ€Ạ
z0EÐḟQZẋÇ$

```

Unnamed monadic link (one-input function) taking a list, which returns:
an empty list in the falsey cases; or
a list containing two lists of characters in the truthy cases.

**Try it online!** (the footer splits the list with a space to avoid printing a smushed representation)
...or see a test suite.

### How?

```
ẠaQ⁼µ€Ạ - Link 1, valid?: mapping list
    µ€  - perform the code to the left for €ach mapping entry
Ạ       -     none of mapping entry falsey? (this & Main's z0 handle unequal input lengths)
  Q     -     deduplicate mapping entry
   ⁼    -     is equal to mapping list? (non-vectorising)
 a      -     and
      Ạ - none falsey (both mapping lists must pass that test)
        - The whole function returns 1 if the mapping list is acceptable, 0 if not

z0EÐḟQZẋÇ$ - Main link: list of strings
z0         - transpose with filler 0 (unequal lengths make pairs containing zeros)
   Ðḟ      - filter discard:
  E        -     all equal? (removes the untranslated character pairs)
     Q     - deduplicate (removes the repeated translation pairs)
      Z    - transpose (list of pairs to pair of lists)
         $ - last two links as a monad:
       ẋ   -     repeat list this many times:
        Ç  -         call last link (1) as a monad

```

# Answer
> 4 votes
# Jelly, ~~28~~ 26 bytes

```
QL$€⁼L€
EÐḟQZK0Ç?
ZÇ0L€E$?

```

Try it online!

```
QL$€⁼L€      Checks validity of mapping
QL$€          number of unique characters in mapping
    ⁼         equals
     L€       number of characters in mapping

EÐḟQZK0Ç?  Writes valid mapping or 0
EÐḟ           filter maps where a = b
   Q          filter duplicate maps
    Z         zip by column [["ac"],["bd"]] => ["ab","cd"]
     K0Ç?   print if valid map, else print 0

ZÇ0L€E$?      main link: takes an array of 2 strings
Z              zip by column: ["ab", "cd"] => [["ac"],["bd"]]
 Ç     ?       print mapping if
   L€E$         all pairs are same length (returns 0 if initial strings were
  0             else 0

```

# Answer
> 3 votes
# Ruby, 133 bytes

```
->a,b{a.size!=b.size||(m=a.chars.zip b.chars).any?{|i,j|m.any?{|k,l|(i==k)^(j==l)}}?0:m.select{|x,y|x!=y}.uniq.transpose.map(&:join)}

```

Try it online!

More readably:

```
->a, b{
    # Pair the letters in each string - [AB, AB, AB,...]
    pairs = a.chars.zip(b.chars)

    # If there's any combination of two pairs that share one character but not both,
    # or if the strings have different lengths, then the input's invalid.
    if a.size != b.size || pairs.any?{|i,j| pairs.any? {|k, l| (i==k)!=(j==l) }}
        return 0 # 0 isn't actually falsy in Ruby, but this challenge allows it anyway
    end
    return pairs.select{|x,y| x != y} # Remove unchanged letters
                .uniq                 # Remove duplicates
                .transpose            # Change [AB, AB, AB] form to [AAA, BBB] form.
                .map(&:join)          # Convert the arrays back into strings
}

```

Just for kicks, here's an 84 byte version in Goruby, which is Ruby, but with a golf flag set when compiling the interpreter. Among other things, it allows you to abbreviate method calls to their shortest unique identifier.

```
->a,b{a.sz!=b.sz||(m=a.ch.z b).ay?{|i,j|m.y?{|k,l|(i==k)^(j==l)}}?0:m.rj{|x,y|x==y}.u.tr.m(&:j)}

```

# Answer
> 3 votes
# Python 3.6, ~~211~~ ~~185~~ ~~181~~ 178 bytes

Exits with an error for falsy results.

```
def f(x,y,d={}):
    for a,b in zip(x,y):1/(a not in d or b==d[a]or len(x)-len(y));d[a]=b;1/([*d.values()].count(b)<2)
    return map(''.join,zip(*[x for x in d.items()if x[0]!=x[1]]))

```

This requires Python 3.6, which you can run in a shell here.

You can test it *without the correct output ordering* on TIO here. (TIO doesn't have 3.6).

**Ungolfed:**

```
from collections import*
d=OrderedDict()                     # keep order
x,y=input()
if len(x)!=len(y):1/0               # equal lengths
for a,b in zip(x,y):
    if a in d and d[a]!=b:1/0       # no duplicate keys
    else:d[a]=b
    if d.values().count(b)>1:1/0    # no duplicate values
print map(''.join,zip(*[x for x in d.items()if x[0]!=x[1]])) # format, no no-ops

```

If only order didn't matter...

# Answer
> 3 votes
# Python 2, ~~198,193,189,182,179,175,169,~~165 bytes

```
def f(a,b):
 r=([""]*2,0)[len(a)!=len(b)]
 for u,v in zip(a,b):
	if r:
		q,w=r
		f=q.find(u)
		if u!=v:r=(([q+u,w+v],r)[f>-1 and w[f]==v],0)[f<0 and v in w]
 print r

```

Try it online!

* -4 bytes! thanks to mbomb007 for suggesting the use of tab instead of space.
* modified the input format, again thanks to mbomb007.

# Answer
> 2 votes
# Röda, ~~108~~ 119 bytes

```
{c=[{_<>_|[[_,_]]|orderedUniq}()]d=[]e=[]c|_|{{d+=a;e+=b}if[a!=b]}for a,b[d,e]if[0,1]|{|n|c|[_[n]]|sort|count|[_2=1]}_}

```

Try it online!

This is a function that takes two lists of characters from the stream and pushes two lists to the stream.

This could be sorter if I was allowed to return pairs.

Explanation (out-dated):

```
{
    c=[{
        _<>_|       /* pull two lists and interleave them */
        [[_,_]]|    /* "unflat", create lists from pairs */
        orderedUniq /* remove duplicates */
    }()]            /* c is a list of the pairs */
    d=[]
    e=[]
    c| /* push the pairs to the stream */
    _| /* flat */
    {  /* for each pair (a, b): */
        { /* if a != b (remove "1-to-1 relations"):  */
            d+=a;
            e+=b
        }if[a!=b]
    }for a,b
    /* return d and e if no character is mapped to more than one character */
    [d,e]if c|[_[0]]|sort|count|[_2=1]
}

```

Here's an underscore solution that contains no variables (114 bytes):

```
{[[{_<>_}()|[[_,_]]|unorderedUniq]]|[[_()|_|[_]if[_1!=_2]],[_1()|_|[_2]if[_1!=_2]]]if[[_1()|_][::2],[_1()|_][1::2]]|[sort(_)|count|[_2=1]]}

```

That's a lot of underscores.

# Answer
> 1 votes
# AWK, 140 bytes

```
BEGIN{RS="(.)"}RT~/\W/{S=1}RT~/\w/&&S{if(RT!=x=A[++b]){if(B[z=RT]==""){B[z]=x
c=c x
d=d z}a=B[z]!=x?0:a}}!S{A[++a]=RT}END{if(a==b)print c,d}

```

Usage: Place code in `FILE` then:

```
awk -f FILE <<< "string1 string2"

```

The input strings need to be whitespace separated.

The output is empty if they fail, or 2 strings separated by a space.

# Answer
> 1 votes
# k, 28 bytes

```
{$[(y?y)~x?x;+?(~=/)#x,'y;]}

```

Explanation:

```
{                          } /function that takes in two strings, x and y
 $[         ;            ;]  /if statement (to check if there is a mapping)
         x?x                 /first index of [each letter in x] in x
   (y?y)                     /first index of [each letter in y] in y
        ~                    /make sure they match
                     x,'y    /zip together the two strings
               (~=/)#        /remove equal pairs
              ?              /unique pairs only
             +               /transpose ("unzip", in a way)

```

# Answer
> 1 votes
# APL (Dyalog) with AGL, 22 bytes

```
{≡/⍳⍨¨⍺⍵:↓⍉↑∪⍺(≠é,¨)⍵}

```

Try it online!

`{``}` anonymous function:

If…

`⍺⍵` the arguments

`⍳⍨¨` when self-indexed (i.e. the first occurrences of their elements in themselves)

`≡/` are equivalent

`:` then:

`⍺(``)⍵` apply the following tacit function to the arguments:

concatenate corresponding elements (errors on mismatching lengths)

`é` then filter by (`é` is just the primitive function `/`)

where the strings are different

unique (remove duplicates)

`↓⍉↑` transpose list-of-pairs to pair-of-lists (lit. mix into table, transpose table, split into lists)

else, do nothing

# Answer
> 0 votes
## CJam, 38 bytes

```
{_:,~={1\/;}:K~z{)\c=!},L|z_{_L|=K}%;}

```

Input and output are arrays on the stack.

# Answer
> 0 votes
# PHP (\>=7.1), 165 bytes

```
for([,$x,$y]=$argv;a&$c=$x[$i];$t[$c]=$d)$z+=($d=$y[$i++])&&$d==($t[$c]??$d);foreach($t as$a=>$b)$a==$b?:$r[$a]=$b;print_r($z<$i|array_unique($r)<$t||a&$y[$i]?0:$t);

```

prints `0` for falsy, associative array else. Run with `-r` or test it online.

**breakdown**

```
for([,$x,$y]=$argv;         # import arguments to $x and $y
    a&$c=$x[$i];            # loop through $x
    $t[$c]=$d)                  # 2. add pair to translation
$z+=                            # 1. increment $z if
    ($d=$y[$i++])&&             # there is a corresponding character in $y and
    $d==($t[$c]??$d);           # it equals a possible previous replacement
                            # remove identities from translation
foreach($t as$a=>$b)$a==$b?:$r[$a]=$b;
print_r(
    $z<$i                   # if not all tests passed
    |array_unique($t)<$t    # or there are duplicates in the translation
    ||a&$y[$i]              # or $y has more characters
    ?0                      # then print 0
    :$r                     # else print translation
);

```

# Answer
> 0 votes
# Ruby, 96 bytes

Throws an error for a negative result.

```
->a,b,**h{a.chars.zip(b.chars){(h[_1]&&h[_1]!=_2)?fail: h[_1]=_2}
h.map(&:join).grep_v(/(.)\1/)}

```

Attempt This Online!

---
Tags: code-golf, natural-language
---


title: Help me pair my socks

text:
# Question
Title: Help me pair my socks
*Disclaimer:* This challenge inspired by me trying to find pairs in a large pile of socks.

*Disclaimer:* This is looking for a very different process and output to Help me sort my socks!. Please don't claim it as a duplicate until you've read both ;)

---

So, I have a huge pile of socks. Of course I keep them categorized by compatibility number. Compatible socks, which I can wear together, have the same number. (Of course, every programmer does this).

My super-convenient plot device quickly scans the pile and outputs an array of compatibility numbers for the pile. It looks a bit like this:

```
[2, 3, 3, 6, 0, 4, 9, 1, 6, 7, 11, 3, 13, 3,
5, 12, 2, 1, 10, 2, 1, 11, 2, 13, 12, 10, 1,
7, 0, 0, 12, 12, 6, 2, 13, 6, 10, 0, 0, 12,
5, 0, 2, 3, 4, 0, 5, 8, 1, 6, 9, 7, 10, 14,
10, 8, 3, 8, 9, 8, 5, 11, 7, 9, 9, 9, 7, 14,
4, 2, 8, 14, 3, 11, 12, 14, 7, 13, 11, 13, 4,
7, 5, 12, 3, 1, 12, 4, 5, 13, 2, 13, 2, 14, 1,
13, 11, 1, 4, 8]

```

That's good data, but it's about as much use to me as scanning the pile myself by eye. What I want to know is how many compatible pairs I need to look for, and which are going to be 'odds', which I can discard for now.

In the above example, I am looking for these pairs of socks:

```
{3=>4, 6=>2, 2=>4, 1=>4, 11=>3, 13=>4, 12=>4, 10=>2, 7=>3, 0=>3, 5=>3, 4=>3, 9=>3, 8=>3, 14=>2}

```

(4 pairs of number 3, 2 pairs of number 6 etc.)

And these numbers will have 'odd ones out'. When I've found all the pairs for these, I can discard the last one.

```
[0, 6, 10, 7, 2, 14]

```

---

# The challenge

* Convert a list of compatible numbers to a count of pairs for each number and an array of 'odds'.
    + The pairs will be composed of a data structure (hash, or other) showing how many pairs can be made of each compatibility number (can be skipped if no pairs can be made).
    + The odds will be composed of a list of numbers which occur and odd number of times in the array.
* The order of the outputs is not significant.
* The size of my sock pile can, of course, be arbitrarily large.

# The Rules

* It's golf, make it short.
* No standard loopholes.
* Use any language you like.
* Please include a link to an online interpreter.

# Test Cases

Input: `[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]`

Output:

Pairs: `{2=>1, 3=>1, 4=>2, 5=>2}`

Odds: `[1, 3, 5]`

---

Input: `[2, 3, 3, 6, 0, 4, 9, 1, 6, 7, 11, 3, 13, 3, 5, 12, 2, 1, 10, 2, 1, 11, 2, 13, 12, 10, 1, 7, 0, 0, 12, 12, 6, 2, 13, 6, 10, 0, 0, 12, 5, 0, 2, 3, 4, 0, 5, 8, 1, 6, 9, 7, 10, 14, 10, 8, 3, 8, 9, 8, 5, 11, 7, 9, 9, 9, 7, 14, 4, 2, 8, 14, 3, 11, 12, 14, 7, 13, 11, 13, 4, 7, 5, 12, 3, 1, 12, 4, 5, 13, 2, 13, 2, 14, 1, 13, 11, 1, 4, 8]`

Output:

Pairs: `{3=>4, 6=>2, 2=>4, 1=>4, 11=>3, 13=>4, 12=>4, 10=>2, 7=>3, 0=>3, 5=>3, 4=>3, 9=>3, 8=>3, 14=>2}`

Odds: `[0, 6, 10, 7, 2, 14]`

---

Input: `[1, 2, 1, 2]`

Output:

Pairs: `{1=>1, 2=>1}`

Odds: `[]`

---

Input: `[1,2,3]`

Output:

Pairs `{}`

Odds: `[1,2,3]`

---

Input: `[]`

Output:

Pairs: `{}`

Odds: `[]`

# Answer
# Perl 6, 46 bytes

```
{.kv.map(*=>*+>1),.keys.grep:{.{$^k}%2}}o*.Bag

```

Try it online!

### Explanation

```
{                                      }o*.Bag  # Convert to Bag and feed into block
                 ,  # 2-element list
 .kv  # Key-value list (key is sock type, value is count)
    .map(       )  # Map to
         *=>*+>1   # Pair of sock type and count right-shifted by 1
                  .keys  # Keys (sock types)
                       .grep:  # Filter
                             {.{$^k}%2}  # Count is odd

```
> 8 votes

# Answer
# Python 3.8, ~~85~~ ~~78~~ ~~73~~ 72 bytes

```
lambda s:{*((c,(d:=s.count)(c)//2)for c in s),*(c for c in s if d(c)%2)}

```

Try it online!

---

Output is a list where pairs are tuples, `(a, b)` rather than `a => b`, and odds are not part of a tuple.

There's a sub-70 in here somewhere just staring at me, I can feel it...

**Previous Version (73 bytes):**

```
lambda s:{*((c,s.count(c)//2)for c in s),*(c for c in s if s.count(c)%2)}

```
> 7 votes

# Answer
# 05AB1E, 11 bytes

```
¢2÷øê,¢ÉÏê,

```

Try it online!

```
¢              # count occurences of each element in the input
 2÷            # integer divide by 2
   ø           # zip with the input
    ê          # sort and uniquify
     ,         # output (this is the list of pairs counts)
¢              # count occurences of each element in the input
 É             # mod 2
  Ï            # filter the input, keep only where the above is 1
   ê           # sort and uniquify
    ,          # output (this is the list of singles)

```
> 7 votes

# Answer
# 05AB1E, ~~23~~ 21 bytes

```
{γεÙygª}Dε`2÷‚}sø`ÉÏ‚

```

Outputs as a pair of lists, where both are ordered ascending by key. Also includes the optional value=0 pairs in the output, like all answers.

(Initially) inspired by *@Malivil*'s C# answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
{           # Sort the (implicit) input-list
            #  i.e. [4,2,3,3,1,3,2,4,4,3,4,3] → [1,2,2,3,3,3,3,3,4,4,4,4]
 γ          # Split it into groups of the same keys
            #  i.e. [1,2,2,3,3,3,3,3,4,4,4,4] → [[1],[2,2],[3,3,3,3,3],[4,4,4,4]]
            # (this is shorter than the regular (unsorted) group-by `.¡}`)
  ε         # Map each inner list `y` to:
   Ù        #  Uniquify the list, so a single key wrapped in a list remains
            #   i.e. [3,3,3,3,3] → [3]
    yg      #  Push the list `y` again, and pop and push its length (the count)
            #   i.e. [3,3,3,3,3] → 5
      ª     #  Append it to the 'key-list' to create the key-count pair
            #   i.e. [3] and 5 → [3,5]
            #  i.e. [[1],[2,2],[3,3,3,3,3],[4,4,4,4]] → [[1,1],[2,2],[3,5],[4,4]]
  }D        # After the map: duplicate the list of key-count pairs
    ε       # Map it to:
     `      #  Push key and count separated to the stack
            #   i.e. [3,5] → 3 and 5
      2÷    #  Integer-divide the count by 2
            #   i.e. 5 → 2
        ‚   #  And pair them back together
            #   i.e. 3 and 2 → [3,2]
            #  i.e. [[1,1],[2,2],[3,5],[4,4]] → [[1,0],[2,1],[3,2],[4,2]]
    }s      # After this map: swap to get the initial duplicated key-count pairs again
      ø     # Zip/transpose; swapping rows/columns
            #  i.e. [[1,1],[2,2],[3,5],[4,4]] → [[1,2,3,4],[1,2,5,4]]
       `    # Push both lists separated to the stack
        É   # Check for each count whether it is odd
            #  i.e. [1,2,5,4] → [1,0,1,0]
         Ï  # Only leave the keys at the truthy indices
            #  i.e. [1,2,3,4] and [1,0,1,0] → [1,3]
          ‚ # And pair it together with the earlier created list of key-count//2 pairs
            # (after which the result is output implicitly)

```
> 6 votes

# Answer
# APL (Dyalog Unicode), 23 bytesSBCS

Anonymous tacit prefix function. Prints (unique sock number, count of pairs) pairs, then prints list of odds.

```
∊{⊂(2|≢⍵)/⊃⎕←⍺,⌊2÷⍨≢⍵}⌸

```

Try it online!

`{``}⌸` on each (unique sock number, its indices in sock list):

indices in sock list; `[4,5,6]`

count them; `3`

`2÷⍨` let two divide them; `1.5`

round down; `1`

`⍺,` prepend sock number; `[3,1]`

`⎕←` send to console; `"3 1\r"`

pick the first (the sock number); `3`

`(``)/` make this many copies of that:

`≢⍵` the count of indices; `3`

`2|` the 2-mod of that (i.e. "is it odd?"); `1`

enclose so all the results will be self-contained; `[1]`

**ϵ**nlist (flatten); `[1,3,5]`
> 6 votes

# Answer
# Python 2, 68 bytes

```
lambda A:({v:A.count(v)/2for v in A},{v for v in A if A.count(v)%2})

```

Try it online!

Outputs a `dict` containing the number of pairs, and a `set` of left-over sock ids.
> 6 votes

# Answer
# , 47 bytes

```
S=table(scan());S[S%/%2>0]%/%2;names(S[!!S%%2])

```

Try it online!

Returns a `table` with `names` equal to the compatibility number and the pair counts as the values, as well as the compatibility numbers (as strings) of unpaired socks.
> 5 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~162~~ ~~154~~ ~~136~~ ~~128~~ 108 bytes

```
a=>(a.GroupBy(x=>x).Select(x=>(x.Key,x.Count()/2)),a.GroupBy(x=>x).Where(x=>x.Count()%2>0).Select(x=>x.Key))

```

Try it online!

-8 bytes thanks to @Kevin Cruijssen for pointing out an unnecessary variable

-18 more bytes thanks to @Kevin Cruijssen for letting me know the 0 rule was made optional and changing the return type from dynamic to array

-8 bytes thanks to @my pronoun is monicareinstate for in-lining the grouping assignment which changes this to a true one-liner

-20 bytes thanks to @Innat3 for changing the grouping to remove an un-needed comparison
> 4 votes

# Answer
# , ~~39~~ ~~27~~ ~~26~~ 24 bytes

```
~.((,.<.@-:);[#~2|])#/.~

```

Try it online!

*-2 bytes thanks to ngn*
> 4 votes

# Answer
# JavaScript (ES10),  ~~91~~  82 bytes

Returns `[odds_array, pair_object]`.

```
a=>[[...new Set(a)].flatMap(v=>(a.map(x=>n+=v==x,n=0),o[v]=n>>1,n&1?v:[]),o={}),o]

```

Try it online!

### Commented

```
a => [               // a[] = input array
  [...new Set(a)]    // build the set of distinct values in a[]
                     // and turn it back into an array
  .flatMap(v =>      // for each value v in there:
    ( a.map(x =>     //   count the number n of values in the original array
        n += v == x, //   that are equal to v
        n = 0        //   start with n = 0
      ),             //
      o[v] =         //   set o[v] to
        n >> 1,      //     floor(n / 2)
      n & 1 ? v : [] //   yield v if n is odd, or [] otherwise
    ),               //
    o = {}           //   o = object holding the number of pairs
  ),                 // end of flatMap()
  o                  // append o
]                    //

```
> 3 votes

# Answer
# Pyth, 17 16 bytes

```
,R//Qd2{Qf%/QT2{

```

Try it online!

-1 byte thanks to @isaacg

Two separate operations, returns two separate lists. Includes zero-pairs, which I believe is optional? Can fix at the cost of 2 bytes, if not allowed, by prepending e# -\> `e#,R//Qd2{Qf%/QT2{`

## How it works

```
,R//Qd2{Qf%/QT2{
,R//Qd2{Q            -- Returns pairs
 R      {Q            -  Right map to the input cast to a set
,                     - A two element list starting with the element of the set (implicit)
   //Qd2              - ...and ending with the count of that element in the input/2
          f%/QT2{     -- Returns odds
          f     {     - Filter the implicit input cast to a set
            /QT       - By the count of each element of the set in the input
           %   2      - Modulo 2

                        Both lists print implicitly

```
> 3 votes

# Answer
# Python 3.8 (pre-release), 63 bytes

```
lambda s:sum([[(c,(d:=s.count(c))//2)]+d%2*[c]for c in{*s}],[])

```

Try it online!

Outputs a list, with tuples `(a, b)` indicating pair counts and solitary elements indicating left over socks.

Interestingly, the `hash` function on integers seems to be the identity function, and so the output is conveniently ordered `[(0, count of 0 pairs), 0 if 0 has odd count, (1, count of 1 pairs), 1 if 1 has odd count, ...` as long as a contiguous sequence of numbers starting at 0 is used for sock indicators.
> 3 votes

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

```
a=>[a.filter(n=>p[n]?0:(a.map(m=>c+=m==n,c=0),p[n]=c>>1,c%2),p={}),p]

```

Try it online!

```
a=>[
  a.filter(n=>               // Filter out paired ones, return unpaired (odd) ones
    p[n]?0:                  // If we already paired it, skip
    (
      a.map(m=>c+=m==n,c=0), // Count
      p[n]=c>>1,             // Count / 2 pairs found
      c%2                    // If count % 2 != 0, there is an odd one
    ),
    p={}                     // Initial pairs dictionary
 ),p]

```
> 3 votes

# Answer
# Japt, ~~17~~ 16 bytes

```
ü
lu mÎp¡[XÎXÊz]

```

Output is an array of the format:
`[O1,O2,...On,[[V1,P1],[V2,P2],...[Vn,Pn]]]`
where `O`s are odds, `V`s are values and `P`s are pairs.

Try it (Footer formats the output for easier reading)
> 2 votes

# Answer
# C (gcc), 155 154 151 bytes

Thanks to ceilingcat for the suggestion.

I use `-1` as the sentinel value for the list. First, I count the length of the input list, then I increment a count array at the index pointed into from the input. Lastly, I print the pairs in `type:number of pairs` format, then any singles remaining.

I initialize `c` to zero even though it's a global because it won't necessarily be zero at the end of the function and I need to have it set correctly at the start of the function. I also use a dynamically-allocated count array so that it will be zero-initialized.

```
d,c,*a;f(int*i){for(c=0;~i[c++];);for(a=calloc(d=c,4);d--;a[i[d]]++);for(d=c;d--;)a[d]&&printf("%d:%d\t",d,a[d]/2);for(;c--;)a[c]%2&&printf("%d\t",c);}

```

Try it online!
> 2 votes

# Answer
# APL(NARS), chars 66, bytes 132

```
{∨/c←×b←⌊2÷⍨≢¨a←a⊂⍨1+a←⍵[⍋⍵]:(⊂c/b,¨∪¨a),⊂∪⊃∪/a/⍨0≠2∣≢¨a⋄(⊂⍬),∪/a}

```

test:

```
  f←{∨/c←×b←⌊2÷⍨≢¨a←a⊂⍨1+a←⍵[⍋⍵]:(⊂c/b,¨∪¨a),⊂∪⊃∪/a/⍨0≠2∣≢¨a⋄(⊂⍬),∪/a}
  ⎕fmt f 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
┌2─────────────────────────────────────┐
│┌4──────────────────────────┐ ┌3─────┐│
││┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│ │ 1 3 5││
│││ 1 2│ │ 1 3│ │ 2 4│ │ 2 5││ └~─────┘│
││└~───┘ └~───┘ └~───┘ └~───┘2         │
│└∊──────────────────────────┘         3
└∊─────────────────────────────────────┘
  ⎕fmt f 1 2 1 2
┌2───────────────────┐
│┌2────────────┐ ┌0─┐│
││┌2───┐ ┌2───┐│ │ 0││
│││ 1 1│ │ 1 2││ └~─┘│
││└~───┘ └~───┘2     │
│└∊────────────┘     3
└∊───────────────────┘
  ⎕fmt f 1 2 3
┌2────────────┐
│┌0─┐ ┌3─────┐│
││ 0│ │ 1 2 3││
│└~─┘ └~─────┘2
└∊────────────┘
  ⎕fmt f ⍬
┌2────────┐
│┌0─┐ ┌0─┐│
││ 0│ │ 0││
│└~─┘ └~─┘2
└∊────────┘

```

but if it not be "codegolf" i would write for question of readability this 93 bytes code:

```
c←{+/⍵=⍺}⋄f←{0=≢a←⍵:⍬⍬⋄(⊂{×≢b←({0≠⌊2÷⍨⍵c a}¨b)/b←∪⍵:b,¨{⌊2÷⍨⍵c a}¨b⋄⍬}⍵),⊂∪({0≠2∣⍵c a}¨a)/a}

```

because `({0≠⌊2÷⍨⍵c a}¨b)/b` or exprestion as that has to be idiomatic... `g(f¨b)/b` traslate the math set `{g(x):x∊b∧f(x)}`.
> 2 votes

# Answer
# Jelly, 14 bytes

```
ṢŒrH2¦€,ṪḂ$ƇƊḞ

```

Try it online!

Somehow, before I stepped back for a bit and questioned my decisions leading up to it, my original solution was going to be `ṢŒrZd2¦2Zµ1,[2,1]œịⱮ,ṪṪ$Ƈ`. I may have gotten a bit too attached to using divmod...
> 2 votes

# Answer
# Brachylog, 18 bytes

```
ọ{÷₂ᵗ}ᵐ|ọ{t%₂1&h}ˢ

```

Try it online!

Generates the output, since it saves a byte over using a fork: `ọ⟨{÷₂ᵗ}ᵐ≡{t%₂1&h}ˢ⟩`

```
       |              The output is
ọ                     the list of pairs [unique element of input, # of occurrences]
 {   }ᵐ               with each pair
    ᵗ                 's last element
  ÷₂                  divided by 2 (rounding down),
       |              or
       |ọ             that same list of pairs
         {      }ˢ    filtered by
          t           the last element
           %₂         mod 2
             1        being 1,
         {    & }ˢ    and mapped to
               h      each pair's first element.

```
> 2 votes

# Answer
# 05AB1E, 18 bytes

```
{ÅγU©X2‰ø`.Áø,®sÏ,

```

Try it online!

```
{       sort input
Åγ      push run-length encoded input (count each element of input)
U©X     save compatibility number in ® and count in X
2‰      divmod count by 2 (for each compatibility number, get the count of pairs and info if a single sock is remaining)
ø       split that into a list of pair counts and a list of single socks
`       push those lists onto the stack
.Á      rotate the stack, so list of compatibility numbers and the list of pair counts are at the top of the stack
ø       zip them (for each compatibility number, get the pair count)
,       print that
®       push another list of compatibility numbers
s       swap with the list of single socks
Ï       keep only compatibility numbers of single socks
,       print that

```
> 2 votes

# Answer
# Red, 169 bytes

```
func[a][b: copy[]m: copy#()foreach n a[alter b n unless
m/:n[put m n 0]m/:n: m/:n + 1]foreach k keys-of
m[t: m/:k either t = 1[remove/key m k][m/:k: t / 2]]insert b m b]

```

Doesn't work in TIO (Apparently `remove/key` is added only recently). It works fine in the Red GUI console:

`#()` is a map structure, the list of single socks is after it.
> 2 votes

# Answer
# K4, ~~27~~ 25 bytes

**Solution:**

```
(,#:'=&_p),,&p>_p:.5*#:'=

```

**Example:**

```
q)k)(,#:'=&_p),,&p>_p:.5*#:'=1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
2 3 4 5!1 1 2 2
1 3 5
// this is how a dictionary looks in the repl
q)k)*(,#:'=&_p),,&p>_p:.5*#:'=1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
2| 1
3| 1
4| 2
5| 2

```

**Explanation:**

```
(,#:'=&_p),,&p>_p:.5*#:'= / the solution
                        = / group input
                     #:'  / count (#:) each
                  .5*     / half (ie pair up)
                p:        / save as p
               _          / floor
             p>           / p > floor p? ie find whole pairs
            &             / where true
           ,              / enlist
          ,               / join
(        )                / do all this together
       _p                 / floor p
      &                   / where
     =                    / group
  #:'                     / count (#:) each
 ,                        / enlist

```

**Extra:**

* **-2 bytes** thanks to ngn
> 2 votes

# Answer
# Zsh, ~~81~~ 74 bytes

*-3 bytes by testing set difference in arithmetic mode instead, -4 bytes by using `local` instead of `typeset`*

```
local -A p
for x;a=(${a:#$x} ${x:|a})&&((${#x:|a}&&++p[$x]))
local p
<<<$a

```

~~Try it online!~~  Try it online!

The expansion `a=(${a:#$x} ${x:|a})` puts `$x` in `$a` if it isn't there, and takes it out if it is. Then we check if `$x` just got removed, and increment our pair count if it was.

---

With a looser definition of "list", we can shave this quite a bit.

# Zsh, ~~56~~ 52 bytes

```
local -A p l
for x;((p[$x]+=1^(l[$x]^=1)))
local p l

```

~~Try it online!~~  Try it online!

Prints the leftover socks as all elements in an associative array with value `1`, not `0`.
> 2 votes

# Answer
# \[Python 2.x or 3.x\], ~~52~~ 43 bytes (thanks to isaacg)

Retruns a Python dict with a tuple as value: `(<pairs of socks>, <1 if a sock remains; 0 otherwise>)`. As fas as I understand this comment of the OP, this is now within spec. Please let me know if this is (still) not the case.

```
lambda s:{c:divmod(s.count(c),2)for c in s}

```

Try it online!

Output for the example case in the question:

```
{2: (4, 1), 3: (4, 0), 6: (2, 1), 0: (3, 1), 4: (3, 0), 9: (3, 0), 1: (4, 0), 7: (3, 1), 11: (3, 0), 13: (4, 0), 5: (3, 0), 12: (4, 0), 10: (2, 1), 8: (3, 0), 14: (2, 1)}

```
> 1 votes

# Answer
# Perl 5, 82 bytes

```
sub{my%H;$H{$_}++for@_;delete@H{@A=grep$H{$_}%2,keys%H};map$_/=2,values%H;\%H,\@A}

```

Try it online!

# (`-ap`), 73 bytes

Returning hash as key value pairs list

```
s/(\b\d+)( .*)(\b\1\b)/$H{$1}++;$2/e&&redo;delete@H{@F};$_="@{[%H]} | @F"

```

Try it online!
> 1 votes

# Answer
# Charcoal, 50 bytes

```
≔⦃⦄ηＦθ«Ｆ¬№υι«⊞υι§≔ηι⁰»§≔ηι⊕§ηι»ＩＥυ⟦ι÷§ηι²⟧ＩΦυ﹪§ηι²

```

Try it online! Unfortunately I don't know how to get the deverbosifier to output `⦃⦄` (I just get `«»` when I try). Explanation:

```
≔⦃⦄η

```

Initialise a dictionary.

```
Ｆθ«

```

Loop over the socks.

```
Ｆ¬№υι

```

Test whether the compatibility number has been seen before. (Sadly Charcoal has no functions for determining dictionary keys, so I have to use a parallel list.)

```
«⊞υι§≔ηι⁰»

```

If it hasn't been seen then push the number to the list and zero out its dictionary entry.

```
§≔ηι⊕§ηι»

```

Increment the dictionary entry.

```
ＩＥυ⟦ι÷§ηι²⟧

```

Output the number of pairs for each compatibility number. The compatibility number and number of pairs are output on separate lines, with each pair of numbers double-spaced.

```
ＩΦυ﹪§ηι²

```

Output those compatibility numbers with odd socks, each on their own line.

52 bytes for a deverbosifier-friendly version:

```
Ｆθ«≔Φυ⁼ι§κ⁰η¿η≔⊟ηη«≔⟦ι⁰⟧η⊞υη»ＵＭη⁺κλ»ＩＥυＥι÷λ⊕μＩΦυ﹪⊟ι²

```

Try it online! Link is to verbose version of code. Outputs the odd sock compatibility numbers double-spaced.

56 bytes for the original (IMHO better) condition that disallows printing zero pairs of socks:

```
Ｆθ«≔Φυ⁼ι§κ⁰η¿η≔⊟ηη«≔⟦ι⁰⟧η⊞υη»ＵＭη⁺κλ»ＩΦＥυＥι÷λ⊕μ§ι¹ＩΦυ﹪⊟ι²

```

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

Would be 43 bytes if Charcoal supported dictionary iteration:

```
≔⦃⦄ηＦθ§≔ηι∨⬤η⁻ιλ⊕§ηιＩΦＥη⟦κ÷ι²⟧§ι¹ＩΦＥηκ﹪§ηι²

```
> 1 votes

# Answer
# Haskell, 112 bytes

```
import Data.List
f i=(\j->([(x,l`div`2)|(x,l)<-j,l>1],[x|(x,l)<-j,l`mod`2>0]))[(x,length s+1)|x:s<-group.sort$i]

```

Try it online!
> 1 votes

# Answer
# Japt `-Q`, 16 bytes

```
ü
lu mÎuUmÎíUËÊz

```

Try it

Better solution that pairs list of first elements with list of lengths/2 using **í** instead of **â**.

# Japt `-Q`, ~~14~~ 16 bytes

```
ü
lu mÎuUËâDÊz h

```

Try it

output \[sock , pairs num\] list followed by odd socks.

```
ü            // sort and group input and save it
lu mÎ        // first element of groups of odd length
     u       // perpended by..
      UË     // imput mapped
        â    // unique elements
         DÊz h // concatenated to half of the length to string

```

Thanks to @Shaggy for finding a bug. Unfortunately using **â(x?)** =\> **x** is concatenated *before* returning unique elements , so it failed with *\[2,2,2,2\]* case. Fixed by using **h** method which returns a string.
> 1 votes

# Answer
# Lua, ~~133~~ ~~123~~ 119 bytes (using global output var)

```
r,o,s={},{},{}for _=1,#t do d=t[_]r[d]=(r[d]or 0)+.5 end for a,b in pairs(r)do s[a],d=math.modf(b)o[#o+1]=d>0 and a end

```

Try it online!

# Lua, 135 bytes (using output return)

```
r,o,s={},{},{}for _=1,#t do d=t[_]r[d]=(r[d]or 0)+.5 end for a,b in pairs(r)do s[a],d=math.modf(b)o[#o+1]=d>0 and a or x end return o,s

```

Try it online!
> 1 votes

# Answer
# Lua, ~~144~~ 142 bytes

```
load'r,p,o,i={},{},{},...for a=1,#i do r[i[a]]=(r[i[a]]or 0)+1 end;for a,b in pairs(r)do p[a],o[#o+1]=b//2,(b%2>0)and a or nil end;return p,o'

```

Try it online!

Function that takes list as argument and returns hashtable representing pairs and list of ones without match using Lua "multireturn".

Note: if there is only one sock of some color (poor guy), it still will go in pairs list with zero pairs. If this is not up to spec, please tell me (it will cost a bunch of bytes but is easily doable).

I personally consider `return` to be required, but results are also stored in globals `p` and `o`, so it in fact can be omitted.
> 1 votes

# Answer
# Clojure, 102 bytes

```
(fn[d](def f(frequencies d))[(map(fn[[x y]][x(quot y 2)])f)(map first(filter #(=(mod(nth % 1)2)1)f))])

```

Try it online!

I really thought clojure would have a better chance. If only I had access to fmap. :-(
> 1 votes

# Answer
As suggested by JoKing this can be substantially shortend to:

# Ruby, 90 bytes

```
c=Hash.new(0)
ARGV.each{|s|c[s.to_i]+=1}
c.each{|k,v|p k if(p"#{k}=>#{v/2}"if v>1)&&v%2>0}

```

Try it online!

Old version:

# Ruby, 139 bytes

```
c=Hash.new(0)
ARGV[0].split(",").map(&:to_i).each{|s|c[s]+=1}
o = []
c.each{|k,v|o<<k if v.odd?}
c.each{|k,v|o<<"#{k}=>#{v/2}" if v!=1}
p o

```

Try it online!

Pardon me for writing non-idiomatic Ruby maybe.
> 1 votes

# Answer
# Burlesque, 27 bytes

```
raf:Jf{-]2.%})[-jm{g_2./_+}

```

Try it online!

```
ra   #Read input as array
f:   #Calculate frequency list
J    #Duplicate
f{   #Filter for
 -]  #Frequency
 2.% #Mod 2 != 0
}
)[-  #Get odd IDs
j    #Swap
m{   #For each block of the frequency list
 g_  #Pop count
 2./ #Divide by 2
 _+  #Concatenate back on
}

```
> 1 votes

# Answer
# Ruby, 58 bytes

Returns an array with the odds first, then the pairs.

```
->a,*b{[a.tally.filter_map{_2%2<1?(b<<[_1,_2/2];p):_1},b]}

```

Attempt This Online!
> 1 votes

---
Tags: code-golf
---