title: Infinite quote escaping sequence

text:
# Question
Title: Infinite quote escaping sequence
*Related*

We start with the string `a`, and forever append to the string a comma followed by the string quote-escaped, where quote-escaping means doubling all quotes in a string, and then surrounding it with an additional pair of quotes.

In the first few steps we will get:

* `a`
* `a,'a'`
* `a,'a','a,''a'''`
* `a,'a','a,''a''','a,''a'',''a,''''a'''''''`

If we continue to do that forever, we get the following infinite string: `a,'a','a,''a''','a,''a'',''a,''''a''''''','a,''a'',''a,''''a'''''',''a,''''a'''',''''a,''''''''a''''''''''''''','a,''a'',''a,''''a'''''',''a,''''a'''',''''a,'''...`

If create a sequence, which is 1 at indices that string contains a quotes, we'll get the following sequence:

1. `0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, ...`

Alternatively, we can look at the indices of quotes, and get the following sequence (this is 0-indexed):

2. `2, 4, 6, 9, 10, 12, 13, 14, 16, 19, 20, 22, 23, 25, 26, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 42, 45, 46, ...`

Your task is to output one of these numeric sequences.

## Rules

* You can choose whether you use 0-indexing or 1-indexing.
* If you output sequence 1, you can use any truthy/falsey values instead of 1/0, or any two different consistent values.
* If you output sequence 2 (the one with the indices), you can choose if those indices use 0-indexing or 1-indexing.
* You can use one of following output modes:
    + Take \\$n\\$ as an input, and output the \\$n\\$-th element in the sequence.
    + Take \\$n\\$ as an input, and output all elements in the sequence up to the \\$n\\$-th element.
    + Take no input, and output the entire sequence forever.
* You can use any reasonable input/output format.
* Standard loopholes are disallowed.

This is code golf, so the shortest code wins.

# Answer
> 7 votes
# Python, 57 bytes (@Steffan)

```
a=b="/"
while[print(end=b)]:b="/\%s\\"%repr(a)[1:-1];a+=b
```

Attempt This Online!

### Old Python, 58 bytes

```
a=b="/"
while[print(end=b)]:b="/\\%s\\"%repr(a)[1:-1];a+=b
```

Attempt This Online!

Prints the entire sequence using `/` for `0` and `\` for `1`.

# Answer
> 5 votes
# , 22 19 bytes

```
{1&(],1,~0 1,+#])&0

```

Try it online!

*-3 thanks to ovs!*

Quite slow, as we iterate n times and take the nth result.

TIO link shows first 17 terms.

Approach is straightforward recursion:

* `{` nth item (0-indexed) from...
* `1&( )&0` Iterate n times, starting with 0, and using a constant left arg of 1...
* `(],1,~0 1,+#])` Bookend `+#]` (to be explained below) with `0 1` and `1`
* `+#]` The only interesting part, really. This is how we double up the quotes. Consider `0 0 1 0 1`:
    + `+` adds 1 to every element, taking advantage of the fixed left arg of 1:

    ```
    1 1 2 1 2

    ```
    + `#]` use that as a duplication mask for `0 0 1 0 1`:

    ```
    0 0 1 1 0 1 1

    ```

# Answer
> 4 votes
# Vyxal, 16 bytes

```
0w?(:k≈$vß"1Wf)Ẏ

```

Try it Online!

Same idea as the Jelly answer.

# Answer
> 4 votes
# lin, 57 bytes

```
.\n0\;.n e*.n `t
dup \; `' `flat1`,0`,1`+ `+
dup \; e&
1,

```

Try it here! Returns an iterable with the first *n* elements.

The code above extremely inefficiently runs through *n* iterations. For testing purposes, the following code is equivalent:

```
100 ; `_
.\n0;.n `t
dup \; `' `flat1`,0`,1`+ `+ `size.n < \@ e&
dup \; e&
1,

```

## Explanation

Prettified code:

```
.\n 0 \; .n e* .n `t
dup ( dup ( 1, ) e& ) `' `flat 1`, 0`, 1`+ `+

```
* `.\n 0 \; .n e*` store the input as *n*, push 0, execute the next line *n* times...
    + `dup ( dup ( 1, ) e& ) `' `flat` top of stack with 1s replaced with `1 1`
    + `1`, 0`, 1`+ `+` prepend `0 1`, append `1`, append result to existing sequence

# Answer
> 4 votes
# Haskell, 43 bytes

```
f n=iterate(\x->x++'b':show x)"a"!!n!!n<'a'
```

Attempt This Online!

`f n` is the `n`th element of sequence #1, as either True or False.

The string built by `iterate` has the same "shape" as the real string:

```
ab"a"b"ab\"a\""b"ab\"a\"b\"ab\\\"a\\\"\""…
a,'a','a,''a''','a,''a'',''a,''''a'''''''…

```

`"\` both correspond to quotes, `ab` correspond to `a,`. So, we can use `char<'a'` to detect quotes.

# Answer
> 3 votes
# Jelly, 13 bytes

```
0;x‘Ø1jƲŻ$$¡ḣ

```

A monadic Link that accepts `n` and yields the first `n` terms of the boolean is-a-quote sequence.

**Try it online!** Or see a longer prefix (by not heading) here.

### How?

Starts with a zero (the initial `a`) and builds up the sequence exactly as described in the question, using zeros for non-quotes and ones for quotes.

```
0;x‘Ø1jƲŻ$$¡ḣ - Link: integer, n
0             - set the left argument, x, to zero
           ¡  - repeat n times:
          $   -   last two links as a monad - f(x):
         $    -     last two links as a monad - g(x):
       Ʋ      -       last four links as a monad - h(x):   e.g. [0,0,1,0,1]
   ‘          -         increment                               [1,1,2,1,2]
  x           -         repeat (double the quotes)              [0,0,1,1,0,1,1]
    Ø1        -         [1,1]
      j       -         join (wrap in quotes)                   [1,0,0,1,1,0,1,1,1]
        Ż     -       prepend a zero (prepend a comma)          [0,1,0,0,1,1,0,1,1,1]
 ;            -     concatenate that to x
            ḣ - head to index n

```

# Answer
> 2 votes
# Jelly, 14 bytes

```
;Ø.;x‘$;1
0Ç¡ḣ

```

Try it online!

Full program yielding first \\$n\\$ elements of the quote/non-quote sequence. Exponentially slow; better tested with manual control of the number of iterations.

```
;Ø.;x‘$;1    Monadic helper link: iterate
;Ø.          Append [0, 1].
   ;         Append
    x $      the argument with its elements repeated by
     ‘       themselves incremented.
       ;1    Append 1.

0Ç¡ḣ    Main link
 Ç¡     Repeat that n times
0       starting from 0,
   ḣ    and take the first n elements.

```

# Answer
> 2 votes
# Batch Script, 80 bytes

Outputs the first n elements of sequence 1,

```
CMD/VON/CSET s=0^&(FOR /L %%Q in (1,1,8)DO @SET s=!s!01!s:1=11!1)^&ECHO !s:~,%1!

```

so ie if file is called quote.bat

```
CALL quote.bat 5

```

gives you

```
00101

```

I hardcoded 8 iterations because that's the maximum amount before the string gets too big and CMD fails to parse it. So I'm not too sure if this answer counts, but I thought it would be neat to post it anyway.

Edit : minus a bunch of bytes thanks to Neil

# Answer
> 2 votes
# Python 3, ~~109~~, ~~71~~, ~~64~~, ~~63~~, 62 bytes

```
a=w='0'
while[print(end=w)]:w=f"01{a.replace('1','11')}1";a+=w

```

Try it online!

-45 thanks to @Steffan

-1 because of this answer

-1 thanks to @AnttiP

## Explanation (Outdated):

```
a=w="0"

```

Self-explanatory

```
while 1:

```

Repeat infinite times.

```
print(end=w+"0");

```

print w with 0. There's "0" because "0" is a comma.

```
w="1"+

```

w is "1" and...

```
a.replace("1","11")+

```

double the ones of a and...

```
"1";

```

one.

```
a="00"+w

```

Put two zeroes and w.

# Answer
> 2 votes
# Ruby, ~~52~~ 47 bytes

```
f=->n,r=?0{r[n]||f[n,r+"01#{r.gsub ?1,'11'}1"]}

```

Try it online!

Returns the nth element.

# Answer
> 1 votes
# Charcoal, 29 bytes

```
Ｎθ≔0ηＷ›θＬη≔⁺⁺η0⪫11⪫⪪η1¦11η…ηθ

```

Try it online! Link is to verbose version of code. Outputs the first `n` elements of sequence 1. Explanation:

```
Ｎθ

```

Input `n`.

```
≔0η

```

Start with a string of `0` instead of `a`.

```
Ｗ›θＬψ

```

Repeat until there are enough elements.

```
≔⁺⁺η0⪫11⪫⪪η1¦11η

```

Extend the string by appending its quotation, but use `0` instead of a comma and `1` instead of a quote.

```
…ηθ

```

Output the first `n` elements.

# Answer
> 1 votes
# JavaScript (ES6),  ~~50~~  49 bytes

*Saved 1 byte thanks to @tsh*

Returns the \\$n\\$-th term of the binary sequence, 0-indexed, where `0`'s are encoded with `2`'s.

```
f=(n,s='2')=>s[n]||f(n,s+21+s.replace(/1/g,11)+1)

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
ÎFDX3:5šbJÀ«I£

```

Outputs the first \\$n\\$ items of the binary sequence as string.

Try it online.

**Explanation:**

```
Î              # Push 0 and the input
 F             # Pop and loop the input amount of times:
  D            #  Duplicate the current string
   X3:         #  Replace all 1 with 3
      5š       #  Convert the string to a list of digits, and prepend a 5
        b      #  Convert each digit to a binary string
               #  (3 become 11; 5 becomes 101; 0 and 1 remain unchanged)
         J     #  Join it back together to a single string
          À    #  Rotate it once towards the right, so the leading 1 is trailing
           «   #  Append it to the previous string we've duplicated
            I£ #  Only leave the first input amount of characters
               # (after the loop, the result is output implicitly)

```

# Answer
> 0 votes
# Bash, 61 bytes

```
for((a=0;${#a}<=$1;));do a+=01${a//1/11}1;done;echo ${a:$1:1}

```

Try it online!

Returns the \\$0\\$-based \\$n^{\text{th}}\\$ element of the binary sequence.

# Answer
> 0 votes
# Haskell, 57 bytes

```
s>>=id
s=[0]:[0:1:[b|b<-a,c<-[0..b]]++[1]|a<-scanl1(++)s]
```

Attempt This Online!

# Answer
> 0 votes
# APL (Dyalog Extended), 27 bytes

```
{{∊⍵0 1(,⍨¨@(⍸⍵)⊢⍵)1}⍣⍵⊢,0}

```

Try it online!

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


title: Join Columnar Strings

text:
# Question
Title: Join Columnar Strings
Write the shortest possible program or function that will join a list of columnar strings.

For this challenge, columnar strings are defined as one-character-wide strings **spanning across multiple lines**. Each character, except for the last one, is **separated by a newline character**. Some examples, separated by `---`:

```
a
b
c
d
---
h
e
l
l
o
---
c
o
d
e

g
o
l
f
---
"
q
u
o
t
e
s
"

```

Given a list of columnar strings, join them into a single string with multiple columns. If the columnar string is longer than its surroundings, it should be left-padded by spaces.

### Notes

* This is , so shortest code wins!
* You may assume inputs are ASCII only.
* You may have trailing newlines.
* You may have trailing spaces.
* This is **not a transpose challenge**; each string in the input list of strings has newlines separating each character. The "multi-line strings vs list of strings as input" default does not apply here; each string in the test cases are separated by `---` and include newlines.

### Test Cases

```
Input:
---
a
b
c
d
---
h
e
l
l
o
---
c
o
d
e

g
o
l
f
---
"
q
u
o
t
e
s
"
---
Output: (note how `hello` and `code golf` are left-padded by spaces)
ahc"
beoq
cldu
dleo
 o t
  ge
  os
  l"
  f

Input:
---
h
w
---
e
o
---
l
r
---
l
l
---
o
d
---
Output:
hello
world

Input:
---
p

f
---
b
m
v
---
t

s
---
d
n
z
---
k

x
---
g
N
h
---
Output:
pbtdkg
 m n N
fvszxh

Input:
---
1
---

2
---

3
---

4
---
6

5
---
Output:
1   6
 2
  3
   4
    5

Input:
---
a

c
---
|
---
b
d
---
Output:
a|b
  d
c

Input:
---
Output:
(empty output, or single newline)

```

# Answer
> 10 votes
# Bash \+ GNU utilities, 39

Input is taken from files; 1 file per column; filenames passed as command-line parameters.

```
paste $@|expand|sed -r 's/(.) {7}/\1/g'

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Unicode), 8 bytes

Anonymous tacit prefix function, taking list of strings with CR as newline.

```
⍉∘↑⎕FMT¨

```

Try it online!

`¨` for each string:

`⎕FMT` ForMaT as character matrix, evaluating control characters for layout

mix into 3D array (layers: number of strings; rows: hight of longest string; columns: 1)

then:

reverse order of axes (layers: 1; rows: hight of longest string; columns: number of strings)

---

## Pre spec-change solution, 2 bytes

```
⍉↑

```

Try it online!

# Answer
> 5 votes
# Vyxal `j`, 9 bytes

```
↵¤ðvVðÞṪṅ

```

Try it Online!

# Answer
> 4 votes
# Japt `-R`, ~~1~~ 2 bytes

Note that the spec states that "... *columnar strings are defined as one-character-wide strings* ...", so any empty lines in the test cases should contain a space character.

```
Õë

```

Try it (header allows for input to be formatted as per the test cases) or run all test cases

```
Õë     :Implicit input of array of multi-line strings
Õ      :Transpose
 ë     :Remove every second element
       :Implicit output joined with newlines

```

# Answer
> 4 votes
# 05AB1E, 9 bytes

```
ε¶¡1ú€θ}ζ

```

Input as a list of multiline strings; output as a list of list of characters.

Try it online or verify all test cases. (The footer in the single-TIO is to join each inner list of characters; and then each string by newlines. Feel free to remove it to see the actual list output.)

**Explanation:**

```
ε       # Map over each multiline string of the (implicit) input-list:
 ¶¡     #  Split it on newlines
   1ú€θ #  Convert empty strings to spaces:
   1ú   #   Pad each inner character with a leading space
     €  #   Map over each inner 1 or 2-char string
      θ #    Only keep its last character
}ζ      # After the map: zip/transpose; swapping rows/columns, using " " as filler
        # character if the lists are of unequal lengths
        # (after which the resulting matrix of characters is output implicitly)

```

# Answer
> 3 votes
# Python 3, ~~123 121 137~~ 128 bytes

```
def f(l):l=[''.join(c or' 'for c in q.split('\n'))for q in l];[print(*x,sep='')for x in zip(*[s+max(map(len,l))*' 'for s in l])]

```

Try it online!

+16 bytes because it was failing for concurrent newlines (@hakr14)

Saved 9 bytes by using a trick from 97.100.97.108's answer where it outputs a lot of newlines at the end.

# Answer
> 3 votes
# Octave, ~~13~~ 61 bytes

*+48 bytes in order to properly account for newlines in columnar strings (@hakr14)*

```
@(b)reshape(strrep(b(:,1:2:end)',char(10),' '),[],size(b)(1))

```

Takes in columnar strings (with newline between characters), used as follows:

```
f = ans
a = ['a' newline 'b' newline 'c' newline 'd';
'h' newline 'e' newline 'l' newline 'l' newline 'o';
'c' newline 'o' newline 'd' newline 'e' newline newline newline 'g' newline 'o' newline 'l' newline 'f';
'"' newline 'q' newline 'u' newline 'o' newline 't' newline 'e' newline 's' newline '"']
f(a)

```

# Answer
> 3 votes
# Charcoal, 6 bytes

```
ＦＡ«Ｐι→

```

Try it online! Link is to verbose version of code. Takes input in JSON-like format (but with Python string delimiters). Explanation:

```
ＦＡ«

```

Loop over all of the input strings.

```
Ｐι

```

Print the string to the canvas without moving the cursor.

Move the cursor one character to the right.

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~77~~ 95 bytes

*+18 bytes in order to properly account for newlines inside of the columnar string (@hakr14)*

```
lambda l:"\n".join(map("".join,zip(*[s[::2].replace("\n"," ")+" "*max(map(len,l))for s in l])))

```

Try it online!

Takes in lists of columnar strings (characters separated by newlines). Exploits the rule that you can have extra whitespace at the end.

# Answer
> 2 votes
# sclin, 51 bytes

```
"""."fold
over0:"."" "\ /#" ""."zip~
"^$"" "\ /# ++

```

Try it here! Takes input as a list of lists of single-character strings, and outputs as a list of row-based strings.

For testing purposes (`c<>` splits each string into a list of single-character strings):

```
["abcd" "hello" "code golf" "\"quotes\""] c<> ; n>< n>o
"""."fold
over0:"."" "\ /#" ""."zip~
"^$"" "\ /# ++

```

## Explanation

Prettified code:

```
"""."fold
over0:"."" "\ /#" ""."zip~
"^$"" "\ /# ++

```
* `"" \; fold` starting with the empty string, fold over each column...
    + `over 0: "." " "\ /#` get string of spaces with length of row built thus far as *x*
    + `" " ; zip~` zip with the following (placeholding *x* for empty accumulator elements and a single space for empty subsequent elements)...
        - `"^$"" "\ /#` replace empty string with space
        - `++` concatenate

# Answer
> 2 votes
# Pyth, 25 bytes

```
j%2.t:R"(?<=\n)\n|^\n"+;b

```

Try it online!

Could save 2 bytes if `re` supported alternations in lookbehinds.

##### Explanation:

```
j%2.t:R"(?<=\n)\n|^\n"+;b  | Full program
j%2.t:R"(?<=\n)\n|^\n"+;bQ | with implicit varibles
---------------------------+-------------------------------------------------------------------------
      R                  Q | For each string in the input,
     :                     |  Replace
       "(?<=\n)\n|^\n"     |   Each newline preceded by another newline or by the start of the string
                      +;b  |   with " \n"
   .t                      | Ragged transpose
 %2                        | Every other item (removes the newlines)
j                          | Join by newlines

```

# Answer
> 2 votes
# Excel 65 bytes

```
=LET(v,TEXTSPLIT(CONCAT(A:A),"-"),MID(v,SEQUENCE(MAX(LEN(v))),1))

```

# Answer
> 1 votes
# Excel (ms365), 120 bytes

Formula in `A1`:

```
=TEXTJOIN(CHAR(10),,MAP(SEQUENCE(ROUND(MAX(LEN(A2:A5))/2,),,,2),LAMBDA(a,LET(b,MID(A2:A5,a,1),CONCAT(IF(b=""," ",b))))))

```

I do know that since you allow for trailing spaces I could remove `ROUND()` and `/2` but it felt like cheating.

# Answer
> 1 votes
# C (clang), ~~139~~ 124 bytes

* -15 bytes thanks to ceilingcat and jdt

Takes wide character strings as input.

```
f(*s,**t,m,i){for(t=s,m=0;i=*t;)m=fmax(wcslen(*t++),m);for(;i<m;i-=~puts(""))for(t=s;*t;t++)putchar(i<wcslen(*t)?i[*t]:32);}

```

Try it online!

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

```
x=>[...x+x].map((_,i)=>x.map(v=>v[i+i]||' '))

```

Try it online!

# JavaScript (Node.js), 43 bytes

```
x=>[...x+x].map((_,i)=>x.map(v=>v[i]||' '))

```

Try it online!

43 take input as array, which looks unallowed so I added the 45

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


title: Simulate any 1D cellular automaton

text:
# Question
Title: Simulate any 1D cellular automaton
## The Challenge

You are to write a complete program that takes seven numbers from STDIN, and prints the two dimensional history of the cellular automaton (CA) to STDOUT. This is code golf.

**Input Formatting** The input will be seven integers/strings separated by commas. The first number is the number of the rule according to Wolfram code (the standard name for each rule). The second is the initial starting configuration. The third and fourth describe what pattern and how many times it should be appended to the left of the starting config. as padding. The fifth and sixth do the same for the right side. The last number is the number of generations to run the simulation.

So, an example of input is `90,11,0,4,0,4,5`. This should tell your program that you are running rule 90. It should also tell the program that you want the initial configuration to be `11` with the string `0` appended 4 times to both ends, so the actual starting pattern is `0000110000`. It also tells your program to run this simulation for 5 generations.

**Output** Your program should print the entire array of cells each generation (separated by newlines), so that the output is the space-time diagram of the CA. For each generation, the state of each cell is determined by its state and the states of the cells to the immediate left and right, in accordance to the rule provided as input. The simulation should wrap around the edges. The first thing printed should be the starting array as gen. 0.

The input `90,11,0,4,0,4,5` should result in the following output as exactly as possible.

```
0000110000
0001111000
0011001100
0111111110
1100000011
0110000110

```

Notice that the starting state is not included in the five generations. Also notice that the simulation wraps around the edges.

**More Examples**

input:

```
184,1100,01,2,01,1,4

```

output:

```
0101110001
1011101000
0111010100
0110101010
0101010101

```

input:

```
0,1011,1,0,0,1,2

```

output:

```
10110
00000
00000

```

**More information on how 1D CA's work and how they are numbered**

# Answer
## Golfscript, 77 73 70 chars

```
','/)~\(~:?;~~*@@~*@+\+{1&}/]({[.,{.[3<?256+]{2base}/\~=\(+}*])n@)\+}*

```

Thanks to @Howard, who pointed out how to save 4 chars.
> 5 votes

# Answer
## APL (153 characters)

```
∇ cellularautomaton
  i               ← ⍞
  s               ← (i=',') / ⍳ ⍴i
  (b a x c)       ← {i[s[⍵]↓⍳s[⍵+1]-1]} ¨ ⍳4
  (z x x l x r n) ← ⍎i
  y               ← ⍎ ¨ ⊃ ,/ (l / ⊂a) , b , r / ⊂c
  (n+1) (⊃⍴,y) ⍴ '01'[1+⊃ ,/ y,{({(z ⊤⍨ 8/2)[8 - 2⊥¨ 3 ,/ (⊃⌽⍵),⍵,⊃⍵]}⍣⍵)y} ¨ ⍳n]
∇

```

And in less readable, slightly shorter form:

```
i←⍞⋄s←(i=',')/⍳⍴i⋄b a x c←{i[s[⍵]↓⍳s[⍵+1]-1]}¨⍳4⋄z x x l x r n←⍎i⋄y←⍎¨⊃,/(l/⊂a),b,r/⊂c⋄'01'[1+⊃,/y,{({(z⊤⍨8/2)[8-2⊥¨3,/(⊃⌽⍵),⍵,⊃⍵]}⍣⍵)y}¨⍳n]⍴⍨(1+n),⊃⍴,y

```

Example:

```
      cellularautomaton
26,00110,01,4,10,6,7
0101010100110101010101010
1000000011100000000000001
0100000110010000000000011
0010001101101000000000110
0101011001000100000001101
0000010110101010000011000
0000100100000001000110100
0001011010000010101100010

```

I'm certain there is room for improvement (I even found a few changes while writing this post!), but some of it could involve fundamental changes, and I can't stand staring at APL any longer. The variant of APL used here is Dyalog APL.
> 5 votes

# Answer
## Ruby, 165 159 characters

```
a=gets.split ?,
b=a.map &:to_i
c=(x=a[2]*b[3]+a[1]+a[4]*b[5]).chars.map &:hex
(0..b[6]).map{puts c*''
c=(1..w=x.size).map{|i|b[0]>>c[i-1]*2+c[i%w]+c[i-2]*4&1}}

```

*Edit:* I found some places for small enhancements.

Example run:

```
> 30,1,0,20,0,20,20
00000000000000000000100000000000000000000
00000000000000000001110000000000000000000
00000000000000000011001000000000000000000
00000000000000000110111100000000000000000
00000000000000001100100010000000000000000
00000000000000011011110111000000000000000
00000000000000110010000100100000000000000
00000000000001101111001111110000000000000
00000000000011001000111000001000000000000
00000000000110111101100100011100000000000
00000000001100100001011110110010000000000
00000000011011110011010000101111000000000
00000000110010001110011001101000100000000
00000001101111011001110111001101110000000
00000011001000010111000100111001001000000
00000110111100110100101111100111111100000
00001100100011100111101000011100000010000
00011011110110011100001100110010000111000
00110010000101110010011011101111001100100
01101111001101001111110010001000111011110
11001000111001111000001111011101100010001

```
> 4 votes

# Answer
## C, ~~303 305 301 294~~ 292

305 Edit: oops. Forgot that `calloc()` takes two args. It was blowing up on larger input.

301 Edit: Ah HA! Used my `calloc()` boo-boo to save 2 more bytes by upping the block size of the requested memory.

294 Edit: Broke 300! Eliminated one of the `strcat()`s and tweaked a few loops. Got to use maximal munch, which is as much fun to say as use.

292 Edit: Didn't need the `+2` in memory allocation.

I used luser droog's answer as the base idea, but changed up the wrapping algorithm, as well as a lot of tweaking and factoring out of constants.

```
r,A,C,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);for(s=calloc(A+++C,9);A--;)strcat(s,A?a:b);for(;C--;)strcat(s,c);p=strdup(s);for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)for(j=C;j--;)p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;}

r,A,C,n,j;
main(){
    char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    for(s=calloc(A+++C,9);A--;)
        strcat(s,A?a:b);
    for(;C--;)
        strcat(s,c);
    p=strdup(s);
    for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)
        for(j=C;j--;)
            p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;
}

```
> 4 votes

# Answer
# C (~~487~~ ~~484~~ 418 with spaces removed)

\*Dropped *66* with help from JoeFish\*

```
C,A,r,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    s=malloc(strlen(a)*A+strlen(b)+strlen(c)*C+3);*s=0;
    strcat(s,"0");
    for(;A--;)strcat(s,a);
    strcat(s,b);
    for(;C--;)strcat(s,c);
    strcat(s,"0");
    p=malloc((C=strlen(s)-1)+2);
    for(;n--;){
    *s=s[C-1];
    s[C]=0;
    puts(s+1);
    s[C]=s[1];
    for(j=1;s[j+1];j++)
        p[j]=(1<<(s[j-1]-48)*4+(s[j]-48)*2+s[j+1]-48)&r?49:48;
    t=p;p=s;s=t;
    }
    s[C]=0;
    puts(s+1);
}

```

typescript

```
josh@Z1 ~
$ !m
make ca
cc     ca.c   -o ca
ca.c:1:1: warning: data definition has no type or storage class
ca.c: In function ‘main’:
ca.c:2:5: warning: incompatible implicit declaration of built-in function ‘scanf’
ca.c:3:7: warning: incompatible implicit declaration of built-in function ‘malloc’
ca.c:3:14: warning: incompatible implicit declaration of built-in function ‘strlen’
ca.c:4:5: warning: incompatible implicit declaration of built-in function ‘strcat’

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ca
-bash: ca: command not found

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ./ca
0000110000
0001111000
0011001100
0111111110
1100000011
0110000110

```
> 3 votes

# Answer
# Vyxal ~~67~~ 59

```
□÷bṅṅṘ‟:L∇∇~≤[$_⋏ð\0øV|$_Ẏ]$($₀Sf$~Ŀ,$_‟:₌ht∇++3lvB~İṅ$_^„)

```

There is extra feature: replacement "10" symbols to any Unicode characters.

Many thanks to @lyxal

Try it online!
Input:

* List of replacement symbols
* Width
* Height (number of iterations)
* Initial string
* Wolfram CA-code

Explanations
> 2 votes

---
Tags: code-golf, math, interpreter, cellular-automata
---


title: Tips for golfing in <all languages>

text:
# Question
Title: Tips for golfing in <all languages>
The aim of this post is to gather all the golfing tips that can be easily applied to `<all languages>` rather than a specific one.

**Only post answers that its logic can be applied to the *majority* of the languages**

> Please, one tip per answer

# Answer
> 78 votes
## Merge Loops

You can usually merge two consequent loops, or two nested loops, into one.

Before:

```
for (i=0; i<a; i++) foo();
for (i=0; i<b; i++) bar();

```

After:

```
for (i=0; i<a+b; i++) i<a?foo():bar();

```

# Answer
> 77 votes
Just to mention the obvious:

### Question your choice of algorithm and try something entirely new.

When golfing (especially harder problems that result in longer programs) all too often you might stick to the path you first chosen without trying other *fundamental* options. Of course, you may micro-golf one or a few lines at a time or a part of the overall idea, but often not try a totally different solution.

This was especially noticeable in Hitting 495 (Kaprekar) where deviating from the actual algorithm and looking for patterns you can apply to get to the same result was shorter in many languages (just not J).

The downside is that you possibly solve the same thing half a dozen times. But it works in really all languages except HQ9+ (where finding another way to output *Hello World* would be slightly futile).

# Answer
> 61 votes
# Use Test-Driven Development

If the code must handle various inputs, then write comprehensive tests and make it easy to run them all very quickly. This allows you to try risky transforms one baby step at a time. Golfing then becomes like refactoring with perverse intent.

# Answer
> 61 votes
# Try to reduce logical statements

For example, if `A` and `B` are booleans and your language treats booleans like numbers to some extent, `A and (not B)` and `A>B` are equivalent. For example in Python

```
if A and not B:
    foo()

```

is the same as:

```
if A>B:
    foo()

```

# Answer
> 53 votes
# Write an explanation of your code

Writing an explanation forces you to thoroughly look at each part of your code again and to make your thoughts and choices in writing a certain passage explicit. In doing so, you might find that different approaches are possible which may save some bytes, or that you subconsciously made assumptions which don't necessarily hold.

This tip is similar to Question your choice of algorithm and try something entirely new; however, I have found that the step of actually writing down how each part is supposed to work is sometimes crucial for becoming aware of alternatives.

As a bonus, answers including an explanation are more interesting for other users and are hence more likely to be upvoted.

# Answer
> 44 votes
## Initialize variables using values you already have.

Instead of `x=1`, try to look for something that already equals 1.
For example, a function's return value: `printf("..");x=0;` -\> `x=!printf("..");`. It's easiest with 0, because you can always negate, or when all you need is the right truth value (and don't care if it's 1 or 19).

# Answer
> 41 votes
# Use unary `~` for `x+1` and `x-1`

This trick applies to languages that have a unary bitwise negation operator `~` and a unary regular negation operator `-`.

If your program, by chance, contains the expression `-x-1`, you can replace it with `~x` to save bytes. This doesn't occur all too often, but watch what happens if we negate (`-`) both expressions: `x+1` equals `-~x`! Similarly, `x-1` equals `~-x`. (Think of which way the tilde points: right is `+`, left is `-`.)

This is useful, because in all languages I can think of that have these operators, they have higher precedence than most operators. This allows you to save on parentheses. Watch how we save four bytes here:

```
(x+1)*(y-1)     ==>    -~x*~-y

```

# Answer
> 36 votes
## Squeeze whitespace

Know the rules for whitespace in your language. Some punctuation marks, or other characters, might not need any surrounding whitespace. Consider this *Bourne shell* function:

```
f () { echo a; echo b; }

```

In Bourne shell, `();` are metacharacters, and do not need surrounding whitespace. However, `{}` are words and need whitespace unless they are next to metacharacters. We can golf away 4 spaces next to `();`, but must keep the space between `{` and `echo`.

```
f(){ echo a;echo b;}

```

In *Common Lisp* and *PicoLisp*, `()` are metacharacters. Consider this code to find the average of two numbers:

```
(/ (+ a b) 2)

```

We can golf away 2 spaces.

```
(/(+ a b)2)

```

---

Some languages have strange and subtle rules for whitespace. Consider this Ruby program, which prints the sum and product of a line of integers.

```
#!ruby -an
i=$F.map &:to_i
puts"#{i.reduce &:+} #{i.reduce &:*}"

```

Each `&` needs a space before itself. In Ruby, `i=$F.map &:to_i` means `i=$F.map(&:to_i)` where `&` passes a block parameter. But, `i=$F.map&:to_i` means `i=$F.map.&(:to_i)` where `&` is a binary operator.

This weirdness happens in languages, like Perl or Ruby, that use ambiguous punctuation. If in doubt, use a REPL or write short programs to test the whitespace rules.

# Answer
> 33 votes
## assign functions new names if used multiple times

```
x = SomeLongFunctionName
x(somedata)
x(somemoredata)
etc

```

# Answer
> 31 votes
## Single Letter Variable Names

You have 52 of them; use them all! Don't be afraid to try different approaches and compare lengths. Know the language and the specific shortcuts/library functions available.

# Answer
> 27 votes
## **Use the conditional operator.**

A conditional *operator*

```
bool ? condition_true : condition_false

```

is more beneficial, character wise, than an IF *statement*.

```
if(a>b){r=a;}else{r=b;}

```

can be written as

```
r=a>b?a:b;

```

# Answer
> 25 votes
# Read the question carefully

Code golfing is as much about understanding the question (what is asked and what is **not** asked, even though it would be implied in any other setting) as producing code that (may) only satisfy what is asked.

Any input other than what is explicitly asked for need not be handled. If there are some test cases and no generic requirement, your code may only work in those cases. Etc.

e.g. if the question says "print the prime numbers from 1 to 100 inclusive", the largest prime printed will be 97 and you can change your loop end condition from `100` to `97` and save 1 byte. The question does not say you need to test 98, 99, 100 for primality, so don't do that.

e.g. 2. if the question says "print these numbers" then it does not say your answer must *calculate* the numbers. It might be shorter to store the expected output and decode and print it, than to write a calculator for it, e.g. storing 97 98 99 100 as a string of ASCII characters `'abcd'`.

# Answer
> 25 votes
## use `-` instead of `!=`

for numeric comparisons:

If a equals b, `a-b` results in `0`, which is falsy. Anything else than `0` is truthy; so
if used in a boolean context, `a-b` \<=\> `a!=b`

If you use it with `if/else` or with the ternary operator, this can also save you one byte for equality:
`a==b?c:d` \<=\> `a-b?d:c`

# Answer
> 24 votes
## Double check your character count

Sounds like a no-brainer, but by being careful you might be able to "save" a few characters by not actually doing anything!

If you're using Windows, you may be inputting `\r\n` instead of just `\r` or `\n` when you hit Return - adding an extra byte per line! Turn control characters just to double check you're not doing this.

In Notepad++ you can convert all `\r\n` line endings to just `\r` by going to `Edit > EOL Conversion > UNIX/OSX Format`.

Also make sure you don't include any trailing whitespace in your character count! The line feed on the bottom line in your code is also inconsequential, so that won't need to be counted either.

# Answer
> 22 votes
## Use \> and \< instead of \>= and \<=

When checking against hard-coded integer values, use `>` and `<` instead of `>=` and `<=` where possible. For example, using

```
if(x>24&&x<51)

```

Is 2 bytes shorter than using

```
if(x>=25&&x<=50)

```

# Answer
> 20 votes
## Use bitwise operations for checking numbers between 0 and any 2n-1

Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which m=2n-1 applies have the rightmost n bits set to 1.

So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.

The trick is `x&~m`. This will return true whenever `x` is ***not*** between 0 and `m` (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: `x>=0&&x<=m`, but obviously only works when `m` satisfies 2n-1.

# Answer
> 19 votes
**Greater/Less than to save a digit:**

```
//use:
if(n>9){A}else{B}
//instead of:
if(n<10){B}else{A}

```

Just remember to swap the code from `if` to the `else` and they will do exactly the same thing (or switch the sides of the inequality)!

**Note:** this can be applied with any power of 10 and their negatives: `...-100, -10, 10, 100...`

(source link)

# Answer
> 19 votes
# Understand what other people did

In addition to being fun, if you examine other people's code, you can sometimes discover a good algorithm that you didn't think about, or a trick (sometimes an obvious one) that you overlook.

Sometimes there is an existing answer that you can translate to another language, and benefit from the other language's goodies.

# Answer
> 18 votes
Reuse function parameters instead of new variables

# Answer
> 16 votes
## Avoid premature loop breaks

If running through a loop to check for 1 or more instances of a boolean check, it might make for a more efficient program to exit the loop on the first true value. However, removing the break and looping through all iterations allows for shorter code.

```
int main() {
bool m = false;
int n = 1000;
for (int i = 0; i < n; i++) {
if (i >= 100) {
m = true;
break; // remove this line
}
}
return 0;
}

```

# Answer
> 15 votes
## know your operator precedence

Whenever You combine several expressions, check the operator precedence table for your language to see if you can reorder stuff to save parentheses.

Examples:

* In all languages that I know, bitwise operators have a higher precedence than boolean operators: `(a&b)&&c` needs no parentheses: `a&b&&c` just as `(a*b)+c` does not.
* `a+(b<<c)` can be rewritten as `a+b*2**c`.
That doesn´t save anything for this example, but it will if `c` is a small integer literal (\<14).
* Bitwise operations have a lower precedence than most arithmetic operations, so if your language implicitly casts boolean to int, you can save a byte on `a<b&&c<d` with `a<b&c<d` (unless you need the short circuit evaluation)

# Answer
> 15 votes
# Use unary `~` for `a-b-1` and `a+b+1`

In addition to *@Lynn*'s suggestions regarding `x+1``-~x`; and `x-1``~-x`, you can also golf `a-b-1` and `a+b+1`.

```
a-b-1    // 5 bytes
a+~b     // 4 bytes

a+b+1    // 5 bytes
a-~b     // 4 bytes

```

It might look like a tip you won't use all that often, kinda like using `~x` instead of `-x-1` doesn't happen often, but I've used it enough times to see it as a useful tip here. Especially with array-indexing you might use these above in some cases.

# Answer
> 13 votes
### Split strings for long arrays

Most languages have a way to split a string into an array of strings around a token of some kind. This will inevitably be shorter than an array literal once the length reaches a language-dependent threshold, because the extra overhead per string will be one copy of a one-char token rather than (at least) two string delimiters.

E.g. in GolfScript

```
["Foo""Bar""Baz""Quux"]  # 23 chars

```

becomes

```
"Foo
Bar
Baz
Quux"n/  # 20 chars

```

For some languages, the threshold is as low as one string. E.g. in Java,

```
new String[]{"Foo"}  // 19 chars

```

becomes

```
"Foo".split("~")  // 16 chars

```

# Answer
> 9 votes
# Shorter for-loops

If you have `X` statements `{`inside`}` your for-loop, you can move `X-1` statements `(`inside`)` the for-loop after the second semicolon `for(blah;blah;HERE)` to save 3 bytes. (separate the statements by using a comma `,`)

Instead of

```
for(int i=0;i<9;){s+=s.length();println(i++);}

```

you can move one of the statements into the for-loop's `(` braces`)` while leaving the other out

```
for(int i=0;i<9;println(i++))s+=s.length();

```

and save 3 bytes (saved 1 more byte thanks to @ETHProductions)

---

Put simply,

instead of

```
for(blah;blah;){blah 1;blah 2;...;blah X}

```

move the statements around so you end up with this

```
for(blah;blah;blah 2,...,blah X)blah 1;

```

and save 3 bytes

# Answer
> 8 votes
## O(n^2) is your friend

You spend your time looking to get rid of O(n^2) algorithms and bring runtime and memory use down; golf turns that around - spend freely of CPU and Memory to bring code size down. Use nested loops, calculate 10x too much data instead of a complex exit condition, call `sort()` every loop iteration instead of storing the result.

Some questions have a runtime limit to push you to write a more efficient answer, even then knowing how fast your language and code runs can give you room to take liberties and still stay within it.

# Answer
> 7 votes
## Rely on the compiler to provide the required performance.

Be sure to know which optimisations are guaranteed by the compiler and at which optimisation levels, and use them liberally. And even if performance isn't a ~~concern~~ requirement, you can still test with optimisations on, and then only discount one character because your code is still *technically* valid without the compiler flag.

Consider the following Haskell function to compute 2^n (ignoring the fact that Haskell already has a built-in exponentiation operator or three) (23 characters):

```
p 0=1;p x=p(x-1)+p(x-1)

```

The problem is - it's horrendously slow, it runs in exponential time. This might make your code untestable or to fail any performance constraints given by the question. You might be tempted to use a temporary variable or an immediately invoked function literal to avoid repeated function calls (25 characters):

```
p 0=1;p x=(\y->y+y)$p$x-1

```

But the compiler can already do that for you, you just need set `-O` as a compiler flag! Instead of spending few extra characters per site to eliminate common subexpressions manually, just tell the compiler to do basic optimisations for you.

# Answer
> 7 votes
Maybe somewhat obvious but...

# Make use of operator return values

Keep in mind that the assignment operator returns a value!

For example, if you want to add y to x and then check if x is greater than something, you can do

```
if(25<x+=y)

```

instead of

```
x+=y;if(x>25)

```

Or maybe you want to find the length of a string after trimming it:

```
strlen(s=trim(s))

```

Rather than

```
s=trim(s);strlen(s)

```

# Answer
> 6 votes
## Compress or/and streaks

Simple trick I've come up with when trying to squeeze a long streak of conditions chained by ands (or ors, in this case just substitute 'all' with 'any').

**Eg:**

```
if a>0 and a<10 and a+b==4 and a+3<1:

```

Becomes

```
if all([a>0,a<10,a+b==4,a+3<1]):

```

# Answer
> 6 votes
## Utilize language version / compiler / environment quirks / new features

This is especially useful for s, but can be applied to other challenges. Sometimes, a compiler bug can golf off a byte, a implementation bug can allow you to save a few chars, or a really bleeding-edge feature can improve your score.

# Answer
> 6 votes
# Use truth tables

An example condition can be `(((A AND B) OR (A OR B)) AND C) OR (A OR C)` with `A`, `B` and `C` being boolean variables. But it's so long! Is there any way to shorten it, *and* prove it acts the same after shortening? Well, truth tables to the rescue!

| A | B | C | D=A AND B | E=A OR B | F=D OR E | G=F AND C | H=A OR C | I=G OR H |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 |
| 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 |
| 1 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 1 |
| 1 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 |
| 1 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |

The truth table above represents the possible values and outcomes of the example condition we specified earlier. `D`, `E`, `F`, `G` and `H` are variables which make our life a lot easier. You can see what they're assigned to at the top row of the table. The final variable, `I`, is the outcome of the condition. So, now that we have the outcomes handy, we can simplify the table to just the base variables and the final outcome:

| A | B | C | I |
| --- | --- | --- | --- |
| 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 1 |
| 0 | 1 | 0 | 0 |
| 0 | 1 | 1 | 1 |
| 1 | 0 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 1 | 1 | 0 | 1 |
| 1 | 1 | 1 | 1 |

We can now relatively easily see that the condition above really reduces to just `A OR C`.

# Answer
> 6 votes
## Know the difference between "program" and "function" in your language

Many questions on codegolf.SE ask you to "write a program or function"; this gives you some freedom to play to the strengths of your language and runtime based on how it handles command line parameters, how much boilerplate it needs for defining functions and their parameters, for defining full programs, for reading user input in a running program.

e.g. for a question asking you to write a program or function which takes a number as input, multiplies it by 10 and prints the result:

in Python it might go this way:

```
print(10*int(input()))    # full program
lambda x:print(10*x)      # function

```

in APL, the other way:

```
⎕←10×⎕      # full program
{⎕←10×⍵}    # function

```

In languages with a lot of code to get a whole program to run such as Java, a function could be much shorter. In more dynamic scripting languages such as Perl with many command line options to change how the code acts, a full program with a command line switch could be the shortest. Taking input from an implicit `$args` might be shorter than `input()`, or defining a function with a parameter might be shorter than `System.Console.ReadLine();`

# Answer
> 5 votes
# Use bitwise operators in your `if` statements

In an `if` statement, you can (usually) use the bitwise operator "and" (usually `&` , if it is present) rather than `&&` or `and` and save 1-2 bytes. Sames goes with other keywords (`not` is the same as a bitwise `!` or `~` in many languages (saves 2 bytes), `or` is bitwise `|` in many languages (saves 1 byte), etc.).

# Answer
> 5 votes
# Optimize Imports

Use glob imports over specific symbols, especially if you need multiple symbols from the path.

In rust:

```
use library::some_function; //bad: 25 bytes
use library::*; //good: 13 bytes

```

Renaming long symbol names may also be able to save you bytes if you use the symbol multiple times.

In rust:

```
//bad: 100 bytes
use library::*;
fn main(){
    some_very_long_function_name();
    some_very_long_function_name();
}
//good: 76 bytes
use library::some_very_long_function_name as f;
fn main(){
    f();
    f();
}

```

If you only use a symbol once, using its fully qualified pathname will save bytes.

In rust:

```
//bad: 48 bytes
use library::*;
fn main(){
    some_function()
}
//good: 41 bytes
fn main(){
    library::some_function()
}

```

Which techniques to use varies widely based on the language, what symbols you use, and how you use them. If your use case is complicated trying multiple styles will help you find the shortest. Also, make sure you know your language- they all have their own quirks. For example, Java supports glob imports and fully qualified paths but not symbol renaming.

# Answer
> 4 votes
Combine multiple/nested if checks using And/Or when possible.

i.e.:

```
if (a && (b || c)) {

}

```

instead of:

```
if (a) {
    if (b) {
        //Do Stuff
    } elseif (c) {
        //Do same stuff
    }
}

```

# Answer
> 4 votes
## eval() is perfectly safe

In more dynamic languages it can help to make a string of code and then `eval()` it (or the equivalent in your language), as a way to repeat chunks of code by inserting the code into the right places as a string replace without the overhead of defining and calling functions, or to loop N times without loop boilerplate.

e.g. in Python to print "hello" five times:

```
for i in range(5):print("hello")

exec('print("hello");'*5)

```

e.g. in PowerShell calling `[math]::Truncate()` three times becomes slightly shorter as a function, and slightly shorter again doing a string replace on code and then evaluating it:

```
$a=[math]::Truncate($a/$b);$b=[math]::Truncate($c/$a);$c=[math]::Truncate($d/$e)

function T($a,$b){[math]::Truncate($a/$b)};$a=T $a $b;$b=T $c $a;$c=T $d $e

'$a=T($a/$b);$b=T($c/$a);$c=T($d/$e)'|% r*ce T [math]::Truncate|iex

```

# Answer
> 4 votes
# Don't be afraid to put non-printables in your code.

Sometimes, instead of using escapes like `\0`, `\x1f`, `\033`, `\n`, or `\u0003`, you can just put the codepoint in the string verbatim. You may need to input code points manually using keyboard shortcuts, a hex editor, or a good old `printf "\x1f" >> file`

Note that you cannot copy and paste null bytes on Windows.

Since Stack Exchange doesn't play well with non-printables (and they are difficult to read), I like to represent them by `<kbd>` tags: (make sure to use `language-all` and escape `<` and `>` in the code block)

```
<!-- language-all: lang-c -->
<pre><code>char str[]="abc<kbd>00</kbd>def";</code></pre>

```

```
char str[]="abc`00`def";
```

This is very useful for making lookup tables in languages where strings can be indexed like arrays for their codepoint, such as C, C++, asm, C#, and Python (with `b''`), since the non-printables consist of the first 32 bytes.

```
int l[]={2,9,31,7};l[x]; // 23 bytes
"`02``09``1f``07`"[x]; // 10 bytes

```

This also can apply to invalid UTF-8 sequences, but that is very fragile in practice and far less useful.

# Answer
> 3 votes
# Find better ways to initialise your variables

Some other answers came close to mentioning this already, but in many (strictly typed?) languages, it's shorter to initialise `x` as empty string like:

```
x:=""

```

or `x` as empty rune (char) like:

```
x:=''

```

than

```
var x string

```

and

```
var x rune

```

Using preexisting values is obviously preferred, but not so easy.

# Answer
> 3 votes
## Use LF instead of CRLF

If you use CRLF line endings, each newline will count as two characters. Changing this to LF will save one character per newline in your code.

# Answer
> 2 votes
### Don't declare variables in for-loops

If for-loops have one statement inside of them, you can move the iterating variable's initialisation with the other variables that you already have declared.

```
int a=1;for(int i=1;i<n;)a*=++i;  // 32 bytes
int a=1,i=1;for(;i<n;)a*=++i;     // 29 bytes

```

Also, if you have multiple un-nested for-loops, it would be better if you reuse the same variable. This sort of ties in with this answer.

```
int a=1;for(int i=1;i<n;)a*=++i;for(int j=2;j<n;)a-=j++; // 56 bytes
int a=1,i=1;for(;i<n;)a*=++i;for(i=2;i<n;)a-=i++;        // 49 bytes

```

(I know you can do `a=i=1`, but that is not the point)

---

Now if you don't have any statement before the for-loop (and you only have 1 for-loop), it would be best to initialise the variable inside the for-loop

```
for(int i=0;i<99;)i*=2;       // 23 bytes
int i=0;for(;i<99;)i*=2;      // 24 bytes

```

# Answer
> 2 votes
Using float -\> integer conversion automatic truncates for flooring (positive values) in most languages that don't strongly enforce types:

```
f.floor     # Ruby
f.to_i      # -1 byte
int $f      # Perl
0|$f        # -2 bytes
parseInt(f) # Javascript (Never use Math.floor)
0|f

```

This will truncate downwards (for positive values), and to get the ceil instead, it can be achieved with the same trick by reflecting the value across 0 (not true in all languages / implementations, not always shorter):

```
(i/5.0).ceil # Ruby
-(i/-5)
0-i/-5       # for integers of i, provided by ShadowRanger
```

# Answer
> 2 votes
# Abs

Instead of

```
i<Math.abs(n)

```

,writing

```
i<n|i<-n

```

is shorter in some languages

EDIT:

```
i*i<n*n

```

is usually shorter suggested by ceilingcat

# Answer
> 1 votes
## Use magic numbers / magic strings

Code golfers tend to forget using magic numbers while they're golfing, so I'm putting some ways to make magic numbers here.

* The easiest way a magic number can be used is if the list or string you need to encode is one of two values (and then you can use bit-shifts and logical and to access the bitwise values stored in the magic number).

+ e.g. this answer is a pretty good usage of this type of magic numbers.
* You can also construct magic numbers/strings via brute force or a similar method.

# Answer
> 0 votes
plenty of larger powers (`^`) where an alternative representation is a lot cleaner :

```
   2 ^         10 ->  4^5
   2 ^         16 ->  4^8 (also 2^2^2^2)

   2 ^         12 ->  8^4
   2 ^         15 ->  8^5

   2 ^         24 ->  8^8
   2 ^         32 -> 16^8
   2 ^         48 ->  8^16
   2 ^         64 -> 16^16

   2 ^        256 -> 2^4^4 (also (4^8)^16, or 16^64)
   2 ^       1024 -> 2^4^5

   2 ^        128 -> 4^8^2 (also 16^32)
   2 ^       4096 -> 2^8^4
   2 ^       8192 -> 4^8^4

   2 ^         48 -> 8^4^2
   2 ^      65536 -> 2^4^8 (also 2^2^2^2^2)

   2 ^        512 -> 4^4^4
   2 ^     131072 -> 4^4^8

 even ridiculously large powers such as

   2 ^   16777216 -> 2^8^8
   2 ^   33554432 -> 4^8^8

   2 ^     524288 -> 4^4^9
   2 ^  268435456 -> 4^8^9

   2 ^ 1073741822 -> 2^(8^10-2) # very close to exponent
                                # upper limit of GMP

```

# Answer
> -1 votes
# Overloading for function

I find useful for golfing to use as C++ templates and give to the sys the chance of create function for the type (it would reduce the code written by one human).

Too if there are + function that use + or - the same algorithm, write all in one function only, that depends from one parameter for say what result one want. In this way recently condense 3 function in one with near 50% written code less; reference palpn() function in codegolf.stackexchange.com/a/148745/58988 .

---
Tags: code-golf, tips
---


title: Wordle games without repeating letters

text:
# Question
Title: Wordle games without repeating letters
Given a word list, find all sets of five words of five letters each, such that the words of each set have 25 distinct letters in total.

This challenge was inspired by this video by Matt Parker.

### Testcases

Use this file if you want to test your code against the English vocabulary. Sample output sets:

* `["fjord", "vibex", "waltz", "nymph", "gucks"]`
* `["fjord", "vibex", "waltz", "gymps", "chunk"]`

Here's a shorter version of the same file, with only words of five letters and no repeated letters. Here's an even shorter version with just 2000 words.

### Rules

* Standard I/O rules apply.
* Words contain only lowercase (or alternatively, uppercase) alphabetic characters.
* You can assume there are no empty words (i.e. words of length zero).
* The input can contain words that cannot belong to any set that satisfies the property, such as words with less than five letters, words with more than five letters, and words with repeated letters.
* You do not need to output every permutation of each valid set/list of five words.
* This is so the shortest code in bytes wins

Sandbox

# Answer
# Vyxal, 11 bytes

```
'L5=;5ḋ'∑Þu

```

Try it Online!

Get all 5 letter words, and all 5 word combinations where all the letters are unique.

## Explained

```
'L5=;5ḋ'∑Þu
'L5=;       # keep only words that are length 5
     5ḋ     # combinations without replacement of size 5
       '∑Þu # keep only those where the sum of all strings has all unique letters

```
> 7 votes

# Answer
# 05AB1E, 10 bytes

```
5ù5.ÆʒJDÙQ

```

Outputs as a list of lists.

Try it online.

**Explanation:**

```
5ù          # Keep all words of the (implicit) input-list of length 5
  5.Æ       # Get all 5-element combinations of the remaining words
     ʒ      # Filter this list of quintuplets by:
      J     #  Join the five words together to a single string
       DÙQ  #  Check that all characters are unique:
       D    #   Duplicate the string
        Ù   #   Uniquify its characters
         Q  #   Check if the two strings are still the same
            # (after which the filtered list of quintuplets are output implicitly)

```
> 4 votes

# Answer
# Japt v2.0a0, ~~14~~ 13 bytes

12 bytes if the words in each set do not need to be delimited.

```
l5 à5 fÈ¬¶X¬â

```

Try it (Test case borrowed from Neil)

```
l5 à5 fÈ¬¶X¬â     :Implicit input of word array
l5                :Filter words of length 5
   à5             :Combinations of length 5
      f           :Filter by
       È          :Passing each X through the following function
        ¬         :  Join
         ¶        :  Is equal to
          X¬      :  Join X
            â     :  Deduplicate

```
> 4 votes

# Answer
# Python,  ~~87~~  113 bytes

(+26 for word length filter)

i'm really interested in knowing if there's a way i could golf the 5-letter word length filter.

```
lambda x:[i for i in combinations([j for j in x if len(j)==5],5)if len({*''.join(i)})==25]
from itertools import*

```

Attempt This Online!
> 4 votes

# Answer
# Jelly, 12 bytes

```
Ẉẹ5ịœc5FQƑ$Ƈ

```

Try it online!

Outputs the sets of words. -1 byte to output all permutations.

## How it works

```
Ẉẹ5ịœc5FQƑ$Ƈ - Main link. Takes a list of words W on the left
Ẉ            - Lengths of each word
 ẹ5          - Indexes of 5s
   ị         - Index into W
    œc5      - All combinations without replacement of 5 words
          $Ƈ - Filter by the following:
       F     -   when flattened...
         Ƒ   -   ...the list is unchanged after...
        Q    -   ...only keeping unique elements

```
> 3 votes

# Answer
# JavaScript (V8), 88 bytes

Prints the sets as space-separated strings.

```
f=([w,...a],o='')=>o[29]?new Set(o).size-26||print(o):w&&f(a,o,w.length-5||f(a,o+w+' '))

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  [w,             //   w   = next word from the input array
      ...a],      //   a[] = array of remaining words
  o = ''          //   o   = output set, as a string
) =>              //
o[29] ?           // if we have 5 x 6 characters in o:
  new Set(o)      //   turn o into a set
  .size - 26      //   if its size is 26 (space included),
  || print(o)     //   print the output set
:                 // else:
  w &&            //   if w is defined,
  f(              //   do a 1st recursive call:
    a,            //     pass a[] unchanged
    o,            //     pass o unchanged
    w.length - 5  //     if the word has 5 characters,
    || f(         //     do a 2nd recursive call:
      a,          //       pass a[] unchanged
      o + w + ' ' //       append w and a space to o
    )             //     end of recursive call
  )               //   end of recursive call

```
> 3 votes

# Answer
# Charcoal, 35 bytes

```
⊞υωＷＳＦ⁼⁵Ｌι≔⁺υ⁺Φυ⬤ι¬№λνιυＥΦυ⁼²⁵Ｌι⪪ι⁵

```

Try it online! Link is to verbose version of code. Too slow for TIO with 2000 words so link uses the 106 "words" in the question at time of writing. Takes input as a list of newline-terminated words. Explanation:

```
⊞υω

```

Start with the empty string.

```
ＷＳＦ⁼⁵Ｌι

```

Loop over the input words of length `5`.

```
≔⁺υ⁺Φυ⬤ι¬№λνιυ

```

Get all of the existing strings that have no overlap with this word, append the current word to all of those strings, and append the resulting strings to the list.

```
ＥΦυ⁼²⁵Ｌι⪪ι⁵

```

Find all of the strings of length `25` and split them back into words.
> 3 votes

# Answer
# Pyth, 14 bytes

```
f{IsT.cfq5lTQ5

```

Try it online!

### Explanation

```
                  # implicitly assign Q = eval(input())
       f    Q     # filter Q on lambda T
        q5lT      #   length(T) == 5
     .c      5    # all 5 element combinations of the filtered list
f                 # filter on lambda T
 {IsT             #   T, concatenated to a single string is invariant under deduplicaiton

```
> 2 votes

# Answer
# Python, 104 bytes

```
lambda W:[w for w in combinations(W,5)if len({*chain(*w)})<<max(map(len,w))==800]
from itertools import*

```

Attempt This Online!

The direct port of the JS solution is shorter though :-(

```
def f(w=0,*R,g=""):len({*g})-26or print(g)if len(g)>29else w and(f(*R,g=g),len(w)-5or f(*R,g=g+w+" "))

```
> 2 votes

---
Tags: code-golf, string, alphabet, word-puzzle
---


title: Tips for golfing in OCaml

text:
# Question
Title: Tips for golfing in OCaml
Inspired from the assortment of other 'Tips for golfing in language xyz'. As usual, please only suggest tips that are specific to OCaml and not programming in general. One tip per answer please.

# Answer
## Use functions instead of match

```
let rec f=function[]->0|_::t->1+f t

```

is shorter than

```
let rec f x=match x with[]->0|_::t->1+f t

```
> 4 votes

# Answer
## Never use begin \[…\] end

This:

```
begin […] end

```

is always synonymous with this:

```
([…])

```
> 3 votes

# Answer
## Define several variables or functions at once

Thanks to tuples, you can define several variables at once. And as functions are first-class citizens…:

```
let f,g=(fun x->x+1),fun x->2*x

```

You can’t, however, write:

```
let f,g=(fun x->x+1),fun x->2*f x

```

> Error: Unbound value f

Unfortunately, you can’t avoid the issue by using `rec`:

```
let rec f,g=(fun x->x+1),fun x->2*f x

```

> Error: Only variables are allowed as left-hand side of `let rec`
> 2 votes

# Answer
## Exploit curryied functions

Functions in OCaml are curryied. It might be useful to exploit that fact sometimes.

```
let n y=f x y

```

can be written

```
let n=f x

```

If you need arithmetic operations, you can surround them with parentheses so they behave like standard, prefix functions. `(+)`, `(-)`, …

```
let n=(+)1;;
n 3;;

```

> `- : int = 4`
> 2 votes

# Answer
# `downto`

If you're not sure how to loop downwards, `downto` is usually the one to go for. Instead of:

```
for i=0 to 1000 do
Printf.printf"%d
"(1000-i)
done

```

You can do:

```
for i=1000 downto 0 do
Printf.printf"%d
"i
done

```
> 1 votes

# Answer
# `print_string`

Instead of the usual `Printf.printf""`, you can actually use the below (ONLY for strings, no formatting):

```
print_string"wassup"

```

Which is 1 byte shorter than:

```
Printf.printf"wassup"

```
> 0 votes

---
Tags: code-golf, tips
---


title: How did I end up with this FizzBuzz?

text:
# Question
Title: How did I end up with this FizzBuzz?
FizzBuzz is so simple, bet you can do it backwards. In this challenge, you will be given the length of the FizzBuzz string and must give the positive integer that produced that string.

## Description

To break this down, a FizzBuzz string for `n` is generated by the following algorithm.

Start with an empty string and, for every `i=1..n` (inclusive):

1. If `i` is divisible by `3` and by `5`, append `FizzBuzz` to the string.
2. If `i` is just divisible by `3` append `Fizz`.
3. If `i` is just divisible by `5` append `Buzz`.
4. If `i` is divisible by neither, append the decimal representation of `i`.

So for example `FizzBuzz(15)` is the following:

```
12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz

```

You will be given `Length(FizzBuzz(n))` and must determine `n`. You may assume that the input is positive and is always going to be the length of some FizzBuzz string.

## Rules

Your solution may a complete program or a function definition in any standardly acceptable language. Your program/function may take in arguments and return answers in any standardly accepted way. Standard loopholes are forbidden.

You may assume that the input is positive and valid (describes the length of some FizzBuzz string) and is smaller than the largest integer representable natively in your language.

This is code golf, so shortest byte-count wins.

## Examples

Here are some example cases

```
Length(FizzBuzz(n)) -> n
1                   -> 1
6                   -> 3
15                  -> 6
313                 -> 100
3677                -> 1001

```

## Edit

Fixed last test case. Thanks @SteadyBox.

# Answer
> 9 votes
# Jelly,  ~~16~~  14 bytes

<sup>2 bytes saved using more recent language features `)` for `µ€` and `Ä` for `+\`</sup>

```
3,5ḍS×4oDL$)Äi

```

**Try it online!** or see the test cases.

### How?

Builds a list of the lengths of every item from `1` to the input, reduces by addition and then finds the one-based index of the input in the list. (This also means an invalid input results in `0`, "not in list").

```
3,5ḍS×4oDL$)Äi - Main link: theLength
           )    - perform the chain to the left for each (€) in
                     implicit range from 1 to the input and
                     pass the result into the monadic chain (µ) to the right
3,5            - 3 paired with 5: [3,5]
   ḍ           - divides?  for a multiple of 15 [1,1]; sum = 2; times 4 = 8
    S          - sum       for a multiple of  5 [0,1]; sum = 1; times 4 = 4
     ×4        - times 4   for a multiple of  3 [1,0]; sum = 1; times 4 = 4
                           for none of those    [0,0]; sum = 0; times 4 = 0
          $    - last two links as a monad
        D      -     to decimal digit list
         L     -     length - e.g. 313 -> [3,1,3] -> 3
       o       - logical or: replace a 0 with the decimal length, keep the 4s and 8s
            Ä  - reduce with addition: e.g. [1,1,4,1, 4, 4, 1, 1, 4, 4, 2, 4, 2 ,2, 8]
                                         -> [1,2,6,7,11,15,16,17,21,25,27,31,33,35,43]
             i - index of theLength in that list (e.g. 15 is at index 6)

```

# Answer
> 12 votes
# C, ~~81~~ 78 bytes

```
l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?snprintf(0,0,"%d",i):4:i%5?4:8);return i;}

```

**68 bytes** if you don't mind converting to `double` and back:

```
l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?log10(i)+1:4:i%5?4:8);return i;}

```

# Answer
> 6 votes
# MATL, ~~31~~ ~~28~~ 27 bytes

```
`@:tI5h!\XJA)VXznJ~z4*+G-}@

```

Try it online!

### Explanation

```
`        % Do...while
  @:     %   Push array [1 2 ...k], where k is iteration index
  t      %   Duplicate
  I5h!   %   Push column vector [3; 5]
  \      %   Modulo, with broadcast. Gives 2 × k matrix
  XJ     %   Copy into clipboard J
  A      %   Row vector that contains true for columns that contain two nonzeros
  )      %   Index with that vector. This keeps numbers that are non-fizz/buzz
  V      %   Convert to string. This inserts spaces between numbers
  Xzn    %   Number of nonspace characters
  J      %   Push 2 × k matrix resulting from modulo operation again
  ~z     %   Number of zeros
  4*     %   Multiply by 4. Gives number of characters corresponding to fizz/buzz
  +      %   Add
  G-     %   Subtract input. This is the loop condition: exit if 0
}        % Finally (execute right before exiting loop)
  @      %   Push current iteration index
         % End (implicit)
         % Display (implicit)

```

# Answer
> 4 votes
## Mathematica, 67 bytes

```
(For[n=s=0,s<#,s+=Tr[4Boole[{3,5}∣++n]]/. 0:>IntegerLength@n];n)&

```

This is both faster and shorter than my initial solution:

```
1//.x_/;Sum[Tr[4Boole[{3,5}∣n]]/. 0:>IntegerLength@n,{n,x}]!=#:>x+1&

```

or my desperate attempt to shorten it:

```
(s=0;1)//.x_/;(s+=Tr[4Boole[{3,5}∣x]]/. 0:>IntegerLength@x)!=#:>x+1&

```

## Explanation

Standard `For` loop which increments `n` until `s := Length(FizzBuzz(n))` is at least equal to the input `#`. The only interesting bit is how I calculate the length of the `(n+1)`-th term of the FizzBuzz sequence

```
                ++n                           Preincrement n
          {3,5}∣                              Test for divisibility by 3 and 5 (returns a list)
    Boole[         ]                          Convert True to 1 and False to 0
   4                                          Multiply by 4
Tr[                 ]                         Sum
                     /.                       Replace
                        0                     0 (leading space is necessary or it thinks we are dividing by 0.0)
                         :>                   with
                           IntegerLength@n    the number of digits in n

```

# Answer
> 3 votes
# MATL, ~~31 30~~ 28 bytes

```
:tI5h!\~s4*t~b10&YlkQ*+YsG=f

```

Uses the same idea as Jonathan Allen's Jelly solution.

Try it on matl.io!

# Answer
> 3 votes
# Java 8, 100 97 bytes

Golfed:

```
l->{int i=0;for(String s="";s.length()<l;)s+=++i%15<1?"12345678":i%5<1||i%3<1?"1234":i;return i;}

```

Ungolfed:

```
import java.util.function.*;

public class HowDidIEndUpWithThisFizzBuzz {

  public static void main(String[] args) {
    for (final int[] data : new int[][] { { 1, 1 }, { 6, 3 }, { 15, 6 },
        { 313, 100 }, { 3677, 1001 } }) {
      final int fizzBuzzLength = data[0];
      final int expected = data[1];
      final int actual = f(l -> {
        int i = 0;
        for (String s = ""; s.length() < l;) {
          s += (++i % 15 < 1 ? "12345678" : (i % 5 < 1 || i % 3 < 1 ? "1234" : i));
        }
        return i;
      } , fizzBuzzLength);
      System.out.println("Length(FizzBuzz(n)) -> " + fizzBuzzLength);
      System.out.println("Expected            -> " + expected);
      System.out.println("Actual              -> " + actual);
      System.out.println();
    }

  }

  private static int f(IntFunction<Integer> function, int fizzBuzzLength) {
    return function.apply(fizzBuzzLength);
  }
}

```

Output:

```
Length(FizzBuzz(n)) -> 1
Expected            -> 1
Actual              -> 1

Length(FizzBuzz(n)) -> 6
Expected            -> 3
Actual              -> 3

Length(FizzBuzz(n)) -> 15
Expected            -> 6
Actual              -> 6

Length(FizzBuzz(n)) -> 313
Expected            -> 100
Actual              -> 100

Length(FizzBuzz(n)) -> 3677
Expected            -> 1001
Actual              -> 1001

```

# Answer
> 2 votes
## JavaScript (ES6), ~~62~~ 57 bytes

```
f=(n,k=0)=>n?f(n-(++k%3?k%5?`${k}`.length:4:k%5?4:8),k):k

```

### Test cases

```
f=(n,k=0)=>n?f(n-(++k%3?k%5?`${k}`.length:4:k%5?4:8),k):k

console.log(f(1   )); // -> 1
console.log(f(6   )); // -> 3
console.log(f(15  )); // -> 6
console.log(f(313 )); // -> 100
console.log(f(3677)); // -> 1001
```

# Answer
> 2 votes
# Javascript (ES6), 56 bytes

```
f=(x,s=i=0)=>s[x]?i:f(x,s+[++i%3?i%5?i:1e3:i%5?1e3:1e7])
```

```
<!-- snippet demo: -->
<input list=l oninput=console.log(f(this.value))>
<datalist id=l><option value=1><option value=6><option value=15><option value=313><option value=3677></datalist>
```

# Answer
> 2 votes
# Ruby, ~~69~~ 66 bytes

```
->n{i=0;(i+=1;n-=i%3>0?i%5>0?i.to_s.size: 4:i%5>0?4:8)while n>0;i}

```

Originally, I was avoiding the nested ternary operator *monstrosity* and got down to 69 bytes:

```
->n{i=0;(i+=1;n-=(x=[i%3,i%5].count 0)>0?4*x:i.to_s.size)while n>0;i}

```

# Answer
> 2 votes
# Python 3, 78 bytes

```
f=lambda i,n=1,s=0:~-n*(s==i)or f(i,n+1,s+(4*((n%3<1)+(n%5<1))or len(str(n))))

```

Recursive function. Will need the recursion limit increased for any result above 1000.

**Explanation:**

```
# i = length of final string
# n = current number in sequence, starting with 1
# s = length of current string, starting with 0
f=lambda i,n=1,s=0: \

# if s==1, this will evaluate to n+1, which is NOT 0, and will return
# else, it will evaluate to (n+1)*0, and trigger the second half of the OR clause
~-n*(s==i)or \

# recursively call the next iteration, with the next number in the sequence
f(i,n+1, \

# increase s by 4 if Fizz or Buzz, 8 if FizzBuzz, or len(n) if number
s+(4*((n%3<1)+(n%5<1))or len(str(n))))

```

# Answer
> 1 votes
# Python, 93 bytes

```
def g(n,c=0,a=[4,0]):
 while n:c+=1;s=a[c%3>0]+a[c%5>0];s+=(s<1)*len(str(c));n-=s
 return c

```

# Answer
> 1 votes
# Java 8, ~~95~~ 93 bytes

```
l->{int j=0,i=0;for(;j<l;)j+=++i%15<1?8:i%3<1||i%5<1?4:Math.floor(Math.log10(i)+1);return i;}

```

This is the optimized version of @Snowman's answer

# Answer
> 1 votes
# k, 33 bytes

```
{1+&x=+\{(#$x;4;8)+/~3 5!'x}'1+!x}

```

Brief (python-ish) explanation:

```
{                                } / function(x):
                             1+!x  /   array from 1 to x, inclusive
                            '      /   for y in array:
        {                  }       /     function(y):
         (#$x;4;8)                 /       yield [ len(str(y), 4, 8 ][
                  +/~3 5!'x        /         sum([not(y mod 3), not(y mod 5)])
                                   /       ]
      +\                           /   cumulative sum of result of for loop
 1+&x=                             /   get index of x in cumulative sum, add one

```

Example using kmac 2016.06.28:

```
 f:{1+&x=+\{(#$x;4;8)+/~3 5!'x}'1+!x}
 ,/f'1 6 15 313 3677
1 3 6 100 1001

```

# Answer
> 1 votes
# dc, ~~76~~ 70 bytes

```
?sa0dsbsc[lc4+sc]sh[lbZ+sc]so[lcdlb1+ddsb3%0=h5%0=hlc=olcla!=y]dsyxlbp

```

Try it online!

# Answer
> 1 votes
# Groovy, 76 bytes

`def f(n){i=0;for(s='';s.size()<n;)s+=++i%15<1?"1"*8:i%5<1||i%3<1?"1"*4:i;i;}`

Mostly the same as @Snowman's answer, but uses some Groovy magic/differences to cut down on the byte count.

# Answer
> 0 votes
# Perl 6, ~~55~~ 52 bytes

~~```
{1+first $_,:k,[\+] map {4*($_%%3+$_%%5)||.chars},1..*}

```~~
```
{(0,{my \i=++$;$_+(4*(i%%3+i%%5)||i.chars)}...$_)-1}

```

Try it online!

### How it works

```
{                                                  }  # A lambda.
  0                                                   # Start with 0.
   ,{                                     }           # Use the iteration formula...
     my \i=++$;                                       #   Fetch current index.
               $_+(                      )            #   Last element plus:
                   4*(i%%3+i%%5)                      #     Fizz/Buzz/FizzBuzz length,
                                ||i.chars             #     or number length.
                                           ...$_      # ...until the input is reached.
 (                                              )-1   # Sequence length minus 1.

```

# Answer
> 0 votes
# Japt, 20 bytes

```
@µ35ìx_XvZÃ*4ªXìÊ}f1

```

Try it

```
@µ35ìx_XvZÃ*4ªXìÊ}f1     :Implicit input of integer U
@                        :Function taking an integer X as argument
 µ                       :  Decrement U by
  35ì                    :    Digit array of 35
     x                   :    Reduce by addition
      _                  :    After passing each Z through the following function
       XvZ               :      Is X divisible by Z?
          Ã              :    End reduce
           *4            :    Multiply by 4
             ª           :    Logical OR with
              Xì         :      Digit array of X
                Ê        :      Length
                 }       :End function
                  f1     :First integer >=1 that returns a falsey value (i.e, 0) when passed through that function

```

# Answer
> 0 votes
# Perl 5 `-p`, 48 bytes

```
$\++;($_-=4*(!($\%3)+!($\%5))||length$\)&&redo}{

```

Try it online!

# Answer
> 0 votes
# C (gcc), 68 bytes, `stdout`-spamming

* Thanks to H.PWiz for this approach, saving six bytes.

```
f(n,j,r){for(r=j=0;!r;r=!n*j)n-=++j%3?j%5?printf("%d",j):4:j%5?4:8;}

```

Try it online!

---

# C (gcc), 74 bytes

```
f(n,j,r){for(r=j=0;!r;r=!n*j)n-=++j%3?j%5?snprintf(0,0,"%d",j):4:j%5?4:8;}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 17 bytes

```
Lε35SÖ4*OygM}.¥sk

```

Try it online or verify all test cases.

**Explanation:**

```
L          # Create a list in the range [1, (implicit) input]
           #  i.e. 15 → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
 ε         # Map each value to:
  35S      #  Push 35 as digit list: [3,5]
     Ö     #  Check if the current value is divisible by these (1 if truthy; 0 if falsey)
      4*   #  Multiply both by 4
        O  #  And take the sum of that
           #   i.e. 2 → [0,0] → [0,0] → 0
           #   i.e. 9 → [1,0] → [4,0] → 4
           #   i.e. 10 → [0,1] → [0,4] → 4
           #   i.e. 15 → [1,1] → [4,4] → 8
  yg       #  Push the current value again, and pop and push it's length
           #   i.e. 2 → 1
           #   i.e. 15 → 2
  M        #  And then push the largest value on the stack
           #   i.e. 0 and 1 → 1
           #   i.e. 8 and 2 → 8
 }.¥       # After the map: undelta the list (starting from 0)
           #  i.e. [1,1,4,1,4,4,1,1,4,4,2,4,2,2,8]
           #   → [0,1,2,6,7,11,15,16,17,21,25,27,31,33,35,43]
    sk     # Swap to get the (implicit) input, and get its 0-based index in the list
           #  i.e. 15 → 6
           # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Python 3 (79 bytes)

```
f=lambda s,n=0,l=0:l-len(s)and f(s,n+1,l+(4*(n%3//2+n%5//4)or len(str(n))))or n

```

# Python 2 (74 bytes)

```
f=lambda s,n=0,l=0:l-len(s)and f(s,n+1,l+(4*(n%3/2+n%5/4)or len(`n`)))or n

```

# Answer
> 0 votes
# Python 3.8 (86 bytes)

```
f=lambda s:len(s.rpartition("z")[2])/len(str(n:=max(s.count("F")*3,s.count("B")*5)))+n

```

This exploits the fact that after the last "Fizz" or "Buzz", all the following integers have the same number of digits.

Try it Online

# Answer
> 0 votes
# Thunno, \\$ 29 \log\_{256}(96) \approx \\$ 23.87 bytes

```
Re1+Ax35d%.!S4*xdL~Ez(A$sAh1+

```

Port of Jonathan Allan's Jelly answer.

#### Explanation

```
           # Implicit input
Re         # Loop through range(0, input):
  1+Ax     #   Add one and store in x without popping
      35d  #   Pair [3, 5]
%.!        #   Check for divisibility
   S4*     #   Multiply the sum by 4
      xdL  #   Get the length of the digits of x
~          #   Do a logical or
 E         # End the loop
  z(       # Get the running sums of the list
    A$     # Push the input
      sAh  # Get the index of this in the running sums
1+         # And add one to account for Thunno's 0-indexing
           # Implicit output

```

#### Screenshot

---
Tags: code-golf, fizzbuzz
---


title: Non-Unique/Duplicate Elements

text:
# Question
Title: Non-Unique/Duplicate Elements
Write a program which finds the non-unique elements of an array of signed integers. The resulting array can be in any order.

Your answer may be a snippet which assumes the input to be stored in a variable (`d`, say) and evaluates to the correct result.

### Test Cases

Each test case is a single line in the format `input => output`. Note that other permutations of the output are valid as well.

```
[]                        => []
[-1, 0, 1]                => []
[1, 1]                    => [1]
[3, 0, 0, 1, 1, 0, 5, 3]  => [3, 0, 1]
[-34, 0, 1, -34, 4, 8, 4] => [-34, 4]

```

Order of the elements doesn't matter.

This is code golf, so the shortest answer (in bytes) wins.

# Answer
# K5, 5 bytes

Assuming the input is already in a variable called `d`,

```
?d^?d

```

Take the distinct elements (`?`) of d except (`d^`) the distinct elements of d (`?d`). Nicely symmetrical, no? This works because the "except" operator removes only the first occurrence of the right argument from the left argument.

More generally,

```
nu: {?x^?x}

```

In action:

```
  nu'(();-1 0 1;1 1;3 0 0 1 1 0 5 3;-34 0 1 -34 4 8 4)
(()
 ()
 ,1
 0 1 3
 -34 4)

```

## Edit:

If we wanted to preserve the order of the first occurrence of non-unique elements, we could reverse the source list before and after we remove the unique elements via except at the cost of 4 extra bytes:

```
  nu: {?|(|x)^?x}
  nu'(();-1 0 1;1 1;3 0 0 1 1 0 5 3;-34 0 1 -34 4 8 4)
(()
 ()
 ,1
 3 0 1
 -34 4)

```
> 18 votes

# Answer
# CJam, 10

Assuming the array is already in variable D (based on this comment):

```
D{De=(},_&

```

Try it online

**Explanation:**

```
D{…},   filter items of D based on the block
  De=   count occurrences in D
  (     decrement (resulting in true/false for duplicate/unique)
_&      remove duplicates from the results

```

Note: append a `p` if you want pretty printing, otherwise the resulting array is just printed out with no delimiters by default. That is acceptable since the question specifies the snippet only needs to "evaluate to the correct result".

## Standard input/output version, 13:

```
q~_{1$e=(},&p

```

Try it online

**Explanation:**

```
q~      read and evaluate the input array
_       duplicate the array
{…},    filter items based on the block
  1$    copy the array
  e=    count occurrences
  (     decrement (resulting in true/false for duplicate/unique)
&       set intersection with the initial array (removes duplicates)
p       pretty print

```
> 10 votes

# Answer
## Haskell - 32

```
import Data.List;f l=nub$l\\nub l

```

Pretty short, even with the import. `a \\ b` removes the first occurrence of each element of `b` from `a`, and `nub` makes all elements of a list unique.
> 9 votes

# Answer
# Pyth, 7 bytes

```
S{.-Q{Q

```

Try it online.

### How it works

Pyth automatically stores the evaluated input in `Q` and prints all unused return values.

```
     {Q  Convert Q into a set. This removes duplicates.
  .-Q    Perform "bagwise" difference of Q and set(Q).
         This removes the first occurrence of all elements in Q.
 {       Convert to set to deduplicate.
S        Sort. Returns a list.

```
> 7 votes

# Answer
# SQL, ~~44~~ 42 bytes

```
SELECT*FROM D GROUP BY I HAVING COUNT(*)>1

```

I hope it is OK to assume the integers are stored in table D? This will work in both SQLServer, PostgreSQL and possibly others. Thanks to @manatwork from the 2 bytes.
> 7 votes

# Answer
# Matlab / Octave, 40

I'm assuming input values are real (not complex). The input is in a variable `d`.

```
unique(d(sum(triu(bsxfun(@eq,d,d')))>1))

```

Try it online in Octave.
> 6 votes

# Answer
## Mathematica, ~~29~~ 26 bytes

Assuming that input is stored in `d`:

```
Select[d⋃d,d~Count~#>1&]

```

Otherwise, it's 29 bytes as an unnamed function:

```
Cases[#⋃#,n_/;#~Count~n>1]&

```

Here, `d⋃d` (or `#⋃#`) is a golfing trick to remove duplicates - by taking the set union with itself, Mathematica interprets the list as a set, removing duplicates automatically, while the actual union doesn't do anything.

Afterwards, both methods simply filter those elements which appear in the original list at least twice.
> 6 votes

# Answer
# APL (Dyalog Unicode), ~~13~~ 9 bytesSBCS

Anonymous tacit prefix function.

```
∊(⊂1↓⊣¨)⌸

```

Try it online!

`(``)⌸` for each unique element (left argument) and the indices where it occurs (right argument), apply the following tacit function:

`⊣¨` one of the left (the unique element) for each on the right (the indices)

`1↓` drop one

enclose (prevents padding with zeros to create a non-ragged matrix)

**ϵ**nlist (flatten)
> 6 votes

# Answer
# PowerShell, ~~31~~ 29 Bytes

```
($d|group|?{$_.Count-1}).Name

```

Assumes that `$d` is already populated (as given) -- e.g., `$d=@(-34,0,1,-34,4,8,4)`.

Pipes the array into the `Group-Object` cmdlet, which groups like-items together and spits out an object that's essentially an array of arrays. We pipe that to a `Where-Object` (the `?` operator) that has `Count` greater than one (i.e., there are duplicates), and output the `.Name` of those items. Has a side bonus of preserving the initial ordering, too.

Edit - saved two bytes thanks to Danko Durbić
> 6 votes

# Answer
# JavaScript (ES6), 37 bytes

Run this in the JavaScript console:

```
e={};d.filter(x=>(e[x]=1+e[x]||0)==1)

```
> 6 votes

# Answer
## Python 3.5, 30

```
[x for x in{*d}if~-d.count(x)]

```

Uses Python 3.5's set unpacking. The `~-` subtracts 1, which takes a count of 1 to 0 which is Falsy.

This gives a list. If giving a set is OK, then we use a set comprehension, saving 1 char and not needing version 3.5:

```
{x for x in d if~-d.count(x)}

```
> 6 votes

# Answer
# R, ~~31~~ 24 bytes

Thanks to flodel for the 7 bytes.

Assuming the input is already in `d`.

### code:

```
unique(d[duplicated(d)])

```

edit: now it outputs correctly if there are more than 2 duplicates as pointed by aditsu.
> 5 votes

# Answer
# Julia, ~~30~~ 29 bytes

```
∪(d[find(sum(d.==d',1)-1)])

```

`d.==d'` creates a symmetric matrix with the value at `i,j` being true if `d[i]==d[j]` and false otherwise. `sum`ming in one dimension and then subtracting 1 will produce zero if there's only one of the element and nonzero if there's more than one. `find` will obtain the indexes of the non-zero elements, which are then used to index the array `d` itself.  (union) acts like `unique` when used in this way, removing the repeats.

Old solution:

```
∪(filter(i->sum(d.==i)>1,d))

```

Simple - for each entry, it checks if there's more than one of it in the array. Those for which there are more than one are returned by "filter", and then  (union) acts like `unique` when used in this way, removing the repeats.

Note: originally had it as a function, but question allows array to be stored in a variable, for which I've chosen `d` as suggested in the question.
> 5 votes

# Answer
# Octave, 22 bytes

Based on Luis Mendo's answer.

```
d(sum(triu(d==d'))==2)

```
> 5 votes

# Answer
# Mathematica, ~~31~~ 29

```
Cases[{s_,t_/;t>1}:>s]@*Tally

```
> 4 votes

# Answer
# Python 2.7, ~~36~~ 42

```
list(set(filter(lambda x:d.count(x)>1,d)))

```

*edit* : surrounded the expression with list(..) in order to comply with the format required in the question
> 4 votes

# Answer
# Python 3 - ~~33~~ 30 bytes

`{_ for _ in d if d.count(_)>1}`

Repl output, `d` as input.
> 4 votes

# Answer
# Shell + GNU coreutils, 12

```
sort|uniq -d

```

### Test output:

```
$ printf "%s\n" -34 0 1 -34 4 8 4 | ./nonuniq.sh
-34
4
$

```
> 4 votes

# Answer
# Pyth, 7 bytes

```
ft/QT{Q

```

Explanation:

```
ft/QT{Q
           Q = eval(input())
     {Q    set(Q) - deduplicate
f          filter - with T as the filter variable.
  /QT      count in Q of T
 t         minus 1.

```

The filter removes all elements that appear exactly once from the set of elements.
> 4 votes

# Answer
## LINQ,62 54 bytes

Kinda new here, but here goes nothing.

```
d.GroupBy(c=>c).Where(g=>g.Count()>1).Select(g=>g.Key)

```
> 4 votes

# Answer
# K (not K5), 10 bytes

```
x@&1<#:'=x

```

Assumes input is in `x`. I thought it'd be fun to do a non-K5 answer!
> 4 votes

# Answer
# K (oK), 7 bytes

**Solution:**

```
&1<#:'=

```

Try it online!

**Explanation:**

```
&1<#:'= / the solution
      = / group, key => value (index)
   #:'  / count length of each group
 1<     / 1 less than
&       / keys where true

```
> 4 votes

# Answer
# Haskell + hgl, ~~11~~ 10 bytes

```
(!!1)~<<bg

```

Attempt This Online!

## Explanation

* `bg` sort a list into lists of like values.
* `(!!1)` get the second value or `[]` if there is none.

We use `~<<` to glue these together, which basically acts as a concat map.

## Reflection

This works pretty well, but the operator precedence is killing me. Both of the following work but requires the parens to prevent an error.

```
nb<(df^*nb)
nb<(fdf~<nb)

```

If the operator precedence was different both of these would be competitive with the first one actually saving bytes.

I don't know if that means the precedence is wrong, but it's worth noticing.

`(!!)` should have a prefix function, *and* a bunch of versions with the index prefilled. I noticed this earlier but still didn't fix it, and now it's coming back to haunt me.
> 4 votes

# Answer
# Ruby, ~~30~~ 28 bytes

In the Interactive Ruby Shell:

```
d.select{|x|d.count(x)>1}|[]

```

Saved 2 bytes thanks to Kirill L.
> 3 votes

# Answer
## Mathematica, 23 bytes

With input stored in `d`:

```
Pick[#,#2>1]&@@@Tally@d

```

As a function, 24 bytes:

```
Pick[#,#2>1]&@@@Tally@#&

```

for example, with

```
d = {3, 0, 0, 1, 1, 0, 5, 3}
Tally@d

```

returns this:

```
   {{3, 2},
    {0, 3},
    {1, 2},
    {5, 1}}

```

(first element of each sublist is the element, second one is frequency of occurrence). Applying to this list `Pick[#,#2>1]&@@@` transforms it to

```
{Pick[3,2>1], Pick[0,3>1], Pick[1,2>1], Pick[5,1>1]}

```

And where the second argument of `Pick` evaluates to `True` the first argument is returned.
> 3 votes

# Answer
## Perl 6, 16 bytes

Assuming the list is stored in `$_` you could use any of the following snippets.
( which was specifically allowed )

```
(--«.BagHash).Set.keys # 23 bytes

```

```
keys .Bag (-) .Set # 18 bytes

```

```
# U+2216 SET MINUS
keys .Bag∖.Set # 16 bytes in utf8

```

---

If you don't care that you get a Bag you could leave off `keys`.

```
$_ = [3, 0, 0, 1, 1, 0, 5, 3];
.Bag∖.Set ∋ 3 # True
.Bag∖.Set ∋ 5 # False

```

---

None of these have the limitation of only working on signed integers, or even just numbers for that matter.

```
say keys .Bag∖.Set given |(<a b c d a a c>), 1/3, 2/3 - 1/3;
# (a c 0.333333)

```
> 3 votes

# Answer
# JavaScript, ~~35~~ ~~28~~ 34 bytes

```
a=>a.filter(o=x=>(o[x]=-~o[x])==2)

```

Try It Online!
> 3 votes

# Answer
# Husk, 4 bytes

```
u-u¹

```

Try it online!

```
u       # unique element of
 -      # set difference between
  u¹    # unique elements of input
        # and input

```
> 3 votes

# Answer
# Thunno `D`, \\$7 \log\_{256}(96) \approx\\$ 5.76 bytes

Note: this only works on Thunno 1.1.3+

```
gc1>kZU

```

(No ATO link since that's on v1.1.0 at the moment)

### Explanation

```
gc1>kZU   # Implicit input. The D flag duplicates it implicitly.
g   k     # Filter the input for elements where the following is truthy:
 c        #   The count of the element in the input
  1>      #   Is greater than 1
     ZU   # Deduplicate and output implicitly

```
> 3 votes

# Answer
# Common Lisp, 57 bytes

```
(remove-duplicates(remove-if(lambda(x)(<(count x d)2))d))

```
> 2 votes

# Answer
# Octave, 33 bytes

```
[~,a]=unique(d);d(a)=[];unique(d)

```
* Finds the indices of the first occurrence of each unique integer,
* removes those occurrences, and
* finds the unique elements of the remaining array.

Here it is on ideone. I've wrapped the snippet in a function so I could call it using all of the sample inputs.
> 2 votes

# Answer
**Java 8, 80 Bytes**

```
x.stream().filter(i->x.indexOf(i)!=x.lastIndexOf(i)).collect(Collectors.toSet())

```

Assuming x contains the input List of numbers.
> 2 votes

# Answer
# PHP, 35 ~~37~~ bytes

Pretty straight forward:

```
array_diff_key($a,array_unique($a))

```

---

**As a note:** I didn't add the `;` at the end of the line, as the questions states:

> Your answer may be a snippet which assumes the input to be stored in a variable (d, say) and evaluates to the correct result

So this snippet could be used like this and evaluates to the correct result:

```
print implode(' ', array_diff_key($a,array_unique($a)));

```

---

**Another note**

The code above works for all test cases provided in the challenge. In those all non-unique characters are at most duplicates. If a element can occur more than two times, another `array_unique()` would be necessary, which increases the length to **49 bytes**:

```
array_unique(array_diff_key($a,array_unique($a)))

```

---

**Edits**

* *Saved* **2 bytes** by replacing `array_diff_assoc` with `array_diff_key`. Thanks to Jörg Hülsermann.
> 2 votes

# Answer
# Japt, 7 bytes

```
â £kX â

```

Try it online!

## Explanation:

```
â £kX â
â         // Get all unique items from the input
  £       // Map X through the results
   kX     //   Remove X from the input
      â   //   Get unique items
-h        // Return the last item

```
> 2 votes

# Answer
# Factor, 10 bytes

```
duplicates

```

Try it online!

Builtin
> 2 votes

# Answer
# Elm, 91 bytes

```
e=List.member
g x z=case z of
 a::b->g(a::x)b++if e a b&&not(e a x)then[a]else[]
 _->[]

```

```
g[]

```
> 2 votes

# Answer
# Curry (PAKCS), 58 bytes

```
x!(y:z)|elem y z&&all(/=y)x=y:(y:x)!z|1>0=x!z
_![]=[]

```

```
([]!)

```

Attempt This Online!

Weirdish port of my Elm answer. Curry has nicer built in functions and pattern matching than Elm.
> 2 votes

# Answer
# Hassium, 104 Bytes

```
func main(){r=[];i=[];foreach(e in d)if(!i.contains(e))i.add(e)else if(!r.contains(e))r.add(e);print(r)}

```

Run online and see expanded here
> 1 votes

# Answer
# Python, 143 bytes

There are already some very good Python answers out there (see @dieters, @ppperry & @xnor answers) so I decided to take a different approach, have some fun with recursion and python `lambda` functions and see what could I come up with. This is not even close to the best answers here but it was fun to think.

The program takes the integer list as a parameter of function `p` and returns a list containing non-unique elements.

```
p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']

```

Two line version for better readability:

```
p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if
len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']

```

### Short Explanation

The inner `lambda` takes a list `x` as a parameter and returns the first element of such list if it is repeated only once in the rest of the list (`x[1:]`). If not it returns `'N'`.

The `lambda` in between the outer and inner `lambdas` is the one in charge of the recursive search. This returns a list containing the non-unique elements and plenty of `'N's`. This is the one which takes the integer list as a parameter.

The outer `lambda` filters the resulting list getting rid of the unwanted `'N's`.

### Test cases

```
p([])
[]
p([-1,0,1])
[]
p([3, 0, 0, 1, 1, 0, 5, 3])
[3,0,1]

```
> 1 votes

# Answer
## STATA, 18 bytes

```
bys v:drop if _n-2

```

Note that this requires the paid version of STATA.

Assumes the data is stored in a variable `v` and then the result will be in `v` at the end. It works by sorting by `v` and grouping duplicate values together. Each duplicate value will have at least two values, which means it can drop anything that is not the second element of each value. Third and subsequent elements will already be represented and the first element will either be unique or represented by the second.

For example, make a file a.b with data:

```
3
0
0
1
1
0
5
3

```

Then run the following code

```
insheet using a.b,clear
rename v1 v
bys v:drop if _n-2 //the actual code that does stuff
list v,noobs noheader

```
> 1 votes

# Answer
# J, ~~12~~ ~~14~~ 13 bytes

```
~.d#~1<+/=/~d

```

Assumes the list is in `d`.

Explanation:

```
         =/~d   NB. compare each element in d to each element in d
       +/       NB. sum the columns (giving amount of occurrences)
     1<         NB. see which columns are greater than 1 (=not unique)
  d#~           NB. select those elements from d
~.              NB. unique elements from that

```

If an anonymous function is OK as well, it can be shortened to ~~13~~ 12:

```
~.#~1<+/"1@=

```
> 1 votes

# Answer
**C# - 40**

```
i.GroupBy(g=>g).SelectMany(s=>s.Skip(1))

```

Using select many to be able to use Skip and skip the first occurrence if it exists.
> 1 votes

# Answer
# Jelly, 4 bytes, language postdates challenge

```
œ-QQ

```

Try it online!

Same algorithm as the accepted answer, just a shorter syntax.
> 1 votes

# Answer
# PHP, 75 bytes

```
function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}

```

Try it online!
> 1 votes

# Answer
## Python 2.7, 36 bytes

```
list({x for x in i if i.count(x)>1})

```

Where `i` is the input
> 1 votes

# Answer
# 05AB1E, ~~8~~ ~~6~~ ~~5~~ 4 bytes

```
¢ÏKÙ

```

Try it online or verify all test cases.

**Explanation:**

```
      #  e.g. input=[1,2,3,2,1,1,6,4,5,6]
¢     # Count how many times each item of the (implicit) input-list occurs in the
      # (implicit) input-list
      #  → [3,2,1,2,3,3,2,1,1,2]
 Ï    # Only keep the values in the (implicit) input-list at the truthy (==1) indices
      #  → [3,4,5]
  K   # Remove those values from the (implicit) input-list, leaving all non-unique items
      #  → [1,2,2,1,1,6,6]
   Ù  # Uniquify that list of non-unique items
      #  → [1,2,6]
      # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Kotlin, 41 bytes

```
{it.filter{v->it.count{it==v}>1}.toSet()}

```

Try it online!
> 1 votes

# Answer
# Perl 6, 14 bytes

```
*.repeated.Set

```

Try it online!

Gets a `Set` of the `repeated` elements.
> 1 votes

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

```
f=>[...new Set(f.filter(e=>f.indexOf(e)!=f.lastIndexOf(e)))]

```

Try it online!
> 1 votes

# Answer
# JavaScript (Node.js), 43 bytes (another try)

```
a=>a.filter((t={},e=>!(1-(t[e]=++t[e]|0))))

```

Try it online!
> 1 votes

# Answer
# Burlesque, 9 bytes

```
peJNB\\NB

```

Try it online!

```
pe # Parse and push
J  # Duplicate
NB # Remove duplicate elements
\\ # Difference between nubbed and original lists
NB # Nub the difference

```
> 1 votes

# Answer
# Perl 5, 18 bytes

Since a snippet is allowed here, the input is assumed to be in `@F`. The TIO link adds a little I/O around it.

```
grep++$k{$_}==2,@F

```

Try it online!
> 1 votes

# Answer
# , 24 bytes

```
names((t=table(v))[t>1])

```

Try it online!

Completely different approach to the previous  answer for the same number of bytes when written (as here) as a snippet with pre-defined variable `v`, but 4 bytes shorter as a full program (which, admittedly, isn't required by the challenge).
Outputs the non-unique elements as a vector of strings.

---

# , 25 bytes

```
(r=rle(sort(v)))$v[r$l>1]

```

Try it online!

One byte longer (and yet another approach) if you want to output as an integer vector.
> 1 votes

# Answer
# Vyxal, 4 bytes

```
UÞ⊍U

```

Try it Online!

Multiset Symmetric difference is very powerful
> 1 votes

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

```
a=>a.filter(o=x=>a.a+a+a==(o[x]+=a))

```

Try it online!
> 1 votes

# Answer
# jq, 22 bytes

```
[group_by(.)[][1:2][]]

```

Try it online!

Explanation:

```
[                    ]     # collect
                   []      # each
              [1:2]        # second item
            []             # from each
 group_by( )               # array of arrays of
          .                # identical values

```
> 1 votes

# Answer
# Zsh coreutils, 15 bytes

```
sort|uniq -d|rs

```

Try it online!
> 1 votes

# Answer
# Pip `-p`, 11 bytes

```
UQ:_Ng>1FIg

```

Takes the integers as command-line arguments. Attempt This Online!

### Explanation

```
UQ:_Ng>1FIg
          g  List of command-line arguments
        FI   Filter by this function:
   _N          The number of times this element appears in
     g         the list of command-line arguments
      >1       is greater than one
UQ:          Uniquify the resulting list

```
> 0 votes

# Answer
# Arturo, 40 bytes

```
unique select b'x[1<size select b=>[=x]]

```

Try it
> 0 votes

# Answer
# Japt, 7 bytes

```
ü lÉ cÎ

```

Try it (includes all test cases)

```
ü lÉ cÎ     :Implicit input of integer
ü           :Group & sort by value
  l         :Filter by length
   É        :  Minus 1
     c      :Flat map
      Î     :  First element

```
> 0 votes

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