# Question
Title: Duplicates in "n × hamming weight of n" sequence
## Background

The sequence in the title is A245788 "n times the number of 1's in the binary expansion of n" ("times" here means multiplication), which starts like this:

```
1,   2,   6,   4,   10,  12,  21,  8,   18,  20,
33,  24,  39,  42,  60,  16,  34,  36,  57,  40,
63,  66,  92,  48,  75,  78,  108, 84,  116, 120,
155, 32,  66,  68,  105, 72,  111, 114, 156, 80,
123, 126, 172, 132, 180, 184, 235, 96,  147, 150,
204, 156, 212, 216, 275, 168, 228, 232, 295, 240, ...

```

Though it is not immediately obvious, this sequence has some duplicates (same number appearing at least twice). The first duplicate appears at \\$a(22) = a(33) = 66\\$. The next ones are \\$a(39) = a(52) = 156\\$, and \\$a(44) = a(66) = 132\\$. Note that the duplicates do not appear in ascending order.

It is easy to prove that there exist infinitely many duplicates in this sequence, and I suspect that there exist infinitely many \\$k\\$-plicates (the numbers that appear at least \\$k\\$ times in the sequence) as well. For the record, the first triplicate entry is \\$a(1236) = a(1545) = a(2060) = 6180\\$.

## Challenge

Produce the sequence of **unique** duplicates in A245788, **in ascending order**. For example, 156 should appear after 132, and 6180 should appear only once in the sequence. The following is the list of all 124 terms under 10000, generated using this Python program:

```
66,   132,  156,  228,  264,  300,  312,  420,  435,  456,
528,  588,  600,  624,  804,  840,  870,  912,  1056, 1100,
1164, 1176, 1200, 1220, 1248, 1545, 1572, 1608, 1635, 1680,
1740, 1824, 2050, 2100, 2112, 2196, 2200, 2244, 2316, 2328,
2340, 2352, 2400, 2440, 2496, 2580, 2628, 2820, 3090, 3108,
3140, 3144, 3216, 3270, 3325, 3360, 3480, 3535, 3648, 3690,
4025, 4098, 4100, 4200, 4224, 4260, 4392, 4400, 4488, 4620,
4632, 4656, 4680, 4704, 4800, 4880, 4914, 4992, 5160, 5256,
5640, 5880, 6125, 6180, 6195, 6216, 6280, 6288, 6432, 6510,
6540, 6650, 6660, 6720, 6960, 7070, 7296, 7380, 7608, 8040,
8050, 8196, 8200, 8220, 8292, 8400, 8448, 8490, 8520, 8580,
8784, 8800, 8976, 9228, 9240, 9264, 9312, 9360, 9408, 9600,
9732, 9760, 9828, 9984

```

Default I/O methods for are allowed:

* Take no input, and output the terms infinitely.
* Take \\$n\\$ as input, and output the \\$n\\$-th term (0- or 1-indexed).
* Take \\$n\\$ as input, and output the first \\$n\\$ terms.

Standard rules apply. The shortest code in bytes wins.

# Answer
> 13 votes
# JavaScript (V8),  ~~72 71 70~~  69 bytes

A full program that prints the sequence forever.

```
for(n=1;c=2;c||print(n))for(d=++n;d--;)c>>=n==(h=n=>n&&h(n&n-1)+d)(d)

```

Try it online!

### Commented

```
for(                   // infinite outer loop:
  n = 1;               //   start with n = 1
  c = 2;               //   before each iteration: initialize c to 2
  c || print(n)        //   after each iteration: print n if c = 0
)                      //
  for(                 //   inner loop:
    d = ++n;           //     increment n and start with d = n
    d--;               //     stop when d = 0 / decrement d
  )                    //
    c >>=              //     right-shift d by 1 position if ...
      n == (           //       ... n is equal to ...
        h = n =>       //       ... the result of the recursive function h
          n &&         //       which adds d as many times as there are
          h(n & n - 1) //       bits set in d, using n & n - 1 to clear
          + d          //       the least significant bit at each iteration
      )(d)             //

```

### Note

We decrement \\$d\\$ right away in the inner loop, which means that we never consider the case where the divisor of \\$n\\$ is \\$n\\$ itself. But that would only work if there's a single 1 in the binary representation of \\$n\\$, which means that \\$n\\$ is a power of \\$2\\$ and all its divisors have a single 1 in their binary representation as well. Therefore, \\$n=1\times n\\$ is the only possible solution and \\$n\\$ does not belong to the sequence.

# Answer
> 7 votes
# Jelly, 9 bytes

```
×BS)ċ>1µ#

```

Try it online!

-1 byte thanks to Jonathan Allan

## Explanation

```
×BS)ċ>1µ#  Main Link
        #  nfind; find first (read from stdin) numbers such that
     >1    there is more than one
    ċ      occurrence of the original number in the list of
   )       each number from 1 to N
×BS        multiplied by its hamming weight

```

Note that `×BS` doesn't actually chain as `× (B S)`. In other words, this isn't *actually* multiplying each number by its hamming weight. However, by distribution of multiplication over addition, instead of doing \\$a\times(b\_1+b\_2+\dots+b\_n)\\$, it's actually doing \\$ab\_1+ab\_2+\dots+ab\_n\\$ because `×` vectorizes, and those happen to be literally the same thing. It chains as `(× B) S`, but that ends up giving the same result.

# Answer
> 6 votes
# Scala, ~~144~~ 135 bytes

Saved 9 bytes thanks to Kirill L.!

```
n=>Stream.from(1).scanLeft(0::Nil)((s,x)=>x*Integer.bitCount(x)::s).collect{case h::t if t toSet h=>h}.distinct.take(n*2).sorted take n

```

Try it in Scastie!

Pretty naive solution. Returns the first n elements.

```
n =>  //How many elements you want
Stream.from(1)  //Infinite list of natural numbers
.scanLeft(0::Nil) //Scan left, collecting prefixes of hamming number sequence (reversed)
((s,x) =>    //s is the previous sequence, x is a natural number
  x * Integer.bitCount(x)  //Find the next hamming number
    ::s)   //Prepend to s
.collect{  //Keep the ones that work with this PartialFunction:
  case h::t  //A prefix with hamming number h at the start and initial piece t
    if t toSet h =>  //If h is a duplicate
    h        //Keep h
}.distinct  //Uniquify
.take(n*2)  //Take the first 2n elements
.sorted    //Sort them
take n    //Take the first n elements

```

# Answer
> 3 votes
# Pyth, ~~19~~ 15 bytes

```
.f<1lfq*TsjT2ZS

```

Try it online!

Outputs the first \\$n\\$ elements of the sequence.

Explanation:

```
.f<1lfq*TsjT2ZS   | Full program
.f<1lfq*TsjT2ZSZQ | with implicit variables
------------------+--------------------------------------------------
.f              Q | first Q (input) numbers Z starting at 1 such that
    lf        SZ  |  the number of elements T of [1, Z] such that
       *TsjT2     |   T * sum of digits of T in base 2
      q      Z    |   equals Z
  <1              |  is greater than 1

```

# Answer
> 3 votes
# Haskell, 65 bytes

```
[x|x<-[1..],sum[1|n<-[1..x],n*h!!(n-1)==x]>1]
h=1:do x<-h;[x,x+1]

```

Try it online!

The list defined in the first line is the infinite list of duplicates in the sequence. `h` is a helper infinite list that contains the hamming weight of \\$n\\$ at position \\$n-1\\$.

# Answer
> 2 votes
# Charcoal, 29 bytes

```
≔⁰θＦＮ«≦⊕θＷ›²ＬΦθ⁼θ×λΣ⍘λ²≦⊕θ»Ｉθ

```

Try it online! Link is to verbose version of code. Outputs the `n`th element of the sequence. Explanation:

```
≔⁰θ

```

Start the accumulator at `0`.

```
ＦＮ«

```

Find `n` elements of the sequence.

```
≦⊕θ

```

Increment the accumulator.

```
Ｗ›²ＬΦθ⁼θ×λΣ⍘λ²

```

While the number of integers whose base 2 sum multiple equals the accumulator is less than 2, ...

```
≦⊕θ

```

... increment the accumulator.

```
»Ｉθ

```

Output the accumulator.

# Answer
> 2 votes
# Red, ~~140~~ 136 bytes

```
func[n][i: m: 1 until[d: 0 repeat k i: i + 1[p: k b: 0
until[b: p % 2 * k + b(p: p / 2)= 0]if b = i[d: d + 1]]if d > 1[m: m + 1]n < m]i]

```

Try it online!

Returns the \\$n\\$th element of the sequence.

Since the above code is really slow, I decided to write a faster function:

# Faster alternative, 168 bytes

```
func[n][r:[]m: copy#()i: 0 until[p: i: i + 1 b: 0
until[b: p % 2 * i + b(p: to 1 p / 2)= 0]either m/:b[r:
union r to[]b][m/:b: 1](length? r)=(2 * n)]take/part sort r n]

```

Try it online!

# Answer
> 2 votes
# JavaScript (V8), 66 bytes

```
for(d=o=[];;o[d]&&print(d))o[p=(h=n=>n&&h(n&n-1)+d)(++d)]=o[p]+1|0

```

Try it online!

# Answer
> 2 votes
# Ruby, 55 bytes

```
loop{p$.if(1..$.+=1).count{|y|y*y.digits(2).sum==$.}>1}

```

Try it online!

# Answer
> 2 votes
# , ~~78~~ 76 bytes

*Edit: -2 bytes thanks to Kirill L.*

```
repeat{T=T+1;s=0;for(n in 1:T)s=s+(n*sum(n%/%2^(0:n)%%2)==T);if(s>1)show(T)}

```

Try it online!

# Answer
> 2 votes
# Clojure, ~~81~~ 78 bytes

```
#(for[i(range):when(second(for[j(range i):when(=(*(Long/bitCount j)j)i)]j))]i)

```

Try it online!

Returns the infinite sequence.

# Answer
> 1 votes
# Japt, ~~18~~ 16 bytes

```
Èò_*¤è1Ãè¥X z}jU

```

Try it

Thanks to @Galen Ivanov for spotting an error which once fixed saved me 1 Byte!

```
È ... }jU  - first input U elements to return a truthy value when passed trough : f(XYZ)
ò_   >  range[0..X] trough f(Z)
*      * multiply Z by
¤è1Ã   * convert to binary string an count '1's
è¥X  > is number of elements == X
z    > divided by 2 not 0 ?

```

# Answer
> 0 votes
# 05AB1E, 12 bytes

```
∞ʒLDb1ö*y¢2@

```

Outputs the infinite sequence.

Try it online.

**Explanation:**

```
∞            # Push an infinite positive list: [1,2,3,...]
 ʒ           # Filter each value `y` by:
  L          #  Pop and create a list in the range [1,`y`]
   D         #  Duplicate this list
    b        #  Convert each inner value to a binary-String
     1ö      #  Sum the digits of each inner binary-String (by converting it to base-1)
       *     #  Multiply each binary-sum to its [1,`y`] value of the duplicated list
        y¢   #  Count how many times `y` occurs in this list
          2@ #  And check whether this count is larger than or equal to 2
             # (after which the filtered infinite list is output implicitly as result)

```

---
Tags: code-golf, math, sequence, number-theory, binary
---


# Question
Title: Phibonacci - Relation between Phi and Fibonacci
You want to see how quickly the ratio of two consecutive Fibonacci numbers converges on φ.

Phi, known by the nickname "the golden ratio" and written as \\$φ\\$, is an irrational number, almost as popular as π and e. The exact value of \\$φ\\$ is \\$\frac {1 + \sqrt 5} 2 = 1.618...\\$

The Fibonacci sequence is a recursive series of integers calculated by

$$F\_n = F\_{n-1} + F\_{n-2} \\ F\_0 = 0 \\ F\_1 = 1$$

Calculate \\$φ\\$'s value and the ratio \\$\frac {F\_n} {F\_{n-1}}\\$. How closely does \\$φ\\$ match the ratio?

## Examples

\\$n = 2\\$, ratio: \\$\frac 1 1 = 1.000\\$, compared to \\$1.618...\\$, 0 decimal spots match

\\$n = 5\\$, ratio: \\$\frac 5 3 = 1.666...\\$, compared to \\$1.618...\\$, 1 decimal spot matches

### Input

1 integer \\$n\\$ to calculate \\$\frac{F\_n}{F\_{n-1}}\\$

\\$ n \>= 5\\$

### Output

1 integer \\$x\\$, indicating the number of decimal places that match the value of \\$φ\\$

It is acceptable that the program only works accurately until the float precision limit of the language.

### Test Cases

```
Input -> Output

5 -> 1
10 -> 2
12 -> 2
15 -> 5
20 -> 7
23 -> 7
25 -> 9
50 -> 18
100 -> 39

```

### Tips

Do not round the ratio of \\$\frac{F\_n}{F\_{n-1}}\\$

Rounding will give you errors.

Let's look at \\$n = 5\\$ again.

\\$1.666...\\$ rounds to \\$1.7\\$ and \\$1.618...\\$ rounds to \\$1.6\\$, so 0 is the wrong answer.

### Useful information and math.

The limit of the ratios of the consecutive Fibonacci terms as \\$n\\$ tends to infinity is the golden number \\$φ\\$. The inverse of this ratio is \\$\frac 1 φ\\$ which equals to \\$φ−1\\$.

\\$\frac 1 φ = φ -1 \\$

\\$ \lim\_{n \to \infty} \frac{F\_n}{F\_{n-1}} = φ\\$

## Winning criterion

Code Golf.

# Answer
> 8 votes
# JavaScript (ES7),  ~~77 75 69~~  67 bytes

```
n=>(g=p=>--n>1?g(q,q+=p):(1+5**.5)/2*(m*=10)^q/p*m?0:1+g(p))(q=m=1)

```

Try it online!

### Commented

```
n => (            // main function, taking n
  g = p =>        // g is a recursive function taking p which, along with q,
                  // is used to compute the Fibonacci sequence
  --n > 1 ?       // decrement n; if it's still greater than 1:
    g(q, q += p)  //   do a recursive call with (p, q) = (q, q + p)
  :               // else:
    (1 + 5 ** .5) //   compute the golden ratio
    / 2           //
    * (m *= 10)   //   multiply m by 10 and multiply the golden ratio by m
    ^             //   xor (forces the decimal places to be discarded)
    q / p         //   compute q / p (last Fibonacci term / penultimate one)
    * m           //   multiply by m
    ?             //   if the above values are not equal:
      0           //     stop
    :             //   else:
      1 + g(p)    //     increment the final result and do a recursive call
)(q = m = 1)      // initial call to g with p = q = m = 1

```

# Answer
> 5 votes
# APL (Dyalog Extended), ~~37~~ 32 bytes

Full program, assumes `⎕IO←0`.

-5 bytes by not using `dfns.fibonacci`.

```
0⍳⍨2↓=⌿↑⍕¨(÷/(+/,⊃)⍣⎕⍳2),2÷⍨1+√5

```

Try it online!

`(+/,⊃)⍣⎕⍳2` calculates adjacent fibonacci pairs. Starting with `0 1 ≡ ⍳2`, iterate input () times: pair the sum of both values `+/` with the first value .

```
2÷⍨1+√5            ⍝ Phi
,                  ⍝ paired with
÷/(+/,⊃)⍣⎕⍳2       ⍝ fib(n) ÷ fib(n-1)
↑⍕¨                ⍝ format both numbers as strings and arrange in character matrix
=⌿                 ⍝ reduce each column by equality
2↓                 ⍝ remove the first two values (first digit and decimal point)
0⍳⍨                ⍝ get the index of 0 in this list
                   ⍝ this is the first index where Phi and fib(n-0) ÷ fib(n-1) differ

```

# Answer
> 5 votes
# Haskell, ~~76~~ 75 bytes

```
g n=last[i|i<-[1..n],i?n==i?99]
e?n=floor$10^e*f!!n/f!!(n-1)
f=0:scanl(+)1f

```

Try it online!

The relevant function is `g`, which takes `n` as input and returns the number of matching decimal digits between \\$\varphi\\$ and \\$F\_n/F\_{n-1}\\$. It probably won't work if the answer is larger than `15` because that's the maximum precision allowed by `Double`s.

## How?

`f=0:scanl(+)1f` is the standard Haskell definition of the Fibonacci numbers.

`e?n=floor$10^e*f!!n/f!!(n-1)` is a function `(?)` which computes $$ \left\lfloor10^e\cdot\frac{F\_n}{F\_{n-1}}\right\rfloor. $$

`g n=last[i|i<-[1..n],i?n==i?99]` finds the largest exponent `i` such that $$ \left\lfloor10^i\cdot\frac{F\_n}{F\_{n-1}}\right\rfloor=\left\lfloor 10^i\varphi\right\rfloor. $$ Note that \\$\varphi\\$ is computed as \\$F\_{99}/F\_{98}\\$ to save bytes, since the error is far beyond the accuracy of `Double`s. Also, the fact that the answer will always be smaller than `n` is exploited.

# Answer
> 4 votes
# Jelly, 17 bytes

```
,’ÆḞ÷/Ṿ=ØpṾ¤ŒɠḢ_2

```

Try it online!

Probably can be improved.

## Explanation

```
,’ÆḞ÷/Ṿ=ØpṾ¤ŒɠḢ_2   Main monadic link
,                   Pair with
 ’                    n-1
  ÆḞ                Get the Fibonacci numbers
     /              Reduce by
    ÷                 division
      Ṿ             Convert to string
       =            Equals [vectorized]
           ¤         (
        Øp            Phi
          Ṿ           Convert to string
           ¤         )
            Œɠ      Run lengths
              Ḣ     First element
               _    Subtract
                2     2

```

# Answer
> 3 votes
# Desmos, ~~169~~ ~~113~~ ~~107~~ ~~98~~ ~~97~~ ~~95~~ 87 bytes

```
pp-p~1
F(n)=p^n-(1-p)^n
h(k)=floor(10^{[1...n]}k)
f(n)=\{h(p)=h(F(n)/F(n-1)),0\}.\total

```

Try It On Desmos!

Try It On Desmos! - Prettified

*Finally managed to get it under ~~100~~ 90 bytes after all this time!*

*I don't know why I keep coming back to this answer, but every time I do, I always find a way to golf it even further...*

Test the code on function \\$f(n)\\$. It only works up to around \\$n=25\\$, though, because of float precision errors. Uses the fact that the output has to be smaller than \\$n\\$.

(The `f(n)=\{h(p)=h(F(n)/F(n-1)),0\}.\total` equation does not render properly in Desmos, in case you are wondering. It still works though.)

### Explanation:

`pp-p~1`: Sets `p` to be the golden ratio.

`F(n)=p^n-(1-p)^n`: \\$F(n)\\$ is Binet's formula for the \\$n\\$th Fibonacci number, but with the \\$\sqrt5\\$ denominator taken out, because it gets cancelled out anyways in \\$\frac{F(n)}{F(n-1)}\\$.

`h(k)=floor(10^{[1...n]}k)`: The \\$h(k)\\$ function creates a list of length \\$n\\$. It then computes \\$\left\lfloor10^ik\right\rfloor\\$ for each element, where \\$i\\$ is the index(1-based). Also, the \\$n\\$ in `[1...n]` is referring to the argument passed into \\$f(n)\\$(which is the next equation). For example, \\$h(1.56789)\\$ with \\$n=5\\$ returns the list \\$\[15,156,1567,15678,156789\]\\$.

`f(n)=\{h(p)=h(F(n)/F(n-1)),0\}.\total`: This function \\$f(n)\\$ essentially compares each digit of \\$p\\$ and \\$\frac{F(n)}{F(n-1)}\\$ under the \\$h\\$ function. If you look at the \\$h\\$ function, you will see that at any index \\$1\le i\le n\\$, it is actually comparing every digit up to the \\$i\\$'th decimal place. For example, let's say you were comparing \\$1.56789\\$ and \\$1.56889\\$, with \\$n=5\\$. \\$h(1.56789)=\[15,156,1567,15678,156789\]\\$, and \\$h(1.56889)=\[15,156,1568,15688,156889\]\\$.
From this, you can tell that the first \\$2\\$ elements(\\$15\\$ and \\$156\\$) of each of the lists are the same, but once you get to the digit that is different, the rest of the elements are not equal.
With this information, we can then combine the two lists into one, by doing the following: If the element at index \\$1\le i\le n\\$ in each list are the same, then the \\$i\\$'th element of the new list is \\$1\\$. Otherwise, it is \\$0\\$. (This is what `\{h(p)=h(F(n)/F(n-1)),0\}` does)
We can then simply take the sum of this new list to obtain the answer.

# Answer
> 2 votes
# JavaScript, ~~97~~ 89 bytes

```
n=>[...''+(f=n=>n<2?n:f(n-1)+f(n-2))(n)/f(n-1)].findIndex((e,i)=>`${.5+5**.5/2}`[i]!=e)-2
```

You have got to be kidding me. Not the best answer definitely but uses a different approach.

Also, try it online.

*8 bytes were shaved off the program thanks to suggestions from the OP as well as a rule change.*

# Answer
> 2 votes
# Python 3, ~~120~~ ~~102~~ 88 bytes

Saved a whopping ~~18~~ 32 bytes thanks to ovs!!!

```
f=lambda n,r=1,a=0,b=1:n>1and f(n-1,r,b,a+b)or-((1+5**.5)*r//2!=b*r//a or~f(n,r*10,a,b))

```

Try it online!

# Answer
> 1 votes
# Julia 0.7, ~~68~~ 65 bytes

```
!n=φ^n-(1-φ)^n
>(n,x=1)=!n/!(n-1)*10^x÷1!=φ*10^x÷1?x-1:n>x+1

```

Try it online!

Fibonacci numbers are calculated using Binet's formula dropping the constant \\$\sqrt5\\$ term in the denominator since we are interested in ratios anyway.

Thanks to MarcMush for -3 bytes.

# Answer
> 0 votes
# Charcoal, 39 bytes

```
ＮθＦ²⊞υιＦ⊖θ⊞υΣ…⮌υ²Ｉ⊖⊖⌕ＥＩ∕⊟υ⊟υ¬⁻ι§Ｉ⊘⊕₂⁵κ⁰

```

Try it online! Only works up to `n=40` due to floating-point rounding. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆ²⊞υιＦ⊖θ⊞υΣ…⮌υ²

```

Calculate the first `n` Fibonacci numbers.

```
Ｉ⊖⊖⌕ＥＩ∕⊟υ⊟υ¬⁻ι§Ｉ⊘⊕₂⁵κ⁰

```

Divide the last two and compare the string representation with that of φ.

87 bytes for arbitrary precision:

```
ＮθＦ²⊞υιＦ⊖θ⊞υΣ…⮌υ²≦Ｘχθ≔⁰η≔⁰ζＦ↨×⁵×θθ⁴«≔⁺×ζ⁴ιζ≦⊗η¿›ζ⊗η«≧⁻⊕⊗ηζ≦⊕η»»Ｉ⊖⌕ＥＩ÷×θ⊟υ⊟υ¬⁻ι§Ｉ÷⁺ηθ²κ⁰

```

Try it online! Link is to verbose version of code. Explanation: Uses @Delfad0r's observation that the result is always less than `n` so that you need only compute `n` decimal places.

```
Ｎθ

```

Input `n`.

```
Ｆ²⊞υιＦ⊖θ⊞υΣ…⮌υ²

```

Calculate the first `n` Fibonacci numbers.

```
≦Ｘχθ

```

Compute `10ⁿ`.

```
≔⁰η≔⁰ζＦ↨×⁵×θθ⁴«≔⁺×ζ⁴ιζ≦⊗η¿›ζ⊗η«≧⁻⊕⊗ηζ≦⊕η»»

```

Calculate `⌊√5·10²ⁿ⌋` using the method from my answer to Shift right by half a bit.

```
Ｉ⊖⌕ＥＩ÷×θ⊟υ⊟υ¬⁻ι§Ｉ÷⁺ηθ²κ⁰

```

Calculate the Fibonacci ratio multiplied by `10ⁿ` and compare it with the digits of `φ·10ⁿ` calculated from the above value.

# Answer
> 0 votes
# 05AB1E, 17 bytes

```
3LÍ+ÅfRü/`ø€ËÅγнÍ

```

Try it online!

```
3L    push the list [1,2,3]
Í     subtract 2, [-1,0,1]
+     add to the implicit input, [9, 10, 11]
Åf    take the nth Fibonacci number, [34, 55, 89]
R     reverse, [89, 55, 34]
ü/    take the division of each pair, [1.6181818181818182, 1.6176470588235294]
`     dump to stack
ø     zip, ["11", "..", "66", "11", "87", "16", "84", "17", "80", "15", "88", "18", "82", "13", "85", "12", "89", "24"]
€Ë    map to equal, [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
Åγ    run length encode, [4, 6, 1, 7]
нÍ    head - 2, 2

```

# Answer
> 0 votes
# , 100 bytes

```
h=function(n,m=1,l=0,p=.5+5^.5/2)`if`(n>1,h(n-1,m+l,m),{r=m/l
while(r%/%10^-T==p%/%10^-T)T=T+1
T-1})

```

Try it online!

Gets the ratio of the `n`th and `n-1`th fibonacci numbers using the recursive function:
`g=function(n,m=1,l=0)`if`(n,g(n-1,m+l,m),m/l)`

Then calculates the number of digits of the `r`atio that are shared with `p`hi by comparing successive integer divisions by negative powers of 10:
`while(r%/%10^-T==p%/%10^-T)T=T+1`
(so `T` ends-up with the number of shared digits +1)

# Answer
> 0 votes
# MathGolf, 21 bytes

```
f∩∩k(f/░▒φ░▒^╞╞mÅ▀£2=

```

Try it online.

**Explanation:**

```
f          # Get the n'th Fibonacci number using the (implicit) input-integer `n`
 ∩∩        # Convert it to a float (by changing `F(n)` to `1/1/F(n)`..)
   k       # Push the input-integer again
    (      # Decrease it by 1
     f     # Get the n-1'th Fibonacci number as well
      /    # Divide the F(n) by F(n-1)
       ░▒  # Convert it to a string, and then a list of characters
           # (float directly to character-list isn't possible yet unfortunately)
φ          # Push the golden ratio constant (1.618033988749895)
 ░▒        # And convert it to a list of characters as well
   ^       # Zip the two lists together to create pairs
    ╞╞     # Remove the first two pairs (leading "1.")
m          # Map over each remaining pair,
 Å         # using the following 2 commands:
  ▀        #  Uniquify the pair
   £       #  And pop and push its length
    2=     # Then get the first (0-based) index of a 2 in this list
           # (after which the entire stack is output implicitly as result)

```

The `/░▒φ░▒^` could alternatively be `/░φ░^2/` for the same byte-count, where the zip will create a single string and we split it into pairs with `2/`.

---
Tags: code-golf, sequence, fibonacci
---


title: Pyramid Schemes

text:
# Question
Title: Pyramid Schemes
Mayan pyramids were (and are) an important part of ancient architecture, that were generally used for religious purposes.

They were usually step pyramids, but the steps on each were too steep to climb. Priests would climb to the tops of them via alternative staircases to perform ceremonies. The pyramids were also used as landmarks because of their height, and sometimes even used as burial sites for high ranking officials.

---

# The Challenge

Write a program that can print out a pyramid schematic based on user specifications (see below).

---

# Requirements

* Take an input of two space-separated variables.
* Input must be accepted through STDIN (or closest alternative).
* Output must be through STDOUT (or closest alternative).

---

# Input

* Height as any positive integer. This is used as the base level's width (in blocks). Each succeeding level of the pyramid has the width `n - 1` where `n` is the previous floor's width (in blocks).
* Block size which will be 1 or any odd, positive integer ≤ (less than) 10.

---

# Blocks

The given block size determines the width (and height) of each individual piece. Essentially, there are `i^2` spaces inside the visible box where `i` is the block size.

A 1x1 block would look like this:

```
+++
| |
+++

```

While a 5x5 block would look like this:

```
+++++++
|     |
|     |
|     |
|     |
|     |
+++++++

```

---

# Horizontally Adjacent Blocks

Horizontally side-by-side blocks *must* have their middle walls merged into one.

You *must* have this:

```
+++++
| | |
+++++

```

Instead of something like this:

```
++++++
| || |
++++++

```

---

# Vertically Adjacent Blocks (-5% bonus)

Vertically side-by-side blocks have a special exception: the middle wall can be merged into one.

So, instead of 1x1 blocks looking like this:

```
 +++
 | |
 +++
+++++
| | |
+++++

```

They *could* look like this:

```
 +++
 | |
+++++
| | |
+++++

```

---

# Examples

```
Input: 3 1

Output:

  +++
  | |
  +++
 +++++
 | | |
 +++++
+++++++
| | | |
+++++++

OR

  +++
  | |
 +++++
 | | |
+++++++
| | | |
+++++++

Input: 2 3

Output:

  +++++
  |   |
  |   |
  |   |
  +++++
+++++++++
|   |   |
|   |   |
|   |   |
+++++++++

OR

  +++++
  |   |
  |   |
  |   |
+++++++++
|   |   |
|   |   |
|   |   |
+++++++++

```

---

# Scoreboard

To be ranked on the scoreboard, put your answer in this format:

```
# Language, Score

```

Or if you get the bonus -5%:

```
# Language, Score (Bytes - 5%)

```

```
function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=57939,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```

```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2> <table class="score-table"> <thead><tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead><tbody id="scores"></tbody> </table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```

# Answer
# Pyth, 45 (47 bytes - 5%)

```
AmvdczdVGjm.[Jh*GhHj*H?d\ \+*+2N?d\|\+\ hH;*J\+

```

Try it out here.

```
                                                   Implicit: z=input(), d=' '
    czd                                            Split input on spaces
 mvd                                               Evaluate each part of the above (convert to int)
A                                                  Store the pair in G,H
             Jh*GhH                                J = 1+(G*(H+1))
       VG                                          For N in [0 to G-1]:
          m                             hH;          Map d in [0 to H] to:
                                ?d\|\+                 Get '|' or '+' (vertical edges or corners)
                            *+2N                       Repeat the above (N+2) times
                      ?d\ \+                           Get ' ' or '+' (block centre or horizontal edge)
                    *H                                 Repeat the above H times
                   j                                   Join (|/+) by (   /+++)
           .[J                        \                Centrally pad the above to width J using spaces
         j                                           Join on newlines, implicit print
                                           *J\+    Get J '+'s, implicit print

```
> 1 votes

# Answer
# JavaScript (ES6), 161 (169-5%) ~~166 (174-5%)~~

Using template strings, the 2 newlines are significant and counted.

Test running the snippet below in an EcmaScript 6 browser. Firefox ok, not Chrome because it lacks support for destructuring assignment.

Code explained after the snippet.

```
/*Test: redefine console.log*/ console.log=x=>O.innerHTML+=x+'\n';

for([h,b]=prompt().split` `,g='+'[R='repeat'](-~b),f=' '[R](b),n=o='';h--;o+=e+(d=g[R](++n)+`+
`)+f.replace(/./g,e+('|'+f)[R](n)+`|
`))e=' '[R](h*-~b/2);console.log(o+d)
```

```
<pre id=O></pre>
```

**Less Golfed**

```
[h, b] = prompt().split` `; // get the space separated input values
c = -~b; // Add 1 to b. As b is of string type b+1 would be a string concatenation
g = '+'.repeat(c); // top border
f = ' '.repeat(b); // inner blank row
o = ''; // initialize output string
for(n = 0; h > 0; --h) // loop on height
{
   ++n;
   e = ' '.repeat(h*c/2); // blanks for offset from left margins
   d = g.repeat(n) + `+\n`; // top border repeated, then right end and newline
   // the block body is squared, there are as many rows as columns inside
   // so I can build the right number of rows replacing the chars in a single row
   o += e + d + f.replace(/./g, e + ('|'+f).repeat(n)+`|\n`)
}
o += d // add last top border as bottom
console.log(o)

```
> 11 votes

# Answer
# Ruby, 124 (130 - 5%)

```
n=(g=gets).to_i
b=g[-2].to_i+1
a=(0..n*b-1).map{|i|[?+*(i/b*b+b+1),(?|+' '*(b-1))*(i/b+1)+?|][i%b<=>0].center(n*b+1)}
puts a,a[-b]

```

With comments

```
n=(g=gets).to_i                                  #get input and interpret as a number for pyramid height (everything after the space is ignored)
b=g[-2].to_i+1                                   #the single-character block size is the second last character (just before the newline.) Add 1 to give the pitch between squares.
a=(0..n*b-1).map{|i|                             #run through all lines except the last one
[?+*(i/b*b+b+1),                                 #calculate number of + symbols
(?|+' '*(b-1))*(i/b+1)+?|]                       #or alternatively, pattern '|    |'
     [i%b<=>0]                                   #check if i%b is zero or positive to decide which to print
     .center(n*b+1)}                             #centre the text. It will be mapped to the array a.
puts a,a[-b]                                     #a contains the pyramid, minus its last line. Print it, and add the last line

```
> 9 votes

# Answer
## Python 2, 117 (123 bytes)

```
h,n=map(int,raw_input().split())
p,v='+|'
while h:p+='+'*-~n;v+=' '*n+'|';h-=1;l=~n/-2*h*' ';print l+p+('\n'+l+v)*n
print p

```

The idea is to build up the bricks' top `p` as `+++++++++` and side `v` as `| | |`. The top starts as `+` and is augmented by `n+1` `+`'s each layer. The side starts as `|` and is augmented by `n` spaces and a `|`. Each layer, we augment the tops and sides, then print one top and `n` sides.

To center them, we first print an indent `l`. It consists of a number of spaces that scales with the current height `h`. To update it, we decrementing the height variable `h` until it hits `0`, after which the current layer is flush against the left edge of the screen. We print the top once more to make the bottom layer, and we're done.
> 2 votes

# Answer
# Python 2, 200 (210 - 5%)

```
a,b=map(int,raw_input().split());c=0;a+=1;i=a*b+a-b;e=[i*'+']
while a-1:
 v=(('|'+' '*b)*a).rstrip();p=' '*((i-len(v))/2);a-=1;c+=1
 for u in range(b):e.insert(0,p+v)
 e.insert(0,p+'+'*len(v))
print'\n'.join(e)

```

I used string multiplication and stripped extra spaces.
> 0 votes

# Answer
# Vyxal `o`, 44 bytes (46 - 5%)

```
(n£¹n-‹⁰½⌈*ð*:\+⁰›n›*›*+:→x,⁰(:₴\|:⁰꘍¥›*p,))←x

```

Try it Online!
> 0 votes

# Answer
# 05AB1E, ~~27~~ 26 bytes

Takes the height and then block size on seperate lines. 30 bytes if the input format is strict.

```
Lε'|²úRy²>*>©∍²и®'+×.ø}˜.c

```

Try it online!

```
L                         # push range [1 .. h]
 ε                     }  # for y in [1 .. h]:
  '|                     '# push "|"
    ²úR                   # pad with w spaces in the back
       ²>*>               # line length: (w+1)*y+1
           ©              # store the line length in the register
            ∍             # extend the string to this length
             ²и           # push a list with w copies of the string
               ®'+×      '# push a string of "+"*line length
                   .ø     # surround the list with this string

˜                         # flatten into a list of strings
 .c                       # centralize

```
> 0 votes

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


title: Just Twice Is Nice

text:
# Question
Title: Just Twice Is Nice
Let's have string multiplication to take a string and a positive number and concatenate that string that many times. In Haskell:

```
0 * s = ""
n * s = s ++ ((n - 1) * s)

```

Your task is to write a program that outputs a number \\$n \> 0\\$. When you double your program (with the described procedure) the new program should output \\$2n\\$. When your program is tripled or quadrupled it should once again output the original \\$n\\$.

This is so your answers will be scored in bytes with fewer bytes being better.

---

Related, Related.

# Answer
> 6 votes
# Python 2, 9 bytes

Outputs via exit code. Full credit goes to Anders Kaseorg for this answer to *I double the source, you double the output!*.

```
';exit(2)

```

Try it online! | Doubled | Tripled | Quadrupled

Regularly, this raises a Syntax Error because the string is not closed properly and exists with exit code **1**, then, when doubled, it becomes `';exit(2)';exit(2)` which simply exits with code **2** because the string literal is now quoted properly and has no effect at all, and when repeated any other arbitrary number of times, it raises Syntax Errors.

# Answer
> 5 votes
# , ~~27~~ 25 bytes

```
1+!1-length(readLines())

```

Try it online!

Inspired by rturnbull's answer to Third time the charm, but the simplicity of the check makes it shorter.

Doubled | Tripled | Quadrupled

### Why this works:

`readLines()` will actually reads the source file itself rather than `stdin`. Hence, adding lines just increments the `length()` of the vector returned by `readLines()`. Therefore, we compute `!(1-length())` to obtain `1` whenever `length()==1` and `0` when `length()!=1`, adding one to have the desired effect.

# Answer
> 3 votes
# 05AB1E, ~~7~~ ~~6~~ 5 bytes, `n=3`

```
₆¾Θè¼

```

-1 byte thanks to *@CommandMaster*.

Try it online; try it doubled; try it tripled; try it quadrupled.

**Explanation:**

```
₆      # Push 36
 ¾     # Push the counter_variable (0 by default)
  Θ    # 05AB1E-style truthify: ==1 (results in 1 if 1; 0 for everything else)
   è   # Use that to index into the 36
    ¼  # Increase the counter_variable by 1
       # (and output the indexed digit implicitly as result)

```

# Answer
> 2 votes
# Runic Enchantments, 29 bytes

```
^w '\
/1@ 3
/ ~!4
2'51\w
/yyy

```

Try it online!

Slight alteration from the Third Times A Charm entry, using Jo King's compressed version and swapping the two reflection locations.

Twice

Thrice

And frice for good measure.

# Answer
> 2 votes
# Klein 000, 6 bytes

```
\1+@
\

```

Try it online!

## Explanation

The idea here is pretty simple, the first 2 copies require the ip to move off the edge of the program but the third does not, that way adding anything extra after the third doesn't change anything.

The first program reflects off of both edges the

```
\
\

```

At the begining is just a fancy noop. So we just run `1+@`.

For the two copies this gets interrupted

```
\1+@
\\1+@
\

```

We hit both `1`s and a `+` to get `2`.

On the three we interrupt the path even further

```
\1+@
\\1+@
\\1+@
\

```

At this point it might not be the clearest, but the ip bounces around in the mirrors a bit before it hits runs the 3rd line.

This is what it runs

```
\
\\
 \1+@

```

Since this doesn't go off an edge further additions don't make any change to the program.

# Answer
> 1 votes
# Charcoal, 10 bytes

```
ＰＩ⊕⁼²Ｌ⊞Ｏυω

```

Try it online! Based on my answer to I double the source, you double the output! but compares the length to 2. Try it doubled. Try it tripled. Try it quadrupled. In verbose syntax this is `Multiprint(Cast(Incremented(Equals(2, Length(PushOperator(u, w)))))));`.

# Answer
> 1 votes
# MATL, 9 bytes

```
vxHQXH4=Q

```

Uses *n* = 1.

Try it online! Original, doubled, tripled, quadrupled.

### Explanation

This uses clipboard H to store state information. Function `H` pastes the clipboard contents onto the stack. Function `XH` copies the top of the stack into the clipboard. The clipboard initially contains the number `2`.

Each time the snippet `vxHQXH4=Q` is run it does the following. The stack contents, if any, are deleted (`vx`). The clipboard contents are pushed (`H`) and incremented (`Q`), and the result is copied back into the clipboard (`XH`). This gives `4` the second time, and only that time.

The number in the stack is tested for equality with `4` (`4=`) and incremented (`Q`). This gives `2` for `4` (second time), and `1` otherwise (any other time).

# Answer
> 1 votes
# Brain-Flak, 36 bytes

```
(({}<>{})[()]<>)(()(){[()](<{}>)}{})

```

Try it online!

Uses a counter off stack. Each time we run the counter is incremented by the result of the last run. If the counter is equal to exactly 1 (which it is when the program is doubled) then we push 2, otherwise 1 is pushed.

The selection is done using a bit of a weird if statement. It is 2 normally but if the if is entered (which it is when the count is not 1) we subtract 1 from it.

# Answer
> 1 votes
# Bash, 8 bytes

This is a rip-off of the Python 2 answer. Output is via exit code.

Unlike the Python 2 answer, this uses \\$n=2\\$.

```
";exit 4

```

Try it online! Try it online (doubled)! Try it online (tripled)! Try it online (quadrupled)!

# Answer
> 1 votes
# Jelly, ~~6~~ 4 bytes (n=1)

```
»ɼḂ‘

```

Try it online!

## Explanation

```
Initial value = 0
Initial register value = 0
 ɼ     Set the register and current value to
»        maximum of the register and current value
  Ḃ    Parity
   ‘   Increment

```

# Answer
> 0 votes
# PowerShell, 24 bytes

```
';$host.setshouldexit(2)

```

Try it online! | Doubled | Tripled | Quadrapled

Outputs through exit code, Shameless port of python answer ;-)

# Answer
> 0 votes
# Vyxal, 4 bytes (n=1)

```
∴:∷›

```

Try it Online!

Same approach as my Jelly answer, but much more aesthetic.

```
∴:∷›
∴    Pop a, b; push max(a,b)
 :   Duplicate
  ∷  Parity
   › Increment

```

# Answer
> 0 votes
# 05AB1E, 4 bytes (n=1)

```
.gΘ>

```

Try it online!

## Explanation

```
.gΘ>
.g   Push length of stack
  Θ  Equals 1?
   > Increment

```

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


title: Encode USB packets (part 2)

text:
# Question
Title: Encode USB packets (part 2)
*Inspired by this video by Ben Eater. This challenge forms a pair with Decode USB packets.*

The USB 2.0 protocol uses, at a low level, a line code called **non-return-to-zero** encoding (specifically, a variant called NRZI), in which a stream of bits is encoded into a stream of two electrical level states `J` and `K`. Encoding works as follows:

* Start with some initial state, which is either `J` or `K`
* For each bit to be encoded:
    + If the bit is a 0, switch the state from `J` to `K` or from `K` to `J`
    + If the bit is a 1, maintain the same state as before
    + and output that state

For this challenge, we will assume the encoding starts in state `J`.

However, it's not that simple: an additional process called **bit stuffing** takes place, which is designed to make it easier to detect if the signal has dropped out. After 6 consecutive `1`s are read, an extra meaningless `0` bit is processed to ensure the signal never stays in the same state (`J` or `K`) for too long.

The full USB specification is available here on the USB website, or mirrored (and easier to access) here, but I'd caution you before reading it because it's extremely long and the pertinent information is hard to pin down.

## Task

Given a non-empty binary string as input, encode the string using the USB implementation of NRZI described above, and output a string of `J`s or `K`s.

## Test-cases

```
Input              Output
=====================================
1                  J
0                  K
1000101            JKJKKJJ
00000000           KJKJKJKJ
11111111           JJJJJJKKK
001111100          KJJJJJJKJ
0011111100         KJJJJJJJKJK
00111111100        KJJJJJJJKKJK
0011111111111100   KJJJJJJJKKKKKKKJKJ
0011011000111001   KJJJKKKJKJJJJKJJ
01101000011101000111010001110000011100110011101000101111001011110111011101110111011101110010111001111001011011110111010101110100011101010110001001100101001011100110001101101111011011010010111101110111011000010111010001100011011010000011111101110110001111010110010001010001011101110011010001110111001110010101011101100111010110000110001101010001   KKKJJKJKJJJJKKJKJJJJKKJKJJJJKJKJKKKKJKKKJKKKKJJKJKKJJJJJKJJKKKKKJJJJKKKKJJJJKKKKJJJJKKKKJKKJJJJKJJJJJKJJKKKJJJJJKKKKJJKKJJJJKKJKJJJJKKJJKKKJKJJKJJJKJJKKJKKJJJJKJJJKJKKKJJJKKKKKJJJKKKJJKJJKKKKKJJJJKKKKJJJKJKJJKKKKJJKJKKKJKJJJKKKJJKJKJKKKKKKKJKKKKJJJKJKKKKKJJKKKJKKJKJJKKJKJJKKKKJJJJKJJJKKJKJJJJKKKKJKKKKJKKJJKKJJJJKKKJKKKKJJKKKJKJKKKJKJJJKKJJKJKK

```

## Rules

* The input should be a string or array of `1`s and `0`s or of `true`s and `false`s
* The output should be a string or array, with the two states `J` and `K` being represented by any two distinct values
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

# Answer
# JavaScript (ES6), 53 bytes

Expects a binary string. Returns an array of 0's and 1's.

```
s=>[...s.replace(/1{6}/g,'$&0')].map(q=c=>q^=c^!!++q)

```

Try it online!

### Commented

This is a rather straightforward implementation in two steps.

```
s =>           // s = input string

               // STEP 1 - Bit stuffing
               //
[...s.replace( // replace in s:
  /1{6}/g,     //   each group of six consecutive 1's
  '$&0'        //   with the same group with a trailing 0
)]             // split the resulting string

               // STEP 2 - NRZI encoding
               //
.map(q =       // initialize q to a zero'ish, non-numeric value
  c =>         // for each character c:
  q ^=         //   invert q if ...
    c ^        //     ... c is not equal to the result of
    !!++q      //     the test 'q is a number'
               //     (0 on the 1st iteration, 1 afterwards)
)              // end of map()

```
> 5 votes

# Answer
# Husk, 11 bytes

```
G=Jḋ126xḋ63

```

Try it online!

Input as array of `0`s and `1`s, output as array of `1`s (for state `J`) and `0`s (for state `K`): TIO header converts to `J`s and `K`s.

```
       x    # split input on
        ḋ63 # binary digits of 63 = [1,1,1,1,1,1]
  J         # then join back together using
   ḋ126     # binary digits of 126 = [1,1,1,1,1,1,0]
G=          # and scan from the left by equality

```
> 5 votes

# Answer
# Jelly, 12 bytes

```
7Ṭ¬©Ṗœṣ@j®⁼\

```

A monadic Link that accepts a list of integers (from \\$\[0,1\]\\$) and yields a list of integers (from \\$\[0,1\]\\$) where \\$0\\$ represents \\$K\\$.

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

### How?

```
7Ṭ¬©Ṗœṣ@j®⁼\ - Link: list of integers in [0..1], A
7            - seven
 Ṭ           - untruth -> [0,0,0,0,0,0,1]
  ¬          - logical NOT -> [1,1,1,1,1,1,0]
   ©         - copy to register
    Ṗ        - pop -> [1,1,1,1,1,1]
     œṣ@     - (A) split on sublists equal to (that)
         ®   - recall from register
        j    - (split list) join (register value)
           \ - cumulative reduce with:
          ⁼  -   (left) equals (right)?

```

---

11 if we could take input with `0` meaning *true* and `1` meaning *false* with `7Ṭ©Ṗœṣ@j®⁻\`.
> 4 votes

# Answer
# Jelly, 14 bytes

```
“?~‘Bœṣjƭƒ^¬¥\

```

Try it online!

-2 bytes thanks to Nick Kennedy

```
“?~‘Bœṣjƭƒ^¬¥\  Main Link; accepts a list of [0, 1] on the left
“?~‘            63, 126
    B           To binary ([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0])
         ƒ      Reduce starting with the input:
        ƭ       Tie; cycle
     œṣ         The first time, split on sublist ([1, 1, 1, 1, 1, 1])
       j        The second time, join on [1, 1, 1, 1, 1, 1, 0]
             \  Cumulative reduce
          ^¬¥   Each time, XOR, and then logical NOT

```
> 3 votes

# Answer
# convey, 31 bytes

Outputs `KJ` as `01`.

```
v|6
0"("=0
+*6!<}
""~,="
{ 5 1<

```

Try it online!

In the top left is a counter that gets incremented by the input 1s `+` and reset whenever it reaches 6 `|6` or the input has a 0 `*`. If it reaches 6, it also injects a 0 into the stream (the `("=0 6!<` part). Because the input stream would be faster (the 0 would get there 2 bits too late), we delay it by 5 ticks `~5`. On the bottom right is the current output bit that gets flipped on 0s with `=` and then copied into the output `=}`.
> 3 votes

# Answer
# , 59 bytes

```
function(x)cumsum(49-utf8ToInt(gsub('(1{6})','\\10',x)))%%2

```

Try it online!

Regex-based bit-stuffing ~~stolen from~~ inspired by pajonk's R answer to the paired usb-decoding challenge.

The state-switching is achieved here by determining whether the cumulative sum is odd or even.
> 3 votes

# Answer
# Vyxal, 16 bytes

```
\16*:0+V1$(nɽß¬…

```

Try it Online!

```
\16*             # Six ones
    :0+          # Duplicate and append a 0
       V         # Replace in input
        1$       # Starting with a one
          (      # Iterating through the string
             ß¬  # Flip if...
           nɽ    # It's a 1
               … # Print without popping

```

Returns 1 for J and 0 for K. Here's a version that does JKs.
> 3 votes

# Answer
## \<\>^v, 161 bytes

```
1±n"0"o"1"i0q.h"J"j"K"kJtv
v   v=ICc®NHn)N  v=N-?1¿H<
    >Q)7=v_qv    >`!     ~
 vcOn(Nq0<  v    >Ktv    T
v<          <>TJ=^Jtv    ^
>C         O=^      >    ^

```

#### Explanation

##### First line

```
1±n"0"o"1"i0q.h"J"j"K"kJtv

1                          Push 1 to stack
 ±                         Negate
  n                        Store in variable `n`
   "0"                     Push "0"
      o                    Store in variable `o`
       "1"                 Push "1"
          i                Store in variable `i`
           0               Push 0
            q              Store in variable `q`
             .             Read line from stdin
              h            Store in variable `h`
               "J"         Push "J"
                  j        Store in variable `j`
                   "K"     Push "K"
                      k    Store in variable `k`
                       J   Push value of variable `j` ("J")
                        t  Store in variable `t`
                         v Redirect instruction pointer down

```

The variables `i` and `o` store the values `"1"` and `"0"`", `j` and `k` store `"J"` and `"K"`. `h` contains the line read from stdin (1's and 0's). `q`, initialized to 0, will be used for bit stuffing. `n` is the "current character pointer".

##### The main loop

```
v   v=ICc®NHn)N  v=N-?1¿H< <-- loop starts here
    >Q)7=v_qv    >`!     ~
 vcOn(Nq0<  v    >Ktv    T
v<          <>TJ=^Jtv    ^
>C         O=^      >    ^
[start of loop]
<    Send instruction pointer leftward
H    Push value of variable `h` to stack
¿    Push length of top of stack
1    Push 1
?    Swap top two elements
-    Substract second element of stack to top of stack
N    Push value of variable `n`
=    If the top two elements of the stack (length of `h` - 1 and `n`) are equal (reached end of string)
    v    Send instruction pointer down
    >    Send instruction pointer right
    `    Print newline
    !    Exit
N    Push value of variable `n` (character index in string)
)    Increment top of stack (increment character index in string)
n    Pop and write to variable `n`
H    Push value of variable `h` (string that was previously read from stdin and that contains the 0's and 1's
N    Push value of variable `n`
®    Set top of stack to (second element of stack)[top of stack] (character read)
c    Write to variable `c` ("current")
C    Push value of variable `c` (variable write pops the stack)
I    Push value of variable `i` ("1")
=    If the top two elements of the stack (current character and "1") are equal
    v    Send instruction pointer down
    >    Send instruction pointer right
    Q    Push value of variable `q`
    )    Increment top of stack
    7    Push 7
    =    If the top two elements of the stack are equal (`q` and 7)
        v    Send the instruction pointer down
        <    Send the instruction pointer left
        0    Push 0
        q    Pop stack and write to variable `q`
        N    Push value of variable `n`
        (    Decrement top of stack
        n    Pop stack and write to variable `n`
        O    Push value of variable `o` ("0")
        c    Pop stack and write to variable `c` (current character)
        v    Send instruction pointer down
        <    Send instruction pointer left
        Go to [loop-continuation]
    Else
    _    Pop stack (remove the 7)
    q    Pop stack and write to variable `q`
    v    Send instruction pointer down
    v    Same as previous, only for readability
    <    Send instruction pointer left
    <    Same
    Go to [loop-continuation]
[loop-continuation]
Else
v.   Send instruction pointer down
v.   Same
>.   Send instruction pointer right
C.   Push value of variable `c` to stack (current character)
O.   Push value of variable `O` ("0")
=.   If the top two elements of the stack (current character and "0") are equal
    ^    Send instruction pointer up
    >.   Send instruction pointer right
    T.   Push to stack value of variable `t` (current state, J or K)
    J.   Push to stack value of variable `j` ("J")
    =    If the top two elements of the stack (current state and "J" are equal)
        ^.   Send instruction pointer up
        >.   Send instruction pointer left
        K.   Push value of variable `k` ("K")
        t.   Pop stack and write to variable `t`
        v.   Send instruction pointer down
        Continue at the [here] indicator
    Else
    J    Push value of variable `j` ("J")
    t.   Pop stack and write to variable `t`
    v.   Send instruction pointer down
    Continue at the [here] indicator
[here]
>.   Send instruction pointer right
^.   Send instruction pointer up
^.   Same
T.   Push value of variable `t` ("J" or "K")
~.   Print top of stack without newline
Go to [start of loop] indicator

```

That can be clarified to :

```
while has not reached end of string:
    increment character_index
    current_character = string[character_index]
    if current_character is a 1:
        increment one_count
        if one_count is 7:
            set one_count to zero
            decrement character_index
            current_character = 0
    if current_character is a 0:
        if state is J:
            state = K
        else:
            state = J
    print state
print newline
exit

```

run online - largest input

run online - enter input yourself
> 3 votes

# Answer
# Red, 79 bytes

```
func[x][p: 0 x: replace/all x"111111""1111110"forall x[prin p: 49 - x/1 xor p]]

```

Try it online!

Both input and output are strings of \\$1\\$s and \\$0\\$s. Output is done by printing. Despite the unwieldy string replacement, other ways to account for the extra zero bit tend to be even longer.
> 3 votes

# Answer
# Retina 0.8.2, ~~33~~ 32 bytes

```
1{6}
$&0
{+rT`d`JK`K.
1T`d`KJ`\d

```

Try it online! Link includes test cases. Explanation:

```
1{6}
$&0

```

Perform bit-stuffing.

```
{`

```

Make as many replacements as possible.

```
+rT`d`JK`K.

```

Change `0` after a `K` to `J` and `1` after a `K` to `K`. Change starting with the character after the last `K` (and working back, not that it matters), and keep replacing characters until there are no digits after a `K`.

```
1T`d`KJ`\d

```

The first remaining digit is not after a `K`, so change `0` to `K` and `1` to `J`.
> 2 votes

# Answer
# Charcoal, 24 bytes

```
≔⪫⪪Ｓ×1⁶⁺×1⁶0θ⭆θ§JK№…θ⊕κ0

```

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

```
≔⪫⪪Ｓ×1⁶⁺×1⁶0θ

```

Perform bit-stuffing.

```
⭆θ§JK№…θ⊕κ0

```

For each prefix of the string count the number of `0`s and output `K` if it is odd and `J` if it is even.
> 2 votes

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

```
0=\.'(t,$0)/(t:6#$1)\

```

Try it online!

Takes input as a string of `"1"`s and `"0"`s. Returns a list of `0`s (for `J`) and `1`s (for `K`).

* do a string replace of `"111111"` with `"1111110"`
    + `(t:6#$1)` store `"111111"` in variable `t`
    + `(t,$0)` append a `"0"` to the end of `t`, generating `"1111110"`
* `.'` convert each character to an integer
* `0=\` use a equals-scan, seeded with 0 (this does the non-return-to-zero part)
> 2 votes

# Answer
# C (gcc), ~~84~~ ~~80~~ 78 bytes

-6 thanks to @ceilingcat

```
x;c;a(char*p){for(c=0,x=1;*p;c>5&&a(L"10"+x))putchar(x^=*p<49),c=*p++/49*-~c;}

```

Try it online! Takes input as the characters `0` and `1`, outputs with bytes `0x01` for `J` and `0x00` for `K`.

For output as actual `J` and `K`, Try it online!

Decoder
> 2 votes

# Answer
# Haskell, 85 bytes

```
map("JK"!!).(0%)
j%(1:1:1:1:1:1:y)=j:j:j:j:j:j:j%(0:y)
j%(i:y)|k<-i^j*j^i=k:k%y
j%e=e

```

Try it online!
> 2 votes

---
Tags: code-golf, binary, encoding
---


title: Internal Truth Machine

text:
# Question
Title: Internal Truth Machine
It's a normal truth machine but instead of taking input, it uses the first character of the program. Thus, internal.

The 0 and 1 are plain characters, i.e. ASCII code 0x30 and 0x31 respectively.

Example: `0abcd` prints 0 and halts, and `1abcd` prints 1 infinitely. Then your submission is `abcd`, whose score is 4 bytes. The 0 or 1 (the first character of the program) is not counted towards your score.

Of course, you're not allowed to look inside the file itself. Like a quine.

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 198288; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
# Python 3, 29 bytes

```
 or~print(0)
while 1:print(1)

```

A full program, which if prefixed with `0` will print `0` then halt, exiting with an error, or if prefixed with `1` will print `1` forever.

**Try 0 online!**
**Try 1 online!**

The right of a logical `or` is only executed if the left is falsey (which `0` is, while `1` is not).

If the prefix is `0` the argument, `print(0)`, of bitwise-not, `~`, is evaluated - this has a side-effect of printing `0` and returns `None` which is an invalid argument for `~` causing an error which halts the program.

If the prefix is `1` the code `~print(0)` is not evaluated and the infinite loop of `while 1:print(1)` is reached.
> 35 votes

# Answer
## , 2 bytes

You know, duplicate the first character and apply while. Simple enough.

```
:w

```

## Explanation, applied the bits

```
1:  % The condition and the body is both 1
  w % While the condition 1 is true, output 1

```

## Explanation 2

```
0:  % The condition and the body is both 0
  w % This while does not get executed
    % The condition 0 gets returned & printed

```
> 19 votes

# Answer
# , 20 bytes

```
->a
while(print(a))0

```

0Try it online!

1Try it online!

Uses rightwards assignment `->`, which I now seem to use about once  month on this site (and never anywhere else).
> 9 votes

# Answer
# x86-16 machine code, IBM PC DOS, 11 bytes

**Binary:**

(`0` example)

```
00000000: 3002 ad8a d03c 30cd 2175 fcc3            0....<0.!u..

```

(`1` example)

```
00000000: 3102 ad8a d03c 30cd 2175 fcc3            1....<0.!u..

```

**Unassembled listing:**

```
?? 02       DB  ?, 2        ; first byte is '1' or '0', second byte is DOS write char fnc
AD          LODSW           ; load input from [SI] into AL, INT 21H function 2 in AH
8A D0       MOV  DL, AL     ; output to DL
3C 30       CMP  AL, '0'    ; is input 0?
        OUTPUT:
CD 21       INT  21H        ; write to console
75 FC       JNZ  OUTPUT     ; if not a '0', keep looping forever
C3          RET             ; return to DOS (only if it was a 0)

```

**Explanation:**

The first byte of the program is either a `'0'` or a `'1'`, and combined with a second byte of `2` (more on that later) decodes to a benign instruction of either `XOR [BP+SI], AL` or `XOR [BP+SI], AX`. In PC DOS, many registers are initialized to known values, so we know that `AX` is `0`, and `SI` is `100H` which is the first byte of the program. Whatever memory address `[BP+SI]` translates to, it simply XOR's `0` to it, doing nothing.

The `LODSW` instruction puts the input byte into the `AL` register and a `2` into the AH register, which is the DOS `INT 21H` API function number to write an ASCII char in `DL` to the console.

The input is compared and `ZF` (zero flag) is set "true" if input is a `0`. The char is written to the console and if `ZF` is not zero, it will loop indefinitely.

**Output of both variants:**
> 9 votes

# Answer
# Haskell, 32 bytes

```
!f=f 0
_!f=f 1*>0!f
main=0!print

```

I think this is the only answer posted so far where the first character (the digit) isn't the entry point.

Anyway, explanation: I'm creating an operator function called `!`, and defining it by cases. We enter the top case if the left operand matches the program's first digit, and the bottom case otherwise. The right operand is bound to `f` in both cases (and it happens to always be `print`). In the top case, we just print a 0. In the bottom case, we print a 1, and then recursively call ourself with the same operands. (We know the left operand will always be 0.) Finally, `main`, the entry point, calls our operator with `0` and `print`.

Try it online with 0! Try it online with 1!
> 7 votes

# Answer
# 05AB1E, 3 bytes

```
µ=0

```

Try `0µ=0` online!

Try `1µ=0` online!

Also 3 bytes:

```
i[,

```

Try `0i[,` online!

Try `1i[,` online!
> 6 votes

# Answer
# Jelly, 3 bytes

```
Ṅḷ¿

```

**Try 0 online!**
**Try 1 online!**

```
 Ṅḷ¿ - Main Link: no arguments
.    - set Left to 0 or 1
   ¿ - while...
  ḷ  - ...condition: Left
 Ṅ   - ...do: print and yield (Left)
     - implicit print (Left)

```
> 6 votes

# Answer
# Scratch 3.0, 10 blocks/80 bytes

As SB Syntax:

```
//1 or 0
repeat until<(n)=[0
say[1
end
say[0
define 0
set [n v]to[0
define 1
set[n v]to[1

```

It's more of a snippet than a program, but it works.

Try it on~~line~~ Scratch!
> 6 votes

# Answer
# \>\<\>,  ~~6~~  5 bytes

-1 thanks to Jo King!

```
:n?!;

```

**Try 0 online!**
**Try 1 online!**

### How?

Instruction pointer starts at the top left (i.e. 0 or 1) facing right. If the instruction pointer leaves the code it wraps around to the other side, continuing in the same direction.

```
X:n?!; -               X=0                X=1
X      - push X          {0}                {1}
 :     - duplicate       {0,0}              {1,1}
  n    - pop & print     {0,} "0"           {1} "1"
   ?   - pop & if...     {}                 {}
    !  - ...truthy:      skip & wrap to X
     ; - ...falsey:                         exit

```
> 6 votes

# Answer
# Labyrinth, 5 bytes

```
"
!"@

```

**Try 0 online!**
**Try 1 online!**

### How?

Instruction pointer starts at the top left (i.e. `0` or `1`) facing right, the stack starts as infinite zeros.

**0:**

```
0"
!"@

```

```
  - stack = {0,0,0,...} (infinite supply of zeros)
0 - multiply top of stack by 10 and add 0 {0,0,0,...}
  - 2 neighbours, 0 -> go forward
" - no-op {0,0,0,...}
  - 2 neighbours -> go forward
" - no-op {0,0,0,...}
  - 3 neighbours T-junction from stem, 0 -> turn around
" - no-op {0,0,0,...}
  - 2 neighbours -> go forward
0 - multiply top of stack by 10 and add 0 {0,0,0,...}
  - 2 neighbours -> go forward
! - pop top of stack, print as decimal "0" {0,0,0,...}
  - 2 neighbours -> go forward
" - no-op {0,0,0,...}
  - 3 neighbours T-junction from side, 0 -> go forward
@ - exit labyrinth

```

**1:**

```
1"
!"@

```

```
  - stack = {0,0,0,...} (infinite supply of zeros)
1 - multiply top of stack by 10 and add 1 {1,0,0,...}
  - 2 neighbours -> go forward
" - no-op {1,0,0,...}
  - 2 neighbours -> go forward
" - no-op {1,0,0,...}
  - 3 neighbours T-junction from stem, 1 -> turn right
! - pop top of stack, print as decimal "1" {0,0,0,...}
  - 2 neighbours -> go forward
1 - multiply top of stack by 10 and add 1 {1,0,0,...}
  - ...etc.

```
> 5 votes

# Answer
# Pyth, 65 63 56 bytes

Pyth's prefix operators don't really suit well to this challenge...

```
Ws@`$__import__("inspect").stack()[1][0].f_locals$_101
1

```

Edit 1: Saved 2 bytes by letting Pyth do the dictionary index, and using `h` instead of `@<py_code>0` because I remembered it exists.

Edit 2: Saved 7 bytes because @isaacg found an even sillier trick :)

Try it online!
> 4 votes

# Answer
# \>\<\>, ~~12~~ 10 bytes

```
:?vn;
 n:<

```

-2 bytes thanks to @JonathanAllan

## Answer History

```
 :?vn;
>:n:<

```

Try it online!

or

Try it with `1`

Try it with `0`

## Explained

Path visualiser is https://fishlanguage.com/

Gif converter is https://www.onlineconverter.com/video-to-gif
> 4 votes

# Answer
# APL (Dyalog Unicode), 8 bytesSBCS

```
{⍞←⍺}⍣≠1

```

0Try it online! 1Try it online!

Prints to stderr.

### How they work

```
0{⍞←⍺}⍣≠1
 {⍞←⍺}⍣≠   ⍝ Iterate {⍞←⍺} until (next value)≠(prev value) is true
 {⍞←⍺}     ⍝ First iteration: print and return left arg (0)
       ≠   ⍝ (next value)=0, (prev value)=1, so 0≠1 is true
           ⍝ Function terminates

1{⍞←⍺}⍣≠1
 {⍞←⍺}⍣≠   ⍝ Iterate {⍞←⍺} until (next value)≠(prev value) is true
 {⍞←⍺}     ⍝ First iteration: print and return left arg (1)
       ≠   ⍝ (next value)=1, (prev value)=1, so 1≠1 is false
 {⍞←⍺}     ⍝ Second and subsequent iterations: called with the same arg (1)
           ⍝ Never terminates; prints 1 infinitely

```
> 4 votes

# Answer
## Befunge-93, 5 bytes

```
:_.@#

```

Try 0 online

Try 1 online

First submission, and I only started learning Funge yesterday, so it's very likely there's a shorter solution.

I tried to find a way to remove the need for the ":" but I couldn't.
> 4 votes

# Answer
# Raku, ~~14~~ 11 bytes

```
,1...&say^1

```

0Try it online! 1Try it online!

Abuses the range operator to loop infinitely and the XOR Junction (`^`) to print and to evaluate if the range should stop.
> 4 votes

# Answer
# Turing Machine Code, ~~29~~ bytes or 28 bytes

With the strange rule that the leading '0' or '1' doesn't count towards the byte count.

```
0 0 1 * 1
* _ 0 * 1
* 1 1 r 1

```

Try '0' online!

```
1 0 1 * 1
* _ 0 * 1
* 1 1 r 1

```

Try '1' online!
> 3 votes

# Answer
# PHP, 24 bytes

```
?:die(0.);for(;;)echo 1;

```

Uses ternary condition knowing that in PHP one of the alternatives can be empty and i doesn't need to be assigned to a variable.

0: Try it online!

1: Try it online!

Edit: had to add `'0'` to properly echo zero

Edit2: Had forgotten that `die` was synonym of `exit` (thanks manual)

Edit3: saved 1 byte with `for(;;)` instead of `while(1)`

Edit4: saved 1 byte with `die(0.)` instead of `die('0')` thanks to @Christoph
> 3 votes

# Answer
# Python 3, 37 bytes

```
and exec('while 1:print(1)');print(0)

```

0: Try it online!
1: Try it online!
> 3 votes

# Answer
# MathGolf, 3 bytes

```
Äo↑

```

Try `0Äo↑` online.
Try `1Äo↑` online.

**Explanation:**

```
1     # Push 1
   ↑  # While true without popping,
 Ä    # by using a single builtin as inner block:
  o   #  Print with trailing newline without popping

0     # Push 0
   ↑  # While true without popping
      # (output the entire stack joined together implicitly as result)

```
> 3 votes

# Answer
# PowerShell, 21 bytes

```
0|?{$_}|%{for(){1}};0

```

Try it online!
> 3 votes

# Answer
# Keg, 4 bytes

```
{:|④

```

Try it online!

It seems I'm a bit late to the party! ¯\\\_(ツ)\_/¯

~~Anyhow, this is simply a modification of the usual truth machine~~ This is literally the same truth machine as it would be if we didn't have to place the digit at the start. Funny how implicit input works.

By this, I mean it doesn't matter if y'all place the digit at the start or you place it in input.

(⌐■◡■)
> 3 votes

# Answer
# JavaScript, 34 bytes

```
?(_=>{for(;;)alert(1)})():alert(0)

```

Try it online!
> 3 votes

# Answer
# \>\<\>, ~~15~~ 9 bytes

```
?\0n;
n1<

```

Try it online!

* -6 bytes thanks to JoKing

My first fish program~~, doesn't beat the other one but I wanted to post it anyway.~~ Beats the other one now!

### Explanation:

For 0:
`0?` skip the next command
`0` push `0` to the stack
`n` output the top of the stack
`;` terminate
For 1:
`1?` don't skip the next command (no-op)
`\` mirror down
`>` switch direction to forward
`1` push `1` to the stack
`n` output, then wrap round
> 3 votes

# Answer
# Charcoal, 6 bytes

```
1ＷΣ⊟ＫＡＤ

```

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

```
0ＷΣ⊟ＫＡＤ

```

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

Explanation: The leading `1` or `0` simply prints literally to the canvas. There then follows a `while` loop, the condition of which is the digital sum of the last character on the canvas. Thus if this is zero, the loop never gets off the ground, and the canvas gets implicitly output with the `0` still on it. However, if this is a non-zero digit, such as `1`, then the loop will dump a copy of the canvas for ever. (Note that the `dump` command has a rate limit on it, so that TIO will time out before the output reaches the size limit.)

There are a few variants with the same byte count, such as using `Cast` rather than `Sum`, or `Maximum` or `Minimum` rather than `Pop`, or even by using `Count` or `Find` instead.
> 3 votes

# Answer
# Alchemist, 27 bytes

```
a->a+Out_b
_+0a->a+b
a+b->_

```

Try it online with 0!

Try it online with 1!

This was a bit tricky. Every execution path up to the first application of the first line must be possible in both programs, and the two possible patterns in the first line are mutually exclusive. Hence, in order for the program to work, execution up to that point must be non-deterministic. This program swaps infinitely between two states until the first line is applied.

```
0a->a+Out_b    # the 0 version: from the initial state, add an a to halt and output 0
1a->a+Out_b    # the 1 version: from the a+b state, output 1 and leave the state unchanged
_+0a->a+b      # From the initial state, move to the a+b state
a+b->_         # From the a+b state, move to the initial state

```

A deterministic solution is possible by starting the first line with a two-digit number, but this is 14 bytes longer.
> 3 votes

# Answer
# Perl 6, ~~16~~ 15 bytes

*-1 byte thanks to Jo King*

```
&&1 xx*X[&put]$

```

Try0 it online!
Try1 it online!
> 3 votes

# Answer
# Cubix, 5 bytes

```
^O?@u

```

0 Try it online!

1 Try it online!

Maps onto the cube like

```
  0
^ O ? @
  u

```
* `^` Redirect up onto the top face
* `0` or `1` pushed to the stack
* `?` test
    + `uO?@` if `0` then u-turn onto the integer output pass through the test again and halt
    + `O^` if `1` output the integer and redirect up again
> 3 votes

# Answer
# Python 3, 38 bytes

```
0 or print(0)or exit()
while 1:print(1)

```

Try it online!

```
1 or print(0)or exit()
while 1:print(1)

```

Try it online!

---

If output to STDERR is allowed (30 bytes):
```
0 or exit('0')
while 1:print(1)

```

Try it online!

---

If output as exit code is allowed (28 bytes):
```
0 or exit(0)
while 1:print(1)

```

Try it online!
> 2 votes

# Answer
# Ruby, 17 bytes

```
>0?loop{p 1}:p(0)

```

Try it online!
> 2 votes

# Answer
# TI-BASIC, 10 bytes

```
Repeat not(Ans:Disp Ans:End:"

```

Add either `0:` or `1:` to the beginning of the code to get the desired output.
Output is either just 0 or an infinite amount of 1s.

`Repeat`  loops until its condition is true and ignores the condition for the first loop.
Thus, `not(Ans` will be 1 if `0:` is added and 0 if `1:` is added.

An empty string is added to the end of the program to prevent it from printing `Done`.

**Examples:**

prgmA: `0:Repeat not(Ans:Disp Ans:End:"`

prgmB: `1:Repeat not(Ans:Disp Ans:End:"`

```
prgmA
              0

prgmB
              1
              1
              1
              1
              1
              1
              1

```

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.
> 2 votes

# Answer
# Triangular, 9 bytes

```
.%).?/%(<

```

Try it online!

Formatted, it looks like this, with X being the number:

```
   X
  . %
 ) . ?
/ % ( <

```

How it works:

* The instruction pointer begins at the top going southeast. It hits the first byte which is the number and pushes that to the stack.
* `%` prints the top of the stack as a number.
* `?` skips the next instruction if the top of the stack is not positive. This effectively ends the program if the first byte was zero.
* `<` redirects the IP left.
* `(` creates a jump point, `%` prints the top of the stack, `)` unconditionally jumps to the most recent jump point.
> 2 votes

# Answer
# Bash, 46 bytes

```
 2>t
f()(echo 1;f)
grep -q '0: c' t&&echo 0||f

```

False Version

True Version \- You may have to stop TIO before you'll see the output of ones.

We redirect the error message for the missing command (0 or 1) to a file named `t`, and then we use `grep` to find out which error occured and branch off it.
> 2 votes

# Answer
# Octave, 22 bytes

```
;do disp(ans)until!ans

```

If additional `ans =` on each line is allowed, this could be 17 bytes: `;do ans until!ans`
> 2 votes

# Answer
# Commodore 64 Basic, 26 bytes

Memory address $0039 (or 57 decimal) contains the low byte of the current line number.

```
0 PRINT PEEK(57):IF PEEK(57)=1 THEN 1

```

or

```
1 PRINT PEEK(57):IF PEEK(57)=1 THEN 1

```
> 2 votes

# Answer
# , 23 bytes

```
 echo@0`($:[echo@1)@.*1

```

Try it online!

False

True
> 2 votes

# Answer
# Forked, ~~15~~ ~~13~~ 12 bytes

```
%v
>%|
^-:-&

```

Try it online!

Forked is a very bad two-dimensional esolang I wrote a while ago. For example, the IP will wrap if you run off the bottom of the screen but the program will terminate if you run off the top.

Control flow begins traveling east at the number inputted, hits `%` to print it, then hits the `v` which redirects it south. It enters the fork (for some reason I wanted forks to be entered using three additional bytes apiece) and turns west if 1 was pushed, east if 0. To the east it hits `&` (terminate). To the west the code goes through a couple redirects that put the code in an infinite loop hitting the print command and nop `|` forever.

Due to the ridiculous fork-entering rule, I believe this is the shortest possible program in Forked to do this.
> 2 votes

# Answer
# , 15 bytes

```
(-[echo@[)^:_]0

```

Try it online! (includes both 0 and 1 cases.)

Abuses "fixed point" feature to choose between iterating once or infinitely.

### How they work

```
0(-[echo@[)^:_]0  Case 0
 (-[echo@[)^:_    Try to find the fixed point of (-[echo@[), which does...
    echo@[          Print left argument once, and then
  -[                Return (left - right)
                  The input (right arg, which counts as 0th iteration) is 0
                  1st iteration is also 0, so ^:_ terminates

1(-[echo@[)^:_]0  Case 1
                  Tries to do the same, but...
                  0th iteration is 0
                  1st iteration is 1 - 0 = 1
                  2nd iteration is 1 - 1 = 0
                  3rd iteration is 1 - 0 = 1... so it oscillates between 0 and 1
                  Therefore, there's no fixed point and ^:_ runs infinitely

```
> 2 votes

# Answer
# Thue, 40 bytes

```
!::=1
1+::=_+
_::=~1
+1::=~0
::=
1!+0!

```

Explanation:

Start with zero:

`0!::=1` : String becomes `1!+1`

`+1::=~0` : String becomes `1!`, and zero is printed

No more possible substitutions

Start with one:

`1!::=1` : String becomes `1+0!`

`1+::=1_+` : String becomes `1_+0!`

`_::=~1` : String becomes `1+0!` and one is printed

last two steps repeat at infimum

Try it online
> 2 votes

# Answer
# AWK, 26 bytes

```
{while(1)print 1}{print 0}

```

Try it online! (0) Try it online! (1)

This requires some form of input; an empty string will suffice. Otherwise, I couldn't come up with a valid AWK program that begins with `0` or `1`.
> 2 votes

# Answer
# Japt, 7 bytes

```
©@Op1}a

```

0Test it

```
0          0 / 1
 ©         AND
  @   }a   return first integer that return a truthy value
           when passed through..
   Op1      return undefined and writes 1 to output

```

1Try it online
> 1 votes

# Answer
# PowerShell, 41 bytes

```
0-ge1|iex -ov a
for(;"$a"-match"True"){1}0

```

Try it online!

I didn't think this would be possible in PowerShell, but then I remembered `-outvariable`, which is the key to making this happen. This is the first time I've *ever* used it, even in my `$DayJob`.

Checks whether the input digit is `-g`reater-than-or`e`qual to `1`. That will yield either `False` or `True` for `0` and `1`, respectively. We pipe that into `iex` (short for `Invoke-Expression` and similar to `eval`), which barfs out a spectacular error message because neither `False` nor `True` are legitimate PowerShell expressions. Thankfully, `stderr` is ignored by default.

Then we use the handy-dandy `-outvariable` to put the output of `iex` into variable `$a`. Since the `-ov` captures *all* output into an arraylist, both stdout and stderr are captured, so we get the error message into `$a`. We then `for` loop on the condition whether `$a` (cast as a string to collapse the arraylist) regex `-match`es `"True"`. If it does, we output `1` continuously; otherwise we simply exit the `for` loop without printing anything, output `0`, and terminate.
> 1 votes

# Answer
# Befunge-93, 9 bytes

```
0>:#1.:_@

```

or:

```
1>:#1.:_@

```

Try it with `0`

Try it with `1`
> 1 votes

# Answer
# Cascade, 8 bytes

```
0/
?@
#|

```

Try 0 online! Try 1 online!

Hardcoded input makes this a lot more trivial, since we don't need to store the value of the input or anything.
> 1 votes

# Answer
# Zsh, ~~23~~ 20 bytes

```
=
<<<${${1+1}:-0}
$0

```

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

Normally, the parameter `$0` holds the program/function name. Running `0=` sets the parameter to the empty string, which causes the recursion to break. Without any arguments, `$1` is unset, so the ${:-fallback} `0` is used instead.

Otherwise, `1=` sets `$1` to the empty string, which causes `${1+1}` to expand to `1`.

---

If the program `1` is not in the user's path or another function, then for **16 bytes**:

```
=1
<<<${1:-0}
$0

```

Try it online!

Same principle, but with the parameter in question set to the value `1` instead of empty.
> 1 votes

# Answer
# Wren, 53 bytes

That extremely long System.print ... but it doesn't matter.

```
==0?System.print(0):(0..0/0).each{|i|System.print(1)}

```

Try it online!

## Explanation

If x is the given input bit:

```
x==0  // If the input bit is 0:
?System.print(0) // Output 0 to the console
:     // Otherwise:
(0..0/0) // Generate range from 0 to 0/0 (which yields nan,
         // a negative infinity constant. No matter how
         // you increment 0, you will never get a negative.)
.each{|i|System.print(1)} // Foreach over this infinite list:
                          // Output the number 1

```
> 1 votes

# Answer
# CJam, 6 bytes

You know, the fact that input isn't taken from STDIN helps the CJam code become shorter! (Martin Ender wrote this before)

```
{_o}h;

```

Try it online!

## Explanation

```
1       "The input bit";
 {  }h  "A do ... while loop, taking";
        "the non-popped TOS as condition";
  _     "Duplicate the input bit";
   o    "Output to STDOUT, popping";
      ; "If the bit is 0, we discard";
        "the extra copy on the stack";
        "That is printed implicitly to the";
        "output";

```
> 1 votes

# Answer
# Implicit, 3 bytes

```
(%)

```

Try it online!

Explanation:

```
 X         Push number X (only works at start of program)
(           Create jump point
%          Print top of stack
)            Jump to most recent jump point if top of stack is truthy

```
> 1 votes

# Answer
# GolfScript, 7 bytes

```
{..}do;

```

It sucks that you need to infinitely print 1, and print exactly one 0 otherwise I could take away a few characters!

If the restriction was "term on 0, hang on 1", then `{.}do` is enough. The extra point is for infinite 1s, and the semicolon is or exactly one zero (otherwise there'd be 2 with this solution).

This takes the header, then duplicates it twice. Pop the top, if it's 0, stop, pop, done. One 0 left. If it's a 1, recur the inside, duplicating 1s until your computer burns out of memory.

EDIT: Note, the Wikipedia article has `~{..p}do;` as its solution. This assumes you use the "input" area, whereas SE has slightly more flexible input rules to allow header starts.

Try it online!
> 1 votes

# Answer
# dc, ~~11~~ 10 bytes

```
[p1=m]dsmx

```

Try it online!

Try with 0.

Try with 1.

*Thanks to user41805 for eliminating 1 byte.*
> 1 votes

# Answer
# 1+, ~~19~~ 15 bytes

```
11+/1<"#:[#":1#

```

A fairly trivial ungolfed solution.

Try it 0nline!

Try it on1ine!

**Explanation:**

Firstly, in this language, `1` pushes 1 and `0` is a NOP.

The program consists of two parts: `11+/1<` which converts the internal input into the corresponding number and `1##":"1+1<1+#` which is basically the Truth Machine.

Another nice feature of 1+ is the "rotate" operation `/` which leave the stack unmodified if there's only one number in the stack and swaps the two numbers if there's two.

```
11+                  [Pushes 2]
   /                 [Rotate the stack]
    1<               [Converts 2 to 0 and leave 1 as-is]
      "#:[#":1#      [See https://codegolf.stackexchange.com/a/208961/87986]

```
> 1 votes

# Answer
# Pxem, filename only: 11 bytes.

```
0.z1.o.a0.o

```

0Try it online!

1Try it online!

If you are not familiar with Pxem: `.z ... .a` is "while stack size\<2 or pop!=pop; do something; done" (sorry I misdescript the function).

Also, pushing literates are done backwards; if program begins with `10.z`, then 48 is pushed first, then 49 next. Then the branching is done.
> 1 votes

# Answer
# Vyxal, 4 bytes

```
[{1₴

```

0Try it Online!
1Try it Online!

```
[       If the top of the stack is truthy (i.e. 1):
 {      Repeat forever:
  1₴    Print 1

```
> 1 votes

# Answer
# sed, 9 bytes

```
1c0
=;G;D

```

Try it online!

(sed requires at the minimum an empty line as input to run.)

sed cycles the input line-by-line. The first line is read into the pattern space first, on which the program is run, at the end of which the resulting pattern space will be implicitly output allowing the next cycle to commence with the next line. Commands can be line-addressed, meaning that they will run only on the specified lines. For example, `11c0` will change the 11th line of input to 0, whilst `1c0` changes the 1st line of input to 0.

If `0` is inserted as the first character, the first line becomes `01c0`, i.e. the first line is changed to 0, which ends up printed. A new cycle is started immediately afterwards, and since there are no more lines, the program exits.

If `1` is inserted as the first character, the first line becomes `11c0`, i.e. change the 11th line to 0. This does not happen, because there is only 1 line of input, the empty line. The program proceeds to `=` which prints the line number, i.e. 1. `G` appends a newline followed by the hold space (starts with being the empty line) to the pattern space, which now contains just a newline. `D` deletes the first line of the pattern space until and including the newline, and restarts the cycle with the resulting pattern space without consuming the next line of input. This creates the infinite loop, and since the line number stays at 1, `1` \+ newline is printed out forever. source
> 0 votes

# Answer
# Stax, 4 bytes

```
WQ|c

```

Run and debug it

prepend with `0` or `1`. Bonus: also works as a regular truth machine with input
> 0 votes

# Answer
# Perl 5, 23 bytes

```
?$_=1:say 0;say while$_

```

True

False
> 0 votes

# Answer
# MAWP, 13 bytes

```
!~M1A?:?.[!:]

```

**Explanation:**

```
               Stack starts with 1.
!              Duplicates 0 or 1  [1,0,0] or [1,1,1]
 ~             Reverses the stack [0,0,1] or [1,1,1]
  M            Adds top 2 elements[0,1]   or [1,2]
   1A          Subtract 1 from top[0,0]   or [1,1]
     ?:        If top of stack is 0, print it, otherwise do nothing
       ?.      If top of stack is 0, end program
         [!:]  Infinite loop which duplicates top of stack and prints it

```

Try it!
> 0 votes

# Answer
# 05AB1E, 3 bytes

```
i[?

```

0Try it online!

1Try it online!

```
i[?  # full program
i    # if...
     # (implicit) hardcoded input...
i    # is 1...
 [   # forever...
  ?  # output...
     # (implicit) hardcoded input
     # implicit output

```
> 0 votes

---
Tags: code-golf, source-layout, self-referential
---


title: Please Read Primes

text:
# Question
Title: Please Read Primes
Do you know the book *Murderous Maths*, in the *Horrible Science* series? In the book, the Laplace Princess' "ridiculous" cipher might be interesting enough and simple enough to be a code-golf challenge.

# Task

The original cipher looks like this:

> Please read primes elephant help you me like cold

The nth word is only meaningful if it is a prime. So, the cipher becomes:

> read primes help me

Your task is to write a program that inputs the cipher and outputs the plaintext.

# Rules

* You can take the input in any acceptable forms, e. g. an list of words.
* The input will only consist of printable-ASCII characters.
* You can use 0-based index or 1-based index.
* A "Word" includes any punctuation. For example:

```
This is, "a" great test! I think.

```

should output

```
is, "a" test! think.

```

# Answer
# Japt `-f`, ~~6~~ 2 bytes

I/O as arrays of words with 0-based indexing

```
Vj

```

Try it

```
Vj     :Implicit filter of input array
V      :0-based index of current word
 j     :Is prime?

```

---

## Japt `-S`, 4 bytes

I/O as space-delimited strings, with 0-based indexing

```
¸fÏj

```

Try it

```
¸fÏj     :Implicit input of string
¸        :Split on spaces
 f       :Filter by
  Ï      :  0-based index
   j     :  Is prime?
         :Implicit output, joined by spaces

```

---

## Japt `-S`, 6 bytes

I/O as space-delimited strings, with 1-based indexing

```
¸fÏÄ j

```

Try it

Same as above using `Ä` to add `1` to the index.
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
#āpÏðý

```

Try it online!

```
#         # split the input on spaces
 ā        # push [1..length of the list of words]
  p       # is prime?
   Ï      # keep only words where the above check is true
    ðý    # join with spaces

```
> 2 votes

# Answer
# Perl 6, 22 bytes

```
*[grep &is-prime,2..*]

```

Try it online!

Takes input as a list of words and outputs the zero indexed list.
> 1 votes

# Answer
# Kotlin, 201 bytes

Input is zero indexed.

```
fun p(s:Int):MutableList<Int>{val l=MutableList(0){0}
o@
for(v in 2..s){for(e in l)if(v%e<1)continue@o
l.add(v)}
return l}
fun main(){var w=readLine()!!.split(" ")
for(i in p(w.size))print("${w[i]} ")}

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~125~~ 107 bytes

107 bytes thanks to Black Owl Kai

```
i=input().split();j=k=1
for c in i:
 if j>1:
  while k>2:
   k-=1
   if j%k<1:k=0
  if k:print(c)
 j+=1;k=j

```

Try it online!

120 bytes if it strictly follows rules. -25 bytes thanks to Black Owl Kai

# Python 3, ~~145~~ 120 bytes

```
i=input().split();j=k=1;l=[]
for c in i:
 if j>1:
  while k>2:
   k-=1
   if j%k<1:k=0
  if k:l+=[c]
 j+=1;k=j
print(*l)

```

Try it online!
> 1 votes

# Answer
# Jelly, 4 bytes

```
LÆRị

```

A monadic Link accepting a list of words which yields a list of words.

**Try it online!** (the footer calls the Link then formats, since a full-program implicitly smashes output)

### How?

```
LÆRị - Link: list, W
L    - length (W)
 ÆR  - inclusive prime range = [2,3,5,7,...,Prime <= length(W)]
   ị - index into (W)

```

---

Also 4:

```
JẒƇị

```
> 1 votes

# Answer
# PHP, 167 bytes

```
<?php $i=explode(' ',$argv[1]);$l=count($i);unset($i[0]);for($x=1;$x<$l;$x++){$y=$x+1;$z=2;while($z<$y){$t=$y/$z;if($t==(int)$t)unset($i[$x]);$z++;}}echo join(' ',$i);

```

Try it online!

### Ungolfed:

```
<?php

$input = explode(' ', $argv[1]);
$length = count($input);
unset($input[0]);

for($x = 1; $x < $length; $x++) {
    $y = $x + 1;
    $z = 2;

    while($z < $y) {
        $test = $y / $z;

        if($test == (int) $test) {
            unset($input[$x]);
        }

        $z++;
    }
}

echo join(' ', $input);

?>

```
> 1 votes

# Answer
# Python 3, 90 bytes

```
print(*[w for n,w in enumerate(input().split()[1:])if all((n+2)%i for i in range(2,n+2))])

```

Try it online!
> 1 votes

# Answer
# Rust, 339 bytes

First ever submission to Code Golf, but it works!

```
use std::io;use std::io::BufRead;fn main(){println!("{}",io::BufReader::new(io::stdin().lock()).lines().flat_map(|s|s.unwrap().split_whitespace().map(|s|s.to_owned()).collect::<Vec<String>>()).enumerate().filter(|(x,_)|{if *x<2{return false}for i in 2..*x{if x%i==0{return false}};true}).map(|(_,y)|y).collect::<Vec<String>>().join(" "));}

```

This code is compressed down from this:

```
use std::io;
use std::io::BufRead;
use std::io::BufReader;

fn main() {
    let s = BufReader::new(io::stdin().lock())
        .lines()
        .flat_map(|s| {
            s.unwrap()
                .split_whitespace()
                .map(|s| s.to_owned())
                .collect::<Vec<String>>()
        })
        .enumerate()
        .filter(|(x,_)| {
            if *x<2 {
                return false
            }
            for i in 2..*x {
                if x % i == 0 {
                    return false
                }
            };
            true
        })
        .map(|(_,y)| y)
        .collect::<Vec<String>>()
        .join(" ");
    println!("{}", &s);
}

```
> 1 votes

# Answer
# Ruby `-p -rprime`, 36 bytes

Replaces every word (and the space after it, if present) with the empty string if it is a non-prime word.

```
i=0
gsub(/\S+ ?/){$&if(i+=1).prime?}

```

Try it online!
> 0 votes

# Answer
# C (gcc), 95 bytes

```
#define f(w,n)for(int i=0,j,p[n]={};++i<n;p[i]||printf("%s ",w[i]))for(j=i*i;j<n;j+=i)p[j]=i>1;

```

Try it online!

Sieve of E.
> 0 votes

# Answer
# \+ gmp, 48 bytes

```
(W=scan(,'',,,,''))[gmp::isprime(1:length(W))>0]

```

Try it online!

This use `gmp` for the `isprime` builtin. This returns 0, 1 or 2, hence the test for \> 0. `scan` takes the input as characters split on whitespace and quotes set to empty string.
> 0 votes

# Answer
# Vyxal, 8 bytes

```
⌈'&›¥æ;Ṅ

```

Try it Online!

```
⌈        # Split on spaces
 '    ;  # Filter by
  &›     # Increment register
    ¥æ   # Register prime?
       Ṅ # Join on spaces

```
> 0 votes

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