title: A challenge for rookies

text:
# Question
Title: A challenge for rookies
Print or return the following string:

```
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*

*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
*....... .*...... ..*..... ...*.... ....*... .....*.. ......*. .......*
R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R

```

This represents all the possible positions of a rook on an 8x8 chessboard and for each the possible moves it can make.

* Standard I/O methods apply, you can output as a string, list of lines, matrix of characters, etc.
* The characters used must be exactly as shown, you cannot substitute them for others.
* Trailing whitespace is permitted on each line, and trailing newlines are permitted, but otherwise the output and spacing must be exactly as shown.
* This is code golf, the shortest code in bytes wins.

# Answer
# , 29 27 24 23 bytes

```
' .*xR'{~*/~,0,.~1+=i.8

```

Try it online!

My initial observation was that the output is essentially a row-wise function table of the 8x8 identity matrix with itself, where each evaluation is simply an ordinary addition table: `row_i +/ row_j`.

This can be simplified further by flattening the identity matrix first, as follows:

* `1+=i.8` 8 by 8 identity table, plus 1:

```
2 1 1 1 1 1 1 1
1 2 1 1 1 1 1 1
1 1 2 1 1 1 1 1
1 1 1 2 1 1 1 1
1 1 1 1 2 1 1 1
1 1 1 1 1 2 1 1
1 1 1 1 1 1 2 1
1 1 1 1 1 1 1 2

```
* `0,.~` Add a column of zeros

```
2 1 1 1 1 1 1 1 0
1 2 1 1 1 1 1 1 0
1 1 2 1 1 1 1 1 0
1 1 1 2 1 1 1 1 0
1 1 1 1 2 1 1 1 0
1 1 1 1 1 2 1 1 0
1 1 1 1 1 1 2 1 0
1 1 1 1 1 1 1 2 0

```
* `,` Flatten:

```
2 1 1 1 1 1 1 1 0 1 2 1 1 1 1 1 1 0 1 1 2 1 1 1 1 1 0 1 1 1 2 1 1 1 1 0 1 1 1 1 2 1 1 1 0 1 1 1 1 1 2 1 1 0 1 1 1 1 1 1 2 1 0 1 1 1 1 1 1 1 2 0

```
* `*/~` Multiplication table with self:

```
4 2 2 2 2 2 2 2 0 2 4 2 2 2 2 2 2 0 2 2 4 2 2 2 2 2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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```
* `' .*xR'{~` Convert to ascii. This returns the required pattern.
> 39 votes

# Answer
# Ruby, ~~67~~ 66 bytes

*-1 byte thanks to @G B*

A function that returns a list of lists.

```
->{(a=0..70).map{|x|a.map{'.*R '[x%9|_1%9<8?1[x%10]+1[_1%10]:3]}}}

```

Attempt This Online!

### Ruby, 69 bytes

Alternatively, outputting the string to STDOUT takes two extra bytes.

```
71.times{|x|71.times{$><<'.*R '[x%9|_1%9<8?1[x%10]+1[_1%10]:3]};puts}

```

Attempt This Online!
> 11 votes

# Answer
# Python, ~~86~~ ~~83~~ ~~82~~ 81 bytes

```
lambda r=range(71):[[" .*R"[i%9|j%9<8and(i%10<1)-~(j%10<1)]for i in r]for j in r]
```

Attempt This Online!

-1 byte thanks to @loopy walt
> 7 votes

# Answer
# K (ngn/k), ~~34 32 30 24~~ 20 bytes

```
".*R"a+\:a:,/|+|3,=8

```

Try it online!

idea from jonah's solution

`=8` identity matrix

`3,` prepend a 3

`|` reverse

`+` transpose (this will extend the 3 to eight copies)

`|` reverse again

`,/` raze

`a:` assign to `a`

`a+\:` add-each-right, i.e. make a matrix in which element i,j is `a[i]+a[j]`

`".*R"` index into this string. out-of-bounds indices generate `" "`-s in the result.
> 7 votes

# Answer
# Python, 77 bytes (@xnor)

```
f=lambda*_:[[" ",I[i%10<1]][i%9<8]for i in range(71)]
I=f(I:='.*'),f(I:='*R')
```

Attempt This Online!

### Previous Python, 79 bytes

```
J=[]
f=lambda I=J:[" "[~i%9:]or I[i%10<1]for i in range(71)]
J+=f('.*'),f('*R')
```

Attempt This Online!

### Previous Python, 80 bytes

```
J=[]
f=lambda I=J:sum(zip(*8*[iter(8*(I+7*I[1:]))],8*' '),())
J+=f('R*'),f('*.')
```

Attempt This Online!

This uses the good old grouper to create lots of 8 and to mix in the separators.
> 7 votes

# Answer
# MATL, ~~26~~ ~~25~~ ~~24~~ ~~21~~ 20 bytes

```
'.*xR '8XyQO9Y(le&*)

```

Try it online!

-3 bytes thanks to @Luis Mendo

### Explanation

Port of @Jonah answer to MATL

```
'.*xR '8XyQO9Y(le&*)
       8Xy              % 8 x 8 identity matrix
          Q             % add one
           O9Y(         % add a row of zeros to the end
               le       % flatten
                 &*     % multiply with itself
'.*xR '            )    % convert numbers to required codepoints

```
> 6 votes

# Answer
# sed `-E`, 125 bytes

```
s/^/Rssssssss/
s/.*/&&&&&&&&/
s/.{8}$//
s/.{8}/& /g
y/s/*/
h
y/R*/*./
H;H;H;H;H;H;H;H
g;H;H;H;G;G
s/.{584}/&\n/g
s/.{1244}$//
```

Attempt This Online!
> 6 votes

# Answer
# C (GCC), 102 bytes

```
main(i,k){for(i=9;++i<82;puts(""))for(k=9;++k<82;)putchar(k%9&&i%9?i%10|k%10?i%10&&k%10?46:42:82:32);}
```

Attempt This Online!

# C (GCC), ~~111~~ ~~109~~ 107 bytes

```
#define F(X,c)for(X=0;++X<9;putchar(c))
main(i,j,k,l){F(i,10)F(j,10)F(k,32)F(l,i-j|k-l?i-j&&k-l?46:42:82);}
```

Attempt This Online!
> 4 votes

# Answer
# Knight, 80 bytes

```
;=i~1W>8=i+1i;=j~1;W>8=j+1j;=x~1;W>8=x+1xO+I?j iS*'*'8xT'R'S*'.'8xT'*'' \'O''O''

```

Try It Online!
> 4 votes

# Answer
# Jelly, 17 bytes

```
8⁼þj-‘×þ`ị“.* R ”

```

A niladic Link that yields a list of the lines of characters. The empty lines have trailing spaces.

**Try it online!** (Footer joins with newlines)

### How?

Implements Jonah's brilliant method.

```
8⁼þj-‘×þ`ị“.* R ” - Link: no arguments
8                 - 8
  þ               - ([1..8]) table ([1..8]) with:
 ⁼                -   is equal?
    -             - -1
   j              - join
     ‘            - increment all values
        `         - use as both arguments of:
       þ          -   table with:
      ×           -     multiply
          “.* R ” - ".* R "
         ị        - index into (1-indexed and modular, so 0 gives ' ')

```
> 4 votes

# Answer
# gbz80 machine code, 73 72 70 bytes

```
21 00 C0 06 00 0E 00 16 00 1E 00 36 00 78 B9 20
01 34 7A BB 20 01 34 AF BE 28 08 3C BE 28 08 3E
52 18 06 3E 2E 18 02 3E 2A 22 3E 08 1C BB 20 DB
36 20 23 14 BA 20 D2 36 0A 23 0C B9 20 C9 36 0A
23 04 B8 20 C0 76

```

As an ASM rookie, I gladly accept.

The string is returned in $C000-$D247 ($1248 long, nice). You may check it by copying that range using an emulator debugger (it finishes very quickly, you'll know it's done if the program counter is on or after the halt) into a text file and opening it with a text editor that supports LF. The emulator I used is BGB.

This code can be placed anywhere in a ROM and jumped to from the entrypoint, or called as a routine if the $76 (halt) at the end is replaced with a $C9 (ret).

Source, which may be assembled with RGBDS:

```
section "Header", ROM0[$100]
    jr GenerateMetaTable    ; the generated binary could be placed anywhere because of the lack of calls and jps

    ds $150 - @, 0          ; Make room for the header

GenerateMetaTable:
    ld hl, LotsaSpace
    ld b, 0                 ; meta-line tracker. each of these hardcoded zeroes is necessary because all of these registers change
.outermost:
    ld c, 0                 ; sub-line tracker
.mediumOuter:
    ld d, 0                 ; meta-row tracker
.mediumInner:
    ld e, 0                 ; sub-row tracker
.innermost:
    ld [hl], 0              ; we're out of registers (besides a which is used for comparing), but we have this convenient value we're pointing to that will get overwritten anyway.
    ld a, b
    cp a, c                 ; meta-line == sub-line -> rook move or rook position
    jr nz, .skipFirstInc
    inc [hl]
    .skipFirstInc:
    ld a, d
    cp a, e                 ; meta-row == sub-row -> rook move or rook position
    jr nz, .skipSecondInc
    inc [hl]
    .skipSecondInc:
    xor a, a
    cp a, [hl]
    jr z, .period           ; [hl] == 0 -> neither rook position nor rook move
    inc a
    cp a, [hl]
    jr z, .star             ; [hl] == 1 -> rook move
    ld a, "R"               ; [hl] == 2 -> rook position
    jr .write
.period:
    ld a, "."
    jr .write
.star:
    ld a, "*"
.write:
    ld [hl+], a
.innermostEnd:
    ld a, 8
    inc e
    cp a, e
    jr nz, .innermost
    ld [hl], " "
    inc hl
.mediumInnerEnd:
    inc d
    cp a, d
    jr nz, .mediumInner
    ld [hl], "\n"
    inc hl
.mediumOuterEnd:
    inc c
    cp a, c
    jr nz, .mediumOuter
    ld [hl], "\n"
    inc hl
.outermostEnd:
    inc b
    cp a, b
    jr nz, .outermost
HangMachine:
    db $76                  ; directly encoded halt, saves one byte over "halt", which automatically adds a nop
                            ; this is here to prevent the program from repeating endlessly. that may not seem problematic, but if a tester stops it while [hl] is being used to hold the match count, they'll copy a bad output.
                            ; to make GenerateMetaTable a function, just replace this with "ret"

section "Memory", WRAM0
LotsaSpace:
    ; we need $1248 of space, but we can't just ds it because WRAM0 is $1000 long. no formalism for you. we don't bank-switch ever, so it's not a problem.

```

Edit 1: "ld a, 0" -\> "xor a, a", -1 byte

Edit 2: rearranging character loading jumps allowed removal of one, -2 bytes
> 4 votes

# Answer
# Retina, 64 bytes

```

R7*$(9*$*R)7*$(¶9*$($*7*$(9*.$*)¶)R7*$(9*$*R
%8,9,`.

8,9,`.+

```

Try it online! Explanation:

```

R7*$(9*$*R)7*$(¶9*$($*7*$(9*.$*)¶)R7*$(9*$*R

```

Replace the empty input with the pattern of `R`s, `*`s and `.`s. Note that `*` is Retina 1's string repetition operator so actual `*`s have to be quoted as `$*`.

```
%8,9,`.

```

Clear out every ninth column.

```
8,9,`.+

```

Clear out every ninth row.
> 3 votes

# Answer
# Charcoal, 31 bytes

```
Ｅ⁷¹⭆⁷¹§ .*R∧﹪⊕ι⁹∧﹪⊕λ⁹⊕⁺¬﹪ιχ¬﹪λχ

```

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

```
 ⁷¹                             Literal integer `71`
Ｅ                               Map over implicit range
    ⁷¹                          Literal integer `71`
   ⭆                            Map over implicit range and join
        .*R                     Literal string ` .*R`
      §                         Indexed by
              ι                 Current row
             ⊕                  Incremented
            ﹪                   Modulo
               ⁹                Literal integer `9`
           ∧                    Logical And
                   λ            Current column
                  ⊕             Incremented
                 ﹪              Modulo
                    ⁹           Literal integer `9`
                ∧               Logical And
                         ι      Current row
                        ﹪       Modulo
                          χ     Predefined variable `10`
                       ¬        Logical Not
                      ⁺         Plus
                             λ  Current column
                            ﹪   Modulo
                              χ Predefined variable `10`
                           ¬    Logical Not
                     ⊕          Incremented
                                Implicitly print

```

Actually using ASCII art drawing commands seems to take 51 bytes: Try it online! Link is to verbose version of code.
> 3 votes

# Answer
# PARI/GP, 69 bytes

```
f()=matrix(71,,i,j,Vec(".*R ")[if(i%9&&j%9,(i%10==1)+(j%10==1)+1,4)])
```

Attempt This Online!
> 3 votes

# Answer
# Haskell, ~~99~~ ~~90~~ 89 bytes

```
[[" R*."!!((f(i%10)+f(k%10)+1)*f(k%9*i%9))|k<-r]|i<-r]
(%)=mod
f=fromEnum.(>0)
r=[10..81]
```

Attempt This Online!
> 3 votes

# Answer
# Rust, 171 bytes

```
||(0..71).any(|x|(0..72).map(|y|(x/9,y/9,x%9,y%9,y/71+1)).any(|(x,y,a,b,l)|print!("{:
<1$}",if a>7||b>7{' '}else if x==a&&y==b{'R'}else if x==a||y==b{'*'}else{'.'},l)>()))

```

Playground Link
> 3 votes

# Answer
# C#, 131 bytes

```
_=>{T[]F<T>(T x,T y,T z)=>new T[72].Select((_,i)=>i%10<1?x:i%9<8?y:z).ToArray();return F(F("R","*"," "),F("*","."," "),new[]{""});}

```

Try it online!

---

Makes use of an inline generic function:

```
_ => {
    /* both the characters within each row and the rows in the whole string follow the same pattern
     a default string, a different string at every 10th string,
     and a space string at every 9th string, starting at 8

    e.g. R******* *R****** **R***** ***R**** ****R*** *****R** ******R* *******R
    the default string is "*", the special character is "R" and the space is " "

    for the whole result string, the default string is "*....... .*...... [...]"
    the special string is "R******* *R****** [...]" and the space is either "" or " " (both work)

    */

    // generic function (defines T as the generic type), inputs of type T
    T[] F<T> (T specialChar, T defaultChar, T space) =>
    // create a new T[] of length 72, and set each element according to its index
    new T[72]
        .Select((_, i) =>
            // special char every 10th element
            i % 10 < 1 ? specialChar :
                // space every 9 starting at 8, otherwise default
                i % 9 < 8 ? defaultChar : space
        ).ToArray();

    // construct rook (special) row string
    var a = F("R", "*", " ");
    // construct default row string
    var b = F("*", ".", " ");
    // correctly typed space for next func call
    var c = new string[] { "" };

    // construct whole string using default, special and space strings
    return F(a, b, c);
};

```
> 3 votes

# Answer
# Haskell, 63 bytes

```
q["",q" .*",q" *R"]
q l=[l!!(0^m 10-0^m 9+1)|m<-mod<$>[10..80]]

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~140~~ 102 bytes

```
#define a(z,y)for(int z=8;z--;putchar(y+10))
main(){a(i,)a(j,)a(k,22)a(l,i-j|l-k?i==j|l==k?42:46:72);}

```

Try it online!

```
#define a(z,y) for (int z=8; z--; putchar(y+10))
main() {
  a(i,) // 10 = space
    a(j,)
      a(k, 22) // 22+10 = 32, space
        a(l,
          (i - j) | (l - k) ? // subtract is quicker than != here
            i == j | l == k ? 42 : // if the x matches xor the y matches, print asterisk
              46 : // if neither match, print dot
                72); // if both match, print R, only the last number has 10 added in the macro, so 82
}

```
> 3 votes

# Answer
# Uiua, 24 bytes

```
⊏⊞×.⇌♭≡'⊂0+1⊞=.⇡8" .*xR"

```

Try it!

Port of @Jonah's J answer. Tip: when looking at the output on the Uiua pad, set the font size to the smallest by clicking the gear in the upper right so you can see the output without line wrapping.

```
⊏⊞×.⇌♭≡'⊂0+1⊞=.⇡8" .*xR"
                 " .*xR"  # place ascii replacements on the stack
            ⊞=.⇡8         # 8x8 identity matrix
          +1              # increment
      ≡'⊂0                # add column of zeros
     ♭                    # deshape
    ⇌                     # reverse
 ⊞×.                      # outer product
⊏                         # select

```
> 3 votes

# Answer
# Factor \+ `math.matrices`, 97 bytes

```
[ 8 identity-matrix 1 m+n [ 0 suffix ] map
concat dup outer [ "\0"" .*R"zip substitute ] map ]

```

Try it online!

A straight translation of @Jonah's excellent J answer.

* `8 identity-matrix` Make an 8x8 identity matrix.
* `1 m+n` Add 1 to each element of the matrix.
* `[ 0 suffix ] map` Add a column of 0s to the far right end of the matrix.
* `concat` Flatten the matrix into a list.
* `dup outer` Take the outer product with itself.
* `[ "\0"" .*R"zip substitute ] map` Convert the resulting matrix to the required code points.
> 2 votes

# Answer
# V (vim), 42 bytes

```
iR·* 7o*·. {7ñä}$FR7jdpbñGï{7ñäGGkdd{p

```

Try it online!

Hexdump:

```
00000000: 6952 b72a 201b 376f 2ab7 2e20 1b7b 37f1  iR.* .7o*.. .{7.
00000010: e416 7d24 4652 1637 6a64 7062 f147 ef7b  ..}$FR.7jdpb.G.{
00000020: 37f1 e447 476b 6464 7b70                 7..GGkdd{p

```
> 2 votes

# Answer
# BQN (REPL), 24 bytes

```
" .*xR"⊏˜×⌜˜⥊∾⟜0˘1+=⌜˜↕8

```

Outputs a 2D array of characters. Try it at BQN online!

### Explanation

Ports Jonah's J solution, which you should upvote.

```
" .*xR"⊏˜×⌜˜⥊∾⟜0˘1+=⌜˜↕8
                        ↕8  Range(8)
                     =⌜˜    Equality table with self (8x8 identity matrix)
                   1+       Add 1 to each (main diagonal is 2s, rest is 1s)
               ∾⟜0˘        Append 0 to each row
             ⥊              Deshape into a flat list
          ×⌜˜               Multiplication table with self
       ⊏˜                   Use each element of that 2D array to index into
" .*xR"                     this string

```

---

Just for fun, here's a different solution (27 bytes) that outputs a 2D array of 2D arrays of characters (feels appropriate, but goes against the challenge's I/O requirements and also is longer):

```
{".*R"⊏˜r(+´‿=⋈)⌜r}⌜˜r←↕8

```

Try it at BQN online!
> 2 votes

# Answer
# Vyxal, 16 bytes

```
8Þ□›0j:v*` €xR`İ

```

Try it Online!

Another port of Jonah's answer.
> 2 votes

# Answer
# JShell (Java), ~~191~~ 188 bytes

```
void f(String x){System.out.print(x);}int i,j,x,y;for(j=0;j<8;j++){for(y=0;y<8;y++){for(i=0;i<8;i++){for(x=0;x<8;x++){int X=i^x,Y=j^y;f(X*Y<1?X+Y<1?"R":"x":".");}f(" ");}f("\n");}f("\n");}

```

Or, expanded:

```
void f(String x) {
    System.out.print(x);
}

int i, j, x, y;
for (j = 0; j < 8; j++) {
    for (y = 0; y < 8; y++) {
        for (i = 0; i < 8; i++) {
            for (x = 0; x < 8; x++) {
                int X = i ^ x;
                int Y = j ^ y;
                f(X * Y < 1 ? X + Y < 1 ? "R" : "x" : ".");
            }
            f(" ");
        }
        f("\n");
    }
    f("\n");
}

```
> 1 votes

# Answer
# Pyth, 36 bytes

```
VJU71sm@>".*R "+!%NT!%dT_<7.|%d9%N9J

```

Try it online!
> 1 votes

# Answer
# Java, 151 145 137 bytes

```
for(int y=0,x,a,b;++y<72;){var s="";for(x=1;x<72;s+=x++%9*(y%9)<1?' ':a+b<1?'R':a*b<1?'*':'.'){a=~-x%10;b=~-y%10;}System.out.println(s);}

```

Attempt This Online! Link is to a "normal" Java version, as I don't know if the link to the online JShell will stay valid.

Jeffrey's answer made me aware of JShell, which saves a couple of bytes compared to a lambda function or an interface. **EDIT** It also reminded me that ternary `if`s don't always need parentheses. Thanks!

-8 bytes thanks to @ceilingcat!
> 1 votes

# Answer
# Dart, 173 bytes

```
main(){var l=[0,1,2,3,4,5,6,7],s="R"+"*"*7+"*......."*7,p=" "*7+"\n",i,j,k,m;print([for(i in l)...[for(j in l)for(k in l)...[for(m in l)s[(k^m)*8+i^j],p[k]],"\n"]].join());}
//       1         2         3         4         5         6         7         8         9         0         1         2         3         4         5         6         7
//345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123

```

Pretty-printed:

```
main() {
  var l = [0, 1, 2, 3, 4, 5, 6, 7],
      s = "R" + "*" * 7 + "*......." * 7,
      p = " " * 7 + "\n",
      i, j, k, m;
  print([
    for (i in l) ...[
      for (j in l)
        for (k in l) ...[for (m in l) s[(k ^ m) * 8 + i ^ j], p[k]],
      "\n"
    ]
  ].join());
}

```
> 1 votes

# Answer
# Perl 5, 100 bytes

```
print$_%72?$_/72%9?$_%9?($v=1==$_%72%10)&($h=1==$_/72%9-$_/648)?R:$v|$h?'*':'.':$":'':$/for 73..5184

```

Try it online!
> 1 votes

# Answer
# Uiua, 21 bytes

```
⬚@ ⊏⊞+.♭⊠⊂⊞=.⇡.8".*R"

```

Try it online!

A port of ngn's K answer, which is also based on Jonah's J but adds a deliberate out-of-bounds indexing trick. With size 4 instead of 8, the following vector is generated:

```
[1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4]

```

and its self outer product by addition gives

```
╭─
╷ 2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  1 0 0 0 4 0 1 0 0 4 0 0 1 0 4 0 0 0 1 4
  2 1 1 1 5 1 2 1 1 5 1 1 2 1 5 1 1 1 2 5
  5 4 4 4 8 4 5 4 4 8 4 4 5 4 8 4 4 4 5 8
                                          ╯

```

In this matrix, 0, 1, 2 correspond to `.*R` respectively, and anything larger is a space, so "index into `".*R"` with any out-of-bounds indexes mapped to spaces" gives the correct matrix of characters. Any number \>= 3 works for the padding; reusing 8 saves a byte over hardcoding any other number (which requires a space between the two numbers).

```
⬚@ ⊏⊞+.♭⊠⊂⊞=.⇡.8".*R"
              ⊞=.⇡ 8        identity matrix of size 8
        ♭⊠⊂     .         append 8 to each row and flatten
     ⊞+.                    self outer product by addition
    ⊏               ".*R"    select; convert 0, 1, 2 into ".*R"...
⬚@                           and all others to spaces

```
> 1 votes

# Answer
# 05AB1E, 21 bytes

```
8LδQ>0δª˜Dδ*" .*xR"sè

```

Another port of *@Jonah*'s J answer, so make sure to upvote him as well!

Try it online. (Footer  is to pretty-print the resulting matrix of characters.)

**Explanation:**

```
8LδQ          # Push an 8x8 equality matrix (8x8 of 0s, with main diagonal of 1s):
8L            #  Push list [1,2,3,4,5,6,7,8]
              #  (implicitly use it twice since there isn't anything else on the stack)
  δ           #  Apply double-vectorized:
   Q          #   Equality check
    >         # Increase each by 1
      δ       # Map over each row:
     0 ª      #  Append a 0 to the row
˜             # Flatten the matrix to a single list
 D            # Duplicate it
  δ           # Apply double-vectorized again:
   *          #  To create a multiplication matrix
    " .*xR"   # Push this string
           s  # Swap so the matrix is at the top of the stack
            è # Index the matrix into the string
              # (after which the result is output implicitly)

```
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, chess
---


title: Tips for golfing in Prolog

text:
# Question
Title: Tips for golfing in Prolog
What general tips do you have for golfing in Prolog? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Prolog (e.g. one letter variables is not specific to Prolog to reduce the size of programs).

Please indicate in your tips if it is specific to an implementation of Prolog (e.g. SWI-Prolog specific built-ins)

Please post only one tip per answer, or a list of tips that are all closely related to the same main idea.

# Answer
> 15 votes
# Use Operators for Predicate Names

It is possible to give predicates operators as names so long as the operator is one of the predefined operators (listed here) and is not already defined as a predicate. This saves a few bytes both when defining and calling the predicate since operator predicates do not need to be written in the normal `name(arg1,arg2,etc..)` form and can be called as one might expect with operators.

For one and two argument predicates, they can be give the names of unary and binary operators, respectively. For higher arity predicates, we can still avoid parentheses using pattern matching. For example if we have a predicate `A+B+C:-...`, Prolog will use its operator precedence and associativity rules to transform it into `(A+B)+C:-...` which is a operator predicate where the first argument is pattern matched to `A+B`. Or `A-B+C*D:-...` which becomes `(A-B)+(C*D)` so its first argument is pattern matched to `A-B` and its second is pattern matched to `C*D`.

### Examples

```
_+_+_.
A-B+C*D:-between(A,B,C),C+D.
\X:-X>1,X<10.
X+Y:-length(Y,X),member(X,Y).

5+[10,5,3,2,5],a+b+c,0-20+X*[2,4,6,5,40],\9.

```

The output will be `X = 5.`

Try it Online!

## Corollary

Since DCGs are syntactic sugar for predicates they too can be given operators for names. This works as expected when calling them as DCGs either from a DCG or using the `phrase` predicates or others that are designed to work with DCGs. When calling them as predicates parentheses are required (eg `A+B-->...` must be called like `+(A,B,...)`) since DCG predicates take an additional two arguments for their difference lists. For operator named DCGs with more than two arguments using operator pattern matching then it is important to make sure when calling it as a predicate that the pattern matched operators are distributed correctly.

Giving operator names to DCGs that take no additional arguments can be useful if you need to call them within your program since then you can do so without using parentheses. Caution is required because it can be the case that what you save in parentheses you can lose to added spacing required to parse adjacent operators.

### Examples

```
/ -->a+b+X,X+d+e.
A+B+C-->[A],[B],[C].

X/[],member(c,X),phrase(f+o+o,Y),+(b+a,r,Z,[]).

```

Output will be

```
X = [a, b, c, c, d, e],
Y = [f, o, o],
Z = [b, a, r].

```

Try it online!

## Caveats

With the unary operators `+` and `-`, Prolog will interpret `+20` or `-20` as numbers instead of a call to a `+/1` or `-/1` predicate. Predicates given unary `+` or `-` as names can still be called on number by using parentheses (`+(20)`, `-(20)`). If avoiding the extra bytes from parentheses is desirable other unary operators such as `\`, `$`, etc can be used as names instead.

The combination of pattern matching and operator named predicates is not entirely without flaws. If you have two predicates that have the same operator as their name and with pattern matching one is strictly more general than the other then the more general one may get called first or if the less general one fails (depending on their ordering in the source). For instance in the example above if `A-B+C*D` fails to match its input then Prolog will try calling `X+Y`. This will result in an error because `length/2` require `Y` to be an integer which it will not be since it will be in the form `C*D`. This can be avoided simply by making sure no two predicates have the same operator as their name or if that fails then using cuts and careful ordering of the source.

# Answer
> 11 votes
# Try to put every possible case into a single rule

The clean way to program in Prolog is to declare multiple rules for the same predicate. For example, a predicate to reverse a list with an accumulator would look like this:

```
r([],Z,Z).
r([H|T],Z,R):-r(T,[H|Z],R).

```

In Code-golf, we can remove the first rule, and add a `;` at the end of the second rule to code the recursion end:

```
r([H|T],Z,R):-r(T,[H|Z],R);R=[H|Z].

```

We know that the first condition `r(T,[H|Z],R)` will fail if T is empty, i.e. if the recursion need to end and thus we can add our termination as an or clause after it.

The same principle works in a lot of situations. Note however that sometimes it is actually shorter to declare another rule rather than doing this.

# Answer
> 8 votes
One trick that is frequently useful: Use **CLP(FD) constraints** for integer arithmetic to obtain predicates that can be automatically used in several directions, thus avoiding conditions and dedicated branches and variants.

Use B-Prolog or GNU Prolog, where such constraints are available out of the box, without needing to load any libraries.

# Answer
> 8 votes
# Use arithmetic operators as tuple constructors and cons pairs

If you need to pass a single structure consisting of two or more values, the most obvious thing to use is a list, e.g. `[A,B]`. That's really verbose, though.

There's an alternative. Prolog values can store a pretty much arbitrary nested structure, which isn't evaluated. Here's an example showing how that works:

```
| ?- member(member(A,B),C).
C = [member(A,B)|_] ? ;
C = [_,member(A,B)|_] ? ;
(etc.)

```

`member(A,B)` is just a named tuple in this situation, and the outside `member` (which is a function call) is treating it as such.

Although named tuples are fairly useful in non-golfed Prolog programming, they might seem even more verbose than the list approach. However, we can use pretty much arbitrary characters in the name of the tuple constructor (assuming they're properly quoted); instead of something cute like `member` or a single character like `a`, we can do something like this:

```
| ?- A = '-'('/'(1,2), '/'(3,4)).
A = 1/2-3/4

```

Here, our tuple constructors are `'-'` and `'/'`. And it's interesting to note what the pretty-printer did with them; it's using *infix* notation for the tuples. This is really terse, and parses the same way that the comparable arithmetic operation would. (This also explains why arithmetic uses `is` not `=`; `A = 1+2` would unify `A` with the *tuple* `'+'(1,2)`, so separate syntax is needed to actually evaluate the unevaluated arithmetic expression.) Because a tuple constructor has to be called *something*, you may as well use a character that has a terse syntax (and as a bonus, `-` and `/` are some of the most common choices in non-golfed code too when they want a quick throwaway tuple constructor rather than something meaningful, in much the same way that `i` is often used as a loop variable, so they're entirely reasonable to use in your input and output if you happen to want a tuple there for some reason).

`'-'` and `'/'` are good choices for tuple constructors because they have well-behaved and useful precedence, allowing you to write tuple literals tersely. However, note that you don't need to worry about precedence when intermediate values are produced inside the program. Prolog keeps the tuples stored as a tree rather than as source code, and pretty-printers can output it unambiguously:

```
| ?- A = '-'('-'(1,2), '-'(3,4)).
A = 1-2-(3-4)

```

Because the tuple syntax is so terse (`f(A,B)` is no shorter than `f(A-B)`), you can replace multiple prediccate arguments with tuples at no cost, meaning that if a predicate needs to pass two or more of its arguments to another predicate, you can often form them into a tuple and just pass the tuple (although this will require changing all calls to the predicate, in addition to the predicate itself, to use an appropriate mix of tuple constructors and commas).

Another advantage of this syntax is if you need to use lists internally (rather than to interoperate with standard predicates); a list is basically just a set of nested cons cells, and a cons cell is just a tuple with constructor `'.'`, as can be seen here:

```
| ?- Q = '.'('.'(A,B),'.'(C,D)).
Q = [[A|B],C|D]

```

If your code uses lists "manually", it can make a lot of sense to use a less bulky tuple constructor than `'.'`. A common choice for me is to represent a cons cell as `'/'(Tail,Head)` (because it's about the most readable you can get in debug output without wasting characters). Note that you'll probably want your own `[]` equivalent too; you *could* use `[]` but it's two bytes long, and there are plenty of one-byte atoms (all the lowercase letters) that you can use instead.

So for example, the following list:

```
[1,2,3]

```

could be converted into a manual representation in the same number of characters like this:

```
x/3/2/1

```

whilst gaining the advantage that `[H|T]`-style pattern matches can now be written more tersely as `T/H`, and a test against the empty list as just `x` rather than the longer `[]`. (Of course, this comes with the obvious disadvantage that `member`, `append`, etc., won't work on this representation.)

# Answer
> 7 votes
# Shorter syntax for lists of lists and a way to declare maps

You can save bytes on lists of lists. If you have a list `[[1,2],[3,4]]`, you can actually declare it as `[1:2,3:4]`, which saves 4 brackets = 4 bytes. Note that you can use something else than `:` (for example, `^`).

`1:2` isn't actually a list in that case (whereas `[1,2]` was), it is represented internally as `:(1,2)`. Therefore you cannot use predicates that work on lists on those sublists that use colons.

This trick is mainly used to declare maps, i.e. a list of keys with values attached to them. For example, if you want to declare a map `M` that contains the spelling of a digit in both English and French, you could do something like this:

```
M=[0:'Zero':'Zéro',1:'One':'Un',2:'Two':'Deux', ... ]

```

You can then for example retrieve elements of the map with a built-in predicate like `member/2`. For example, if you want the digit and English word corresponding to `'Quatre'` in `M`, you could do:

```
member(Digit:Name:'Quatre',M).

```

# Answer
> 7 votes
One neat trick: When you need to **fail**, use something that is equivalent to **false/0**, but shorter, such as:

```
?- repeat, writeln(hi), **0=1**.
```

# Answer
> 7 votes
# Shorter stdlib alternatives

These may not apply exactly based on what you are using the predicates for.

* `numlist/3` is better to generate numeric range lists than `between/3` with `bagof`.
* `bagof/3` is a substitute for `findall/3` if you can guarantee the result to be a non-empty list.
* Many string related predicates also use atoms. eg: `format(atom(X),Y,R)` can be done instead of `string(X)`, saving 2 bytes
* some predicates are good aliases for many uses of `foldl`:
    + `sumlist` in place of `foldl(plus,...)`
    + similarly for `max_list`, `min_list`, etc.
* In `aggregate_all(X,Y,_)`
    + `X=count,Y=member(...)` case can be replaced with `occurrences_of_term(E,S,O)`

# Answer
> 5 votes
## Reuse a predicate with different calling modes

For example, you can parse and print a structure with the same predicate, once with a variable argument and another time with a ground term. I used this approach in Make the Stretchy Snakes Kiss. This is not possible in all challenges, of course.

# Answer
> 3 votes
### Print as a side effect which cannot be undone by backtracking, using backtracking to loop.

Goals like "print the first 1000 integers" can be:

```
:-findall(X,(between(0,999,X)),Nums),maplist(writeln,Nums).

```

That can be shortened to:

```
:-findall(X,(between(0,999,X),writeln(X)),_).

```

Backtracking can be used to get rid of the findall loop:

```
:-between(0,999,X),writeln(X),false.

```

Use a shorter `false` as per another tip in these answers:

```
:-between(0,999,X),\+writeln(X).

```

# Answer
> 2 votes
`findall/3` will evaluate arithmetic expressions. I expected to have to use `is/2` and another variable for that, but no:

?- findall(X,(between(1,10,X),Y is X^2,Y>20),Xs).
Xs = [5, 6, 7, 8, 9, 10].

?- findall(X,(between(1,10,X),X^2>20),Xs).
Xs = [5, 6, 7, 8, 9, 10].
```

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


title: Is it a circumfix?

text:
# Question
Title: Is it a circumfix?
## Introduction

We all know prefixes and suffixes. But there are other types of affixes that exist too. Such as circumfixes, a type of affix that has two parts, one of which is a prefix and another of which is a suffix. Figuring out whether some string is a prefix or a suffix of some other string is easy, but what about figuring out whether it might be a circumfix?

That is today's challenge - create a program or function which takes two strings as input, and determine whether the first is a circumfix of the second.

For the purposes of this challenge a string `i1` is a circumfix of another string `i2` if and only if there exists some non-empty string `j` which is a contiguous substring of `i2` such that removing `j` from `i2` results in `i1`, and `j` is neither a prefix nor a suffix of `i2` (if it is, you don't have a circumfix, you just have a suffix or a prefix respectively).

For example, `"fog"` is a circumfix of `"frog"`, because removing `"r"` from `"frog"` produces `"fog"`.

When given valid input, your program either needs to output a single consistent value of your choice if the first input string is a circumfix of the second, and any other value if it is not, or vice versa. For example, you may decide have your program output `6` when the first string is a circumfix of the second, in which case *any* output except `6` is acceptable when it is not.

This is , so do make sure to golf your code.

## Test cases

```
Format:
"String 1", "String 2" -> output
    comments about the test case - in all these test cases, the output will be true if string 1 is a circumfix or string 2 and false otherwise
```

```
"apply", "appreciably" -> true
    "app]reciab[ly"
"rake", "racket by the lake" -> true
    multiple options - "r]acket by the l[ake" and "ra]cket by the la[ke"
"trout", "trumpet" -> false
    Doesn't work at all
"bring", "brought him a gong" -> false
    You only get to remove one substring - "br]ought h[i]m a go[ng" is not allowed
"falcon", "false conundrum" -> false
    You can't have extra stuff at the start or end either - "fal]se [con(undrum)" is not allowed
"goose", "goosebumps" -> false
    "goose]bumps[" is just a prefix
"lame", "blame" -> false
    And "]b[lame" is just a suffix
"pale", "pale ale" -> true
    "pale] ale[" is just a prefix, but "pal]e al[e" is a circumfix, so this is allowed
"b", "barb" -> false
    This could be a prefix ("b]arb[") or a suffix ("]bar[b"), but not a circumfix - "b]ar[b" is not allowed
"abba", "aba" -> false
    "abba" can be split into a prefix of "aba" ("ab") and a suffix of "aba" ("ba"), but "abba" is still not a circumfix of "aba"
"friend", "friend" -> false
    It's only a proper circumfix if you actually remove something - "fri][end" doesn't make the cut
"float", "on" -> false
    You may not assume the first input will be shorter than the second one
"", "" -> false
    One or both input strings may be empty
"Twin Sister", "Twister" -> false
    Inputs are ordered - you may reverse the order, but there must be a consistent ordering
"case", "Castle" -> false
    Inputs are case sensitive
"<<@ 23|>", "<<@23??|> 23|>" -> true
    "<<@]23??|>[ 23|>", not all characters will be letters)

```

# Answer
# , ~~23~~ ~~21~~ 20 bytes

```
>&#*]e.1}:@}.-&#]\.[

```

Try it online!

*-1 byte thanks to Bubbler*

Return true if:

* `>&#` left arg is strictly longer than right (see the "friend"/"friend" test case)
* `*` and...
* `]` the right arg
* `e.` is an element of the list formed by...
* `1 }:@}.` removing the first and last elements of...
* `-&# ]\. [` all the outfixes `\.` of the left arg `[` whose size is the difference in size between the two args `-&#`

That is, J has a builtin to subtract the "chunks" in the middle of the necessary size and leave us with the remaining prefixes and suffixes, catted. We simply have to remove the non-proper ones (ie, the first and last elements of the list of outfixes), and check for what we're searching for.
> 13 votes

# Answer
# Python3, 86 84 83 80 77 76 bytes

```
lambda a,b:len(a)<len(b)*any(a==b[:i]+b[i-len(a):]for i in range(1,len(a)))

```

Try it online!

-2 bytes thanks to @Value Ink whitespace before and after `==`

-1 byte remove whitespace.

-3 bytes thanks to @ovs using any to write for loop in one line.

-3 bytes by replacing `and` with `*`

-1 byte by replacing def with lambda

# Python3.8, 71 bytes

```
lambda a,b:(c:=len(a))<len(b)*any(a==b[:i]+b[i-c:]for i in range(1,c))

```

Try it online!
> 10 votes

# Answer
# Retina 0.8.2, 17 bytes

```
^(.+)(.+)¶\1.+\2$

```

Try it online! Link includes test suite that takes each test on its own line with the test values separated by a tab and converts them into individual tests with the values on separate lines as the main program expects.
> 7 votes

# Answer
# Brachylog, ~~13~~ 12 bytes

```
~c₃{b&}ᵐ↺b↺c

```

Try it online!

Takes string 1 (the possible circumfix) through the output variable, string 2 through the input variable, and outputs through success or failure.

~~I recall that at some point my original solution could be 12 bytes, but as of now subscriptless `c` seems to cycle through all partitions infinitely, causing false test cases to not terminate~~ except it would also cause false positives where the two inputs are equal.

(I tried golfing `{b&}ᵐ` to `Xz∧X` (when it's already a shorter alternative to `{l>0&}ᵐ`), but it has a false positive for the empty test case, since there's no problem cycling an empty list to the length of the longest when everything is empty.)

```
~c₃             Split the input variable into three parts, such that
   {  }ᵐ        each of them
    b&          can have its first element removed (i.e. it is not empty).
        ↺       Rotate the list of partitions left,
         b      remove the first element (which was in the middle),
          ↺     and rotate the remaining partitions again.
           c    Do they concatenate to the output variable?

```
> 7 votes

# Answer
# Jelly, 11 bytes

```
⁻ȧŒṖḢ;ṪƊ€iɗ

```

Try it online!

Takes string 1 (the potential circumfix) as the right/second argument, string 2 as the left/first argument, and outputs 0 if it's not a circumfix and a positive integer otherwise.

(The test footer is bad, but it's better than nothing.)

```
⁻              The arguments are not equal,
 ȧ             and
          ɗ    you also get a truthy value from the next three links:
         i     the index of the right argument (defaulting to 0) in
  ŒṖ           the list of all partitions of the left argument
        €      with each partition mapped to
    Ḣ;ṪƊ       the concatenation of its first and last elements.

```

Although this is mostly just a translation of my Brachylog answer, `ŒṖ` cannot generate empty elements of partitions while `c` is obligated to, so prefixes and suffixes are naturally accounted for.

This 15-byte monstrosity is what I had before I just tried putting the  at the start of the program... and before I realized I could use `Ḣ;Ṫ`: `ŒṖ1,0ịFƊ€⁸ṭṚi>1`
> 7 votes

# Answer
# Regex (POSIX ERE or better), 17 bytes

Takes the two strings in joined format, delimited by a single newline.

```
^(.+)(.+)
\1.+\2$

```

Turned out to be identical to Neil's Retina answer, so I'm mainly answering this to demonstrate it in a wide range of regex engines:

Try it online! \- ECMAScript (SpiderMonkey)
Try it online! \- ECMAScript 2018 (Node.js)
Try it online! \- Perl 5
Try it online! \- PCRE2 (PHP)
Try it online! \- .NET (C#)
Try it online! \- Java (JDK)
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- POSIX ERE (sed), tab as delimiter
Try it online! \- POSIX ERE (egrep), tab as delimiter
> 6 votes

# Answer
# Zsh, 60 bytes

```
for ((c=#2;++i<$#1;))t=${1: i}&&2=${2:/${1%$t}?*$t}
((c-#2))

```

Try it online!

Key constructs here:

* `${var:/pattern}` will replace $var by the empty string if pattern matches the full string.
* `((#var))` is zero if $var is empty.
> 5 votes

# Answer
# Ruby, ~~76~~ 62 bytes

```
->a,b{s=a.size;s<b.size&&(1..s-2).any?{|i|a==b[0,i]+b[i-s,s]}}

```

Try it online!
> 5 votes

# Answer
# Bracmat, 54 bytes

```
(C=c w a z.!arg:(?c.?w)&@(!c:%?a (%?z&@(!w:!a % !z))))

```

This solution uses associative (string) pattern matching and expression evaluation during pattern matching. The associative pattern is %?a %?z, which splits the subject, !c, in two strings, neither of which is empty. (The % prefix ensures that a pattern variable does not accept a neutral element, i.e. an empty string, in the case of string pattern matching.) The expression that is evaluated during pattern matching is @(!w:!a % !z). This happens to be another associative string pattern matching operation.

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~9~~ 8 bytes

```
.œÅΔćìθQ

```

Try it online!

Outputs a non-negative number if it is a circumfix, -1 otherwise.
> 4 votes

# Answer
# Icon, 70 bytes

```
procedure f(a,b)
return(1<*a<*b&a==b[1:i:=2to*a]||b[i-1-*a:0]&1)|0
end

```

Try it online!
> 3 votes

# Answer
# Ruby, ~~40~~ 39 bytes

```
->a,b{a+b=~/^(.+)(.+)(?=#{b}$)\1.+\2$/}

```

Try it online!

### How

Simple regex: if a+b can be split in 5 parts ABCDE where A==C and B==E, and b=CDE, then a is a circumfix of b.

Thanks benrg for pointing out a problem with the first solution (and saving 1 byte).
> 3 votes

# Answer
# Haskell, ~~72~~ ~~71~~ 62 bytes

```
\a b->or[a==take i b++drop j b|j<-[2..length b-1],i<-[1..j-1]]

```

Try it online!

* -1 byte by moving `l a<l b` into the list comprehension, where it only needs a `,` rather than an `&&`
* -9 bytes from benrg's suggestion
> 3 votes

# Answer
# Python 3, 69 bytes

```
f=lambda c,s,i=1:i<len(c)<len(s)and(c==s[:i]+s[i-len(c):])|f(c,s,i+1)

```

Try it online!

*-2 bytes thanks to Bubbler*
> 3 votes

# Answer
# Curry, 28 bytes

*Tested to work in both PAKCS and KiCS2*

```
f(a:b++c:d)(a:b++_:_++c:d)=1

```

Try it online!

This returns `1` if the first argument is a circumfix and nothing otherwise. In cases where there are multiple ways the string could be a circumfix it will return `1` multiple times i.e. it is non-deterministic but always gives `1`. I think this is fine.

The program is basically just a pattern match checking that the first input is made up of two non-empty strings and that the second is made of the same two strings with another non-empty string between them.

This uses two pattern matching features available to Curry not present in Haskell. The first is `++` patterns, and the second is pattern variables. e.g. we require the two `a`s to be *the same `a`*.

This allows it to beat out the Haskell answer handily.

## Testing

TIO has a limited ability to test things like this. Paste the following to smap and run in `PAKCS 2.2.0` for better testing abilities:

```
import Control.SetFunctions

f(a:b++c:d)(a:b++_:_++c:d)=1

-- Helper to run tests
helper :: [a] -> [a] -> Bool
helper x y =
  not $ isEmpty $ set0 $ f x y

main =
  [ helper "fog" "frog"
  , helper "apply" "appreciably"
  , helper "rake" "racket by the lake"
  , helper "trout" "trumpet"
  , helper "bring" "brought him a gong"
  , helper "falcon" "false conundrum"
  , helper "goose" "goosebumps"
  ]

```

This test handler will not work in KiCS2 or at least not on the version used by smap. But the function itself does if you want to manually test it.
> 3 votes

# Answer
# JavaScript (ES6), 70 bytes

Takes input as `(a)(b)`.

```
a=>b=>[...a].some((_,i)=>b[l=a.length]&&a==b.slice(0,l-i)+b.slice(-i))

```

Try it online!
> 2 votes

# Answer
JavaScript (ES6), 72 bytes

```
s=>t=>[...s].some((x,i)=>t[l=s.length]&&i&&s==t.slice(0,i)+t.slice(i-l))

```

Return true if

* the second string is longer than the first
* there is a position to split the first string in 2 parts, such as the second string starts with the left part and ends with the right part

**Test**

```
z=`"apply", "appreciably" -> true
    "app]reciab[ly"
"rake", "racket by the lake" -> true
    multiple options - "r]acket by the l[ake" and "ra]cket by the la[ke"
"trout", "trumpet" -> false
    Doesn't work at all
"bring", "brought him a gong" -> false
    You only get to remove one substring - "br]ought h[i]m a go[ng" is not allowed
"falcon", "false conundrum" -> false
    You can't have extra stuff at the start or end either - "fal]se [con(undrum)" is not allowed
"goose", "goosebumps" -> false
    "goose]bumps[" is just a prefix
"lame", "blame" -> false
    And "]b[lame" is just a suffix
"pale", "pale ale" -> true
    "pale] ale[" is just a prefix, but "pal]e al[e" is a circumfix, so this is allowed
"b", "barb" -> false
    This could be a prefix ("b]arb[") or a suffix ("]bar[b"), but not a circumfix - "b]ar[b" is not allowed
"abba", "aba" -> false
    "abba" can be split into a prefix of "aba" ("ab") and a suffix of "aba" ("ba"), but "abba" is still not a circumfix of "aba"
"friend", "friend" -> false
    It's only a proper circumfix if you actually remove something - "fri][end" doesn't make the cut
"float", "on" -> false
    You may not assume the first input will be shorter than the second one
"", "" -> false
    One or both input strings may be empty
"Twin Sister", "Twister" -> false
    Inputs are ordered - you may reverse the order, but there must be a consistent ordering
"case", "Castle" -> false
    Inputs are case sensitive
"<<@ 23|>", "<<@23??|> 23|>" -> true
    "<<@]23??|>[ 23|>", not all characters will be letters)`

f=s=>t=>[...s].some((x,i)=>t[l=s.length]&&i&&s==t.slice(0,i)+t.slice(i-l))

z.split('\n').forEach((s,i)=>{
    var m = s.match(/"([^"]*)", "([^"]*)" -> (true|false)/)
    if (m) {
        console.log(`"${m[1]}" "${m[2]}" should be ${m[3]} and is ${f(m[1])(m[2])}`)
    }
})
```
> 2 votes

# Answer
# Prolog (SWI), 104 bytes

```
e([],_).
e([H|T],[H|U]):-e(T,U).
e(L,[_|U]):-e(L,U).
f(X,Y):-string_chars(X,A),string_chars(Y,B),e(A,B).

```

Try it online!
> 2 votes

# Answer
# Java (JDK), 46 bytes

```
a->b->(a+"\0"+b).matches("(.+)(.+)\0\\1.+\\2")

```

Try it online!

## Credits

* -2 bytes thanks to ceilingcat
* -2 bytes thanks to Sara J
* The 46 bytes solution (-86 bytes) is actually the full implementation in Java of deadcode's regex answer (which incidentally also contains a Java solution, but only to demonstrate the regex).
> 2 votes

# Answer
# Wolfram Language (Mathematica), 30 bytes

```
#2/.{p__,__,s__}/;{p,s}==#->0&

```

Try it online!

Takes two lists of characters as input. Returns `0` if the first string is a circumfix of the second, or the second string otherwise.
> 2 votes

# Answer
# APL (Dyalog Unicode), 21 bytesSBCS

Anonymous infix function. Takes strings 1 and 2 as left and right arguments. Requires `⎕IO←0`.

```
{(⊂⍺)∊∊¨↑∘⍵¨¨(1↓⍳≢⍺)-⊂0,~/≢¨⍺⍵}

```

Try it online!

`{``}` "dfn";  and  are is strings 1 and 2:

`⍺⍵` strings 1 and 2

`≢¨` length of each

`~/` remove elements from the first that are in the second (gives empty list if same length)

`0,` prepend zero

enclose to treat as a whole

`(``)-` subtract that from the following:

`≢⍺` length of string 1

indices zero through that

`1↓` drop the first one (the zero)

This gives us the head-tail pairs to try.

`¨¨` for element of each of the head-tail pairs:

`↑∘⍵` take that many characters from string 2 (from the end if negative)

`∊¨`**ϵ**nlist (flatten) each

`(``)∊` is the following an **ϵ**lement of that?

`⊂⍺` the entire string 1
> 2 votes

# Answer
# Perl 5, ~~73~~ 77 bytes

```
sub f{(grep$_[1]=~/^@{[$_[0]=~s|.{$_}|\Q$&\E.+|r]}$/,1..length($_[0])-1)?1:0}

```

Try it online!
> 1 votes

# Answer
# Nekomata \+ `-e`, 7 bytes

```
≠;sᵃN,=

```

Attempt This Online!

```
≠;sᵃN,=
≠           Check that the two inputs are not equal
 ;          Split the second input into two parts
  s         Take a suffix of the second part
   ᵃN       Check that both the first part and the suffix are non-empty
     ,      Join the first part and the suffix
      =     Check that the result is equal to the first input

```
> 1 votes

---
Tags: code-golf, string, decision-problem, subsequence
---


title: Diagonal Binary Sequence

text:
# Question
Title: Diagonal Binary Sequence
## Challenge:

Given a positive number \\$n\\$, convert it to binary, and output a where all `1`s form a top-left to bottom-right diagonal line, including a leading column of `1`s. To give two examples:

\\$n=1\\$ will result in `[1,3,5,9,17,33,65,129,...]`, with binary values:

```
1
11
101
1001
10001
100001
1000001
10000001
↓       ↘

```

\\$n=89\\$ will result in `[89,153,281,537,1049,2073,4121,8217,...]`, with binary values:

```
1011001
10011001
100011001
1000011001
10000011001
100000011001
1000000011001
10000000011001
↓         ↘↘  ↘

```

In general, the binary sequences are formed by replacing the leading `1` with `10` in every iteration, with the exception of \\$n=1\\$.

## Challenge rules:

* The input \\$n\\$ is guaranteed to be positive.
* Default rules apply, so you're allowed to:
    + Take an additional input \\$k\\$ and output the \\$k^{th}\\$ value of the sequence, either 0-index or 1-index.
    + Take an additional input \\$k\\$ and output the first \\$k\\$ values of the sequence.
    + Output the values of the sequence indefintely.
* Of course, any reasonable output format can be used. Could be as strings/integers/decimals/etc.; could be as an (infinite) list/array/stream/generator/etc.; could be output with space/comma/newline/other delimiter to STDOUT; etc. etc.
    + I/O as binary isn't allowed for this challenge, since it's already easy enough as is.

**Please state what I/O and sequence output-option you're using in your answer!**

## General Rules:

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

## Test Cases:

```
n     First 10 values of the output sequence

1     [1,3,5,9,17,33,65,129,257,513,...]
2     [2,4,8,16,32,64,128,256,512,1024,...]
3     [3,5,9,17,33,65,129,257,513,1025,...]
6     [6,10,18,34,66,130,258,514,1026,2050,...]
7     [7,11,19,35,67,131,259,515,1027,2051,...]
12    [12,20,36,68,132,260,516,1028,2052,4100,...]
31    [31,47,79,143,271,527,1039,2063,4111,8207,...]
89    [89,153,281,537,1049,2073,4121,8217,16409,32793,...]
111   [111,175,303,559,1071,2095,4143,8239,16431,32815,...]
1000  [1000,1512,2536,4584,8680,16872,33256,66024,131560,262632,...]

```

# Answer
> 4 votes
# Nibbles, ~~8.5~~ 7.5 bytes (15 nibbles)

```
`.$+^2,:>2``@

```

Attempt This Online!

```
`.$+^2,:>2``@    # full program
`.$+^2,:>2``@$$$ # with implicit arguments shown;
`.               # iterate while unique (in this case, for ever),
  $              # starting with the input:
   +             #   add
               $ #   the previous result to
    ^2           #   2 to the power of
      ,          #     the length of
          ``@$   #     the binary digits of the previous result
        >2       #     without the first two digits
       :      $  #     and appending the result so far

```

# Answer
> 12 votes
# Python, 39 bytes

```
lambda n,k:n^-2&(1^1<<k)<<len(bin(n))-3

```

Attempt This Online!

## Explanation

```
lambda n,k:n^-2&(1^1<<k)<<len(bin(n))-3
           n^                             # change bits
             -2&                          # keep lowest bit
                (1^1<<k)                  # 1 0000 1  (k-1 zeros)
                        <<len(bin(n))-3   # shifted to highest bit

```

---

# Python, 49 bytes

*simple string based solution, the n&1 is needed to satisfy the test-case for input 1*

```
lambda n,k:n&1|int((s:=bin(n))[:3]+k*"0"+s[3:],2)

```

Attempt This Online!

# Answer
> 9 votes
# JavaScript (V8), 41 bytes

Prints the sequence 'indefinitely' (in practice, until the call stack overflows).

```
f=(n,k=2)=>k*2>n?print(n)|f(n+k):f(n,k*2)

```

Try it online!

### Commented

```
f = (         // f is a recursive function taking:
  n,          //   n = input
  k = 2       //   k = power of 2 to be added to n
              //       the minimum is 2, because of
              //       the edge case n = 1
) =>          //
k * 2 > n ?   // if k * 2 is greater than n:
  print(n)    //   print n
  | f(n + k)  //   and do a recursive call with n + k
:             // else:
  f(n, k * 2) //   do a recursive call with k doubled

```

# Answer
> 7 votes
# Husk, 8 bytes

```
¡(Y3ḋ:.ḋ

```

Try it online!

When your language does not have logarithms you need to get creative with base conversion. Here's some fun with half bits!

Takes a positive integer as input and outputs an infinite list of the sequence starting from that number.

### Explanation

```
¡(Y3ḋ:.ḋ
¡(        Infinitely repeat the following commands and collect outputs in a list:
       ḋ    Convert to base 2
     :.     Prepend 0.5 as an extra initial digit
    ḋ       Convert back from base 2
  Y3        Take the maximum between the obtained value and 3

```

As the challenge states, this sequence can be generated by replacing the leading `1` in the binary representation of each value with `10`. If we allow our "binary" number to have digits higher than 1, we could simply add 1 to the first digit (e.g. \\$5\_{10} = 101\_2 \rightarrow 201\_{"2"} = 1001\_{2} = 9\_{10}\\$). Even better, adding 1 to a digit in base 2 is equivalent to adding 0.5 to the digit preceding it! (\\$201\_{"2"} = \[0.5\]\[1\]\[0\]\[1\]\_{2.0} = 1001\_2\\$; I think I'm starting to get *too* creative with notation here).

Taking the maximum between the resulting number and 3 was the shortest way I could find to fix the edge case for 1.

# Answer
> 6 votes
# Python 2, 41 bytes

A function that takes \\$ n \\$ as input, and outputs the sequence indefinitely.

```
def f(n):print n;f(n^3<<len(bin(n))-3&-2)

```

Try it online!

# Answer
> 5 votes
# Excel, ~~41~~ 53 bytes

```
=DECIMAL(10^B1&TEXTAFTER(BASE(A1,2),1),2)+IF(B1,A1=1)

```

Inputs *n* and *k* in cells `A1` and `B1` respectively, where *k* represents the *k*th 0-indexed value of the sequence.

# Answer
> 5 votes
# 05AB1E, 9 bytes

```
λbg<1Mo₁+

```

Try it online! or try all testcases.

## Explanation

```
λ         # recursively start with f(0) = n
 bg<       # push floor(log2(f(i-1)))
 1M        # max(1, floor(log2(f(i-1))))
 o         # 2**max(1, floor(log2(f(i-1))))
 ₁+        # f(i) = f(i-1) + 2**max(1, floor(log2(f(i-1))))

```

# Answer
> 5 votes
# Haskell, 35 bytes

```
(%2)
n%k|k*2>n=n:(n+k)%k|l<-k*2=n%l

```

Attempt This Online!

Port of Arnauld's JavaScript answer.

# Answer
> 5 votes
# K (ngn/k), 13 bytes

```
(3|2/2,1_2\)\

```

Try it online!

A base conversion trick that works somewhat like Husk or Nekomata answers, but keeps things in integers. This works by replacing the leading 1 with a 2 in the binary representation.

```
(3|2/2,1_2\)\
(          )\    collect first k iterations:
         2\      convert to base 2
     2,1_        remove the leading 1 and attach a 2
   2/            convert from "base 2" to integer
 3|              max with 3 to handle 1

```

# Answer
> 4 votes
# , 40 bytes

```
f=\(n){m=log2(print(n))%/%1;f(n+2^m+!m)}

```

Attempt This Online!

# Answer
> 4 votes
# Uiua, ~~18~~ 14 bytes

```
⍥(+ⁿ∶2↥1-1⧻⋯.)

```

Try it!

Returns the nth member of the sequence.

-4 thanks to Dominic van Essen

```
⍥(+ⁿ∶2↥1-1⧻⋯.)
⍥(           )  # repeat
            .   # duplicate
           ⋯    # convert to bits
          ⧻     # length
        -1      # subtract 1
      ↥1        # max between this and 1 (need this for input of 1)
   ⁿ∶2          # 2 raised to the result
  +             # add

```

# Answer
> 4 votes
# Rust, 49 bytes

Input is an integer n as a start value and an integer k for the sequence index. I tried experimenting with `next_power_of_two`, but the name turned out to be way too long.

```
|n:u64,k:u32|1<<n.ilog2()+k|n&!(1<<n.ilog2())|n&1

```

Attempt This Online!

Explanation and prettier code:

```
// A captureless closure with two integer arguments
// n is the seed number, k is the sequence index
|n: u64, k: u32|
// The following numbers get bit-or'ed together:
       // A one followed by zeroes whose length is the length of the original number plus the parameter k.
       // ilog2 calculates the floored base-2 logarithm.
       // This means 1 shifted by it is equivalent to setting all digits but the most significant one to zero.
       // Adding k means shifting the most significant one, which is the only thing k is used for in this sequence.
       1 << n.ilog2() + k
       // The number n, with its most significant one bit set to zero (the replacement part).
   |   n & !(1 << n.ilog2())
       // A one if the original number's least significant digit contains a one. Only relevant for n=1.
   |   n & 1

```

# Answer
> 4 votes
# K (ngn/k), 25 21 bytes

```
{2/?[;!2;1,x=1]@2\x}\

```

Try it online!

-4 bytes - thanks to @coltim

# Answer
> 4 votes
# x86 32-bit machine code, 14 bytes

```
0F BD C8 E3 03 0F B3 C8 01 D1 0F AB C8 C3

```

Try it online!

Following the `regparm(2)` calling convention, this takes *n* in EAX and a 0-index in EDX, and returns a number in EAX.

In assembly:

```
f:  bsr ecx, eax    # Set ECX to the highest position of a 1 bit in EAX.
    jecxz s         # Jump if ECX is 0.
    btr eax, ecx    # (Otherwise) Remove that highest 1 bit.
s:  add ecx, edx    # Add the index (in EDX) to ECX.
    bts eax, ecx    # Reinsert a 1 bit into EAX at position ECX.
    ret             # Return.

```

# Answer
> 3 votes
# Retina 0.8.2, 84 bytes

```
^.+
$*
+`^(1+)\1
$+0
01
1
^(.)(.+)?¶(.+)
$1$3$*0$2$#2$*##
0##
0
1|0#
01
+`10
011
%`1

```

Try it online! Takes `n` and `k` as input and outputs the `k`th (0-indexed) term of the sequence but link is to test suite for multiple values of `n` that sets `k=0..4` (because larger values would be too slow).

91 bytes to output the first `k` terms:

```
^.+
$*
+`^(1+)\1
$+0
01
1
^(.)(.*)¶(.+)
$1$3$*_$2
_
$'¶1
O`
1A`
_\b
1
_
0
1
01
+`10
011
%`1

```

Try it online! Takes `n` and `k` as input and outputs the first `k` terms of the sequence but link is to test suite for multiple values of `n` that sets `k=5` (because larger values would be too slow). Explanation:

```
^.+
$*

```

Convert `n` to unary.

```
+`^(1+)\1
$+0
01
1

```

Convert `n` to binary.

```
^(.)(.*)¶(.+)
$1$3$*_$2

```

Convert `k` to unary as `_`s and insert it after the first digit of `n`.

```
_
$'¶1
O`
1A`

```

Generate all of the first `k` terms.

```
_\b
1

```

Fix the `n=1` error.

```
_
0

```

Change the remaining `_`s to `0`s.

```
1
01
+`10
011

```

Convert to unary.

```
%`1

```

Convert to decimal.

54 bytes with the original intent that the leading `1` participates in the diagonal:

```
.+¶
$*_
\d+
$*
+`(1+)\1
$+0
01
1
^.|1
01
+`1[0_]
011
1

```

Try it online! Takes `k` and `n` as input and outputs the `k`th (0-indexed) term of the sequence but link is to test suite for multiple values of `n` that sets `k=0..4` (because larger values would be even slower).

70 bytes to output the first `k` terms:

```
.+¶
$*_
\d+
$*
+`(1+)\1
$+0
01
1
M!&`_.+
O`
%`^_.|1
01
+`1[0_]
011
%`1

```

Try it online! Takes `k` and `n` as input and outputs the first `k` terms of the sequence but link is to test suite for multiple values of `n` that sets `k=5` (because larger values would be even slower). Explanation:

```
.+¶
$*_

```

Convert `k` to unary as `_`s.

```
\d+
$*

```

Convert `n` to unary.

```
+`(1+)\1
$+0
01
1

```

Convert `n` to binary.

```
M!&`_.+
O`

```

Generate the first `k` terms.

```
%`^_.|1
01
+`1[0_]
011

```

Convert to unary, but the leading `_` makes the next digit `1` while any remaining `_`s are interpreted as `0`s.

```
%`1

```

Convert to decimal.

# Answer
> 3 votes
# Perl 5.10 -n, 35 bytes

```
$_^=$_-1?3<<(1.4427*log):2while say

```

Try it online!

Finds the next elem by xor'ing the current n with `3 << log₂(n)` where \<\< is the left shift operator that only cares about the integer part of log₂. Here n=1 is handled as a special case where 1 is xor'ed by 2 to get 3.

```
 89 xor (3 << log2(89)  ) =  89 xor (3<<6) = 153
153 xor (3 << log2(153) ) = 153 xor (3<<7) = 281
281 xor (3 << log2(281) ) = 281 xor (3<<8) = 537
.
.

```

# Answer
> 3 votes
# Fortran (GFortran), 73 bytes body, 13 bytes header and footer

```
program x

read*,n;i=2**(31-leadz(n));n=n-i;do;print*,i+n;if(i<2)n=n+1;i=i*2;end do

end

```

Try it online: n=1, n=89

Reads `n` from standard input and outputs the corresponding sequence.

Uses `leadz()` to count the leading zeros. Puts the highest 1 into `i` and removes it from `n`. The loop shifts the highest 1 further to the left in each iteration and outputs the sum of `i` and `n` in each cycle. Special handling for `n==1`.

# Answer
> 2 votes
# Charcoal, ~~20~~ 19 bytes

```
ＮθＩ⁺θ×Ｘ²Ｌ⍘÷θ²¦²⊖Ｘ²Ｎ

```

Try it online! Takes `n` and `k` as input and outputs the 0-indexed `k`th element but link is to version that outputs the first `k` elements at a cost of 1 byte. Explanation: Port of @Arnauld's JavaScript answer with some inspiration from @DominicvanEssen's Nibbles answer.

```
Ｎθ                  Input `n` as a number
       ²            Literal integer `2`
      Ｘ             Raised to power
           θ        Input `n`
          ÷         Integer divided by
            ²       Literal integer `2`
         ⍘          Converted to base
              ²     Literal integer `2`
        Ｌ           Take the length
     ×              Multiplied by
                 ²  Literal integer `2`
                Ｘ   Raised to power
                  Ｎ Input `k` as a number
               ⊖    Decremented
   ⁺                Plus
    θ               Input `n`
  Ｉ                 Cast to string
                    Implicitly print

```

14 bytes with the original intent that the leading `1` participates in the diagonal:

```
ＮθＩ｜θＸ²⁺⊖Ｌ↨θ²Ｎ

```

Try it online! Takes `n` and `k` as input and outputs the 0-indexed `k`th element but link is to version that outputs the first `k` elements at a cost of 1 byte. Explanation:

```
Ｎθ              Input `n` as a number
      ²         Literal integer `2`
     Ｘ          Raised to power
           θ    Input `n`
          ↨     Converted to base
            ²   Literal integer `2`
         Ｌ      Take the length
        ⊖       Decremented
       ⁺        Plus
             Ｎ  Input `k`
   ｜            Bitwise Or
    θ           Input `n`
  Ｉ             Cast to string
                Implicitly print

```

# Answer
> 2 votes
# TI-Basic, 20 bytes

```
While 1
Disp Ans
max(3,Ans+2^int(log(Ans,2
End

```

Takes input in `Ans`. Outputs infinitely with each number on its own line. If not using OS 2.53 MP or higher, replace `log(Ans,2` with `log(Ans)/log(2` for +2 bytes.

# Answer
> 2 votes
# Nekomata, 9 bytes

```
ᶦ{Ƃ2ŗɔƃ3M

```

Attempt This Online!

A port of @Leo's Husk answer.

```
ᶦ{Ƃ2ŗɔƃ3M
ᶦ{          Infinite loop and print the result of each iteration:
  Ƃ             Convert to base 2
   2ŗɔ          Prepend 1/2
      ƃ         Convert back from base 2
       3M       Take the maximum of the result and 3

```

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
λb¦TìC3M

```

Now that it's been a short while, I'm gonna post my own solution.

Outputs the infinite sequence.

Try it online or verify the first ten terms of all test cases.

**Explanation:**

```
λ         # Create a recursive environment,
          # to generate the infinite sequence
          # (which will be lazily output implicitly at the end)
          # Starting with a(0) = (implicit) input
          # And where every following a(n) is calculated as:
          #  Implicitly push the previous term a(n-1)
 b        #  Convert a(n-1) to a binary string
  ¦       #  Remove its leading "1"
   Tì     #  Prepend "10" instead
     C    #  Convert it back from binary to a (base-10) integer
      3M  #  Manually fix a(1) for input=1:
      3   #   Push 3
       M  #   Push a copy of the maximum of the stack

```

# Answer
> 2 votes
# Uiua, 12 bytes

```
⍥(↥3+⍜'ₙ2⌊.)
⍥(+ⁿ↥1⌊ₙ2,2)

```

Try it online!

```
⍥(↥3+⍜'ₙ2⌊.)    input: repetition, initial number
⍥(         )    repeat the successor operation the given number of times:
      ⍜'ₙ2⌊      power of two <= current number
   ↥3+     .     add to the current number, and maximum with 3 to handle 1

⍥(+ⁿ↥1⌊ₙ2,2)
       ⌊ₙ2,       floor(log2(current number))
     ↥1          max with 1 to handle 1
    ⁿ     2      2 raised to the power of that
   +             add to the current number

```

Could be 10 bytes if there weren't a bug in `⍜ₙ`:

```
⍥(+⊃⍜ₙ⌊↥2)
    ⊃    2    call two functions on 2 and the current number:
      ⍜ₙ⌊      power of two <= current number,
         ↥     max
   +           add the two

```

# Answer
> 1 votes
# Ruby, 39 bytes

```
->n,k{r=1;r*=2until n<r*2;n-r/2*2|r<<k}

```

Try it online!

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