# Question
Title: Modified Boggle Checker, with Modified Boggle-able Code
# Background

Boggle is a board game where the players have to find English words on a 4-by-4 board of random alphabets. Words can be constructed by selecting sequentially adjacent cells on the board. ("adjacent" means horizontally, vertically or diagonally adjacent.) Also, same cell can't be used more than once in a word.

The following is an example board:

```
I L A W
B N G E
I U A O
A S R L

```

On this board, `BINGO`, `ORANGE` and `WEARS` are valid words, but `SURGE` and `RUSSIA` are not:

* `SURGE` : There's no adjacent pair on the board having `RG`.
* `RUSSIA` : `S` cannot be used twice.

**Modified Boggle** is a modified version of Boggle, with the following rules:

* The board size is `n`-by-`n`, where `n` can be any positive integer.
* Each cell can contain any one byte between 0 and 255 inclusive.
* A cell can be used more than once, *but not twice in a row*.

Using the example board above, in addition to `BINGO`, `ORANGE` and `WEARS`, `LANGUAGE` becomes a valid string (since `G` is used twice, but not twice in a row) but `RUSSIA` is still not (due to `SS` pair).

Here is another example using a code fragment. The string `from itertools import*\n` can be found on the following board, but not `from itertoosl import*` or `from itertools import *`:

```
f   i   ' ' s
r   t   m   l
e   o   o   p
\n  *   t   r

```

Note that you need two `o`'s in order to match the `oo` sequence.

# Challenge

Write a function or program that, given a Modified Boggle board `B` (of any size) and a string `s`, determines if `s` can be found on `B`.

# Restrictions

**Your code itself should also fit on a Modified Boggle board `b`.** That is, you must show the board `b` in your submission along with your code, so that your function/program outputs true if it is given `b` and your code as input.

# Scoring

**The score of your submission is the side length of the smallest board `b` where you can fit your code.** Ties are broken by the usual rules, i.e. the length of your code in bytes. The submission with the **lowest score** (for both criteria) wins.

For example, `from itertools import*\n` has the score of 4 (using the board above) and code length of 23 bytes.

# Input and Output

For input, you can take any convenient method for both `B` and `s`. This includes list of chars and list of charcodes, 2D or flattened or whatever makes sense. Also, you can optionally take the board size as a part of the input.

For output, you can choose one of the following:

* Truthy and falsy values following your language's convention, or
* One predefined value for true and false respectively.

Please specify your input/output method in your submission.

# Answer
> 10 votes
# Python 2, score 3, 20972 bytes

```
exec'cecxc%c'%(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+…

```

Full code is the output of: Try it online!

Fits on the Boggle board:

```
e x (
c % 1
' + )

```

Decodes and executes this program:

```
cecxc=any
c,cec=input()
cxec=len(c)
cexec=lambda    cxc,cexc,c,cec:cexc<=''or   cxc[cec][c]==cexc[0]>0<cecxc(cexec(cxc,cexc[1:],cxcxc,cxcec)for cxcxc   in(c-(c>0),c,c+(+1+c<cxec))for  cxcec   in(cec-(cec>0),cec,cec+(+1+cec<cxec))if(cxcxc,cxcec)!=(c,cec))
cxc=range(cxec)
print   cecxc(cexec(c,cec,cexc,cxec)for cexc    in  cxc for cxec    in  cxc)

```

Which takes input like: `['ILAW','BNGE','IUAO','ASRL'], 'LANGUAGE'`

# Answer
> 5 votes
# CJam, score 2, 9351 bytes

```
'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))~'))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))~

```

Try it online! Expects input like:

```
["ILWA" "BNGE" "IUAO" "ASRL"]
LANGUAGE

```

and fits on the Boggle board:

```
' )
~ )

```

Constructs the string `l~:Q,:K;{\:Y;\:X;:C,!_{;QY=X=C0==_{;[X(XX)]K,&[Y(YY)]K,&m*[XY]a-C1>:D;{~DF}%:|}&}|}:F;l:R;K,2m*{~RF}%:|~` then evaluates it as CJam code.

# Answer
> 3 votes
# Clean, score 12 (175 bytes)

(This is almost certainly going to be outgolfed by an esolang and probably normal languages as well.)

```
import StdEnv;>[]_ _ _ _=True;>[c:s]i j n a=i<n&&j<n&&i>=0&&j>=0&&a.[i,j]==c&&or[>s k l n a\\k<-[i-1..i+1],l<-[j-1..j+1]|i<>k||j<>l];$n c a=or[>c i j n a\\i<-[0..n],j<-[0..n]]

```

This defines a function `$ :: Int [Char] {#String} -> Bool` which checks whether the second argument (the word) can be found in the third argument (the board) given the first argument as width.

In the board on which this fits (see below), `*` marks unused places. There are 16 of those, on a board of size 12×12 = 144, meaning 128 are used effectively (an **efficiency** of **175/128 ≈ 1.37**). It may be possible to get the same program on 11×11, but this is all done by hand and very tedious; my boss probably wouldn't be happy if I would try to get it on 11×11.

```
* * & & * * * * * * * ;
s [ n < j * * u r T > v
  > r & i > * e =   [ n
l k o & 0 = n   ; _ ] E
  & a . = ] a j i > [ d
a n & c [ j . + ] s c t
\ k < - i , - . 1 | : S
\ * 1 l . + 1 = i j |
[ i \ . , ] o a < > k t
0 - < \ a   r >   l ] r
. j , * n j [ i c $ ; o
. n ] ] * *     n i m p

```

Try it online (with the program itself as input)!

# Answer
> 3 votes
# Java, score 23, ~~538~~ 507 bytes

NSFW

```
import java.util.function.*;import java.util.stream.*;class B{static BiFunction<char[][],String,BiFunction<Integer,Integer,Byte>>f;{f=(b,s)->(i,j)->{try{if(b[i][j]!=s.charAt(0))return 0;}catch(Exception e){return 0;}if(s.length()<2)return 1;byte t=0;for(int k=9;k-->1;){t|=f.apply(b,s.substring(1)).apply(i+~k%3+1,j+~(k/3)%3+1);}return t;};BiFunction<char[][],String,Byte>g=(b,s)->{int l=b.length;return (byte)IntStream.range(0,l*l).map(i->f.apply(b,s).apply(i%l,i/l)).reduce((x,y)->x+y-x*y).getAsInt();};}}

```

Try it online!

Compiled with JDK 9, but should work with 8.

I didn't know what to do with the imports and static field (which is in fact necessary), so I decided to just take the whole class and stick the lambdas in a initializer. The lambda `g` can then be applied on a 2D array and a string, and returns `1` if the string is in the board and `0` if not (as a `Byte`, 3 characters shorter than `Integer`).

Credit to this guy for a (in my case) shorter than hardcoding way to address neighbouring cells.

Somewhere in the progress of making this monstrosity I got invested in making it work with lambdas it got progressively worse and worse until this happened. It doesn't even get close to the other answers and it is probably not even close to the optimal solution in Java, but hey, it fits pretty neatly on a 23x23 board (which is not optimal, but perhaps closer than the program itself):

```
duce((x,y)->x+y-x*y).ge
e l=b.length;return (bt
rt3+1,j+~(k/3)%3+1);}yA
.n%te t=0;for(int k=rts
)iky0;}catchExcepti9e)I
){~b (b,s)->(i,j)-o;tIn
l>+;n=ring,iFunct>nkunt
/-i1rftass B{stai{ -rt(
i)( u{Slport jatote-nS)
,synt;,cmutil.vinr)> t;
l,lref];i.porfac<y{1tr}
%bpur>[*;amitu. I{r;}e;
i(pt)>].*vaj nuBnie);a}
y=ae)e[m.noitctitft{Bm}
lg.r0traerts.liFe(uti.}
p>))(yhc<noitcnugbr|Fr
pe12tB,regetnI,re[n=ua
at(<Arahc.s=!]j[]i fng
.yg)(htgnel.s(fi};0.ce
)Bnirtsbus.s,b(ylppat(
s,gnirtS,][][rahc<noi0
,b(ylppa.f>-i(pm.)l*l,

```

Of course, at that point there was no point in trying to make that by hand. So as a bonus, here's the (naive) function I used to compress the code onto the board:

```
static char[][] toBoggleBoard(String s, int n) {

    char[][] board = new char[n][n];
    int i = n / 2;
    int j = i;
    int[] d = {1, 0};

    s = s + s.charAt(s.length() - 1); //the last char gets eaten don't ask me why PS editing loop condition does make it work but causes a StringIndexOutOfBoundsException
    board[i][j] = s.charAt(0);
    s = s.substring(1);
    while (s.length() > 0)
    {
        int[] ra = add(d, right(d));
        int[] r = right(d);
        int[] l = left(d);

        if (board[i + d[0]][j + d[1]] > 0)
        {
            if (board[i + d[0]][j + d[1]] == s.charAt(0))
            {
                i += d[0];
                j += d[1];
                s = s.substring(1);
            }
            else
            {
                i += l[0];
                j += l[1];
                board[i][j] = s.charAt(0);
                s = s.substring(1);
            }
        }
        else if (board[i + ra[0]][j + ra[1]] == s.charAt(0))
        {
            i += ra[0];
            j += ra[1];
            s = s.substring(1);
        }
        else if (board[i + r[0]][j + r[1]] > 0)
        {
            i += d[0];
            j += d[1];
            board[i][j] = s.charAt(0);
            s = s.substring(1);
        }
        else
        {
            int[] rb = sub(r, d);
            d = r;
            if (board[i + rb[0]][j + rb[1]] > 0)
            {
                continue;
            }
            else
            {
                i += d[0];
                j += d[1];
                board[i][j] = s.charAt(0);
                s = s.substring(1);
            }
        }
    }

    for (int k = 0; k < board.length; ++k)
    {
        for (int l = 0; l < board.length; ++l)
        {
            if (board[k][l] == 0)
            {
                board[k][l] = ' ';
            }
        }
    }

    return board;
}

static int[] left(int[] d) {
    return new int[]{-d[1], d[0]};
}

static int[] right(int[] d) {
    return new int[]{d[1], -d[0]};
}

static int[] add(int[] x, int[] y) {
    return new int[]{x[0] + y[0], x[1] + y[1]};
}

static int[] sub(int[] x, int[] y) {
    return new int[]{x[0] - y[0], x[1] - y[1]};
}

```

It maps it's input onto a spiralthe snaking implementation didn't work, leaving characters out if possible. It's rather simple so could probably be improved and I forgot to add checking for characters in the backwards-right direction(update: I added it an it produced incorrect results), so I could probably shave off one or two characters but I doubt it's getting on a 22x22.

Edit: Removed 6 spaces in places they didn't need to be. Saved 13 bytes by replacing a check on array indices with a try-catch. Shaved off 12 bytes by moving the board size into an `int`.

# Answer
> 1 votes
# Jelly, 2316 bytes, score 3

```
1111111111111111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111,11111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111,11111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111D§ịØJv

```

Try it online!

Board:

```
1,v
D1J
§ịØ

```

Note: this is a (somewhat) trivial solution. Credit to Lynn for the idea.

Returns a non-empty list if `s` can be found in `B`, and an empty list if not. The added footer helps clarifying that.

---
Tags: code-challenge, decision-problem
---


title: Entropic Quine!

text:
# Question
Title: Entropic Quine!
Your task is to write a program or function which:

* When run for the first time, outputs its source code.
* On subsequent executions, it should output what it output previously, but with one random character change (defined below). It does not have to be a uniformly random change, but every possible change should have a nonzero chance of occurring.

After the first execution, your program will *not* necessarily be a quine anymore; the output will have changed (and the program is free to modify itself as well).

For example, if your quine was `ABCD`, repeatedly running it might print:

```
ABCD
A!CD
j!CD
j!CjD

```

## Specifications

* A character change is either:

+ The insertion of a random character,
    + The deletion of a random character, or
    + A replacement of a character with a new random character. Note that the new character is allowed to be the same as the one it replaces, in which case no change will be made.

Of course, deleting or replacing a character from an empty string is not a valid change.
* Despite this being tagged , the rules against reading your source code do not apply.

You can use any character set as long as it includes the characters used in your source code.

# Answer
> 7 votes
# Python 3, <sup>~~288 270 224 212 195 196 194 180 178~~</sup>168 bytes

```
f=__file__
m=open(f).read()
x=m
print(end=x)
h=hash
k=h(f)
n=k%2
a=h(m)%-~len(x)
x=x[:a]+(not(k%3)*x)*chr(k%127)+x[a+n:]
open(f,'w').write(m.replace("\t",";x=%r\t"%x))

```

Try it online!

After printing the file source code on the first iteration, we append an extra line to set x to the new source code, rather than m.

### Explanation:

```
f=__file__    #Open and read the source code
m=open(f).read()

x=m       #Set x to the source code for the first iteration
x="..."
...
x="..."   #Set x to the latest iteration
          #On the last iteration there's a tab character to mark progress
print(end=x)    #Print the previous iteration's text

#Modify the text
h=hash
k=h(f)            #Generate a random number to use
n=k%2             #Whether the character will be inserted or changed/deleted
a=h(m)%-~len(x) #The index of the change
                         #Add 1 to the range to append new characters, and to avoid mod by 0 in the case of an empty string
x=x[:a]+(not(k%3)*x)*chr(k%127)+x[a+n:]    #Make the change

open(f,'w').write(m.replace("\t",";x=%r\t"%x))   #Modify the source code, adding the new iteration of the source code

```

Assuming `hash` returns a uniformly random number, there is about 1/6 chance of inserting a new character, 1/6 chance of changing an existing character and 2/6 chance of deleting a character. What's the remaining 2/6 chance you ask? Why, it does nothing at all 2/6 of the time!

(Here's a validation program adapted from mbomb007's answer's. Try it online!)

# Answer
> 4 votes
# Python 2, ~~779~~ 801 bytes

Though the challenge was edited to show that reading your source is allowed, I was already creating my solution without that. So, to show that it's possible, I finished it. No reading of the source file:

```
s='s=%r;print s%%s\nfrom random import*;L=4;f=open(__file__,"wa"[L>5]);R=randint\nf.write("\\n".join((s%%s).split("\\n")[1:5:2]).replace("4",`map(ord,s%%s)`))\nif L>5:exec\'b=[];h=%%d\\nwhile~-h:b+=[h%%%%1000];h/=1000\\nwhile b:r,p,n=b[-3:];b=b[:-3];L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]\\nprint"".join(map(chr,L))\'%%1\n\nn=R(0,2);p=R(0,len(L if L>5else s%%s));r=R(0,255);f.write("%%03d"*3%%(n,p,r))';print s%s
from random import*;L=4;f=open(__file__,"wa"[L>5]);R=randint
f.write("\n".join((s%s).split("\n")[1:5:2]).replace("4",`map(ord,s%s)`))
if L>5:exec'b=[];h=%d\nwhile~-h:b+=[h%%1000];h/=1000\nwhile b:r,p,n=b[-3:];b=b[:-3];L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]\nprint"".join(map(chr,L))'%1

n=R(0,2);p=R(0,len(L if L>5else s%s));r=R(0,255);f.write("%03d"*3%(n,p,r))

```

**Try it online!** *(Note that this won't modify the source. You have to run it locally for that to work)*

To show that the transformations work, here is a test program (currently set up to always pick `100` for `r`, and it prints the result for every combination of `n` and `p` for the initial list.)

---

### Explanation:

```
s='s=%r;print s%%s...';print s%s...

```

The first line is your classic quine, but a lot longer to account for what comes after.

```
from random import*;L=4;f=open(__file__,"wa"[L>5]);R=randint

```

Import for random integers. `L` will become of list of ordinals of the source code, but initially it is an integer not used anywhere else in the source to allow for a string replacement. Open the file to write the new source. On later runs, it will open to append instead.

```
f.write("\n".join((s%s).split("\n")[1:5:2]).replace("4",`map(ord,s%s)`))

```

Remove the first and third lines of code. Replace the `4` above with the list of ordinals.

```
if L>5:exec'b=[];h=%d\nwhile~-h:b+=[h%%1000];h/=1000\nwhile b:r,p,n=b[-3:];b=b[:-3];L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]\nprint"".join(map(chr,L))'%1

n=R(0,2);p=R(0,len(L if L>5else s%s));r=R(0,255);f.write("%03d"*3%(n,p,r))

```

In pieces:

* `if L>5:` \- Skips this line on first execution. Later, `L` will be a list, and this will run. I'll explain the `exec` last, because it's not run the first time.
* `n` \- A random number 0-2. This determines which modification occurs (0 = insert, 1 = replace, 2 = delete).
* `p` \- A random position in the list that the modification will occur at.
* `r` \- A random number to insert or replace in the list
* `f.write("%03d"*3%(n,p,r))` \- Append the 3 randoms to the end of the source file. Every run, this will be adding on to an integer that encodes all the changes to the initial source that have occurred.
* `exec'b=[];h=%d...'%1...` \- Get the random numbers (found after `%1` on later runs), apply the changes to the list, and print.
* `while~-h:b+=[h%%1000];h/=1000` \- Build a list of the randoms generated so far, accounting for the leading `1`, which prevents problems with leading zeros.
* `while b:r,p,n=b[-3:];b=b[:-3]` \- Assign the randoms for this iteration.
* `L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]` \- (0 = insert, 1 = replace, 2 = delete)
* `print"".join(map(chr,L))` \- Print the modified source.

# Answer
> 4 votes
# Python 3, ~~205~~ 195 bytes

```
s='print(end=x);h=hash;k=h(x);n=k%2;a=h(s)%-~len(x);x=x[:a]+(not(k%3)*x)*chr(k%127)+x[a+n:];open(__file__,"w").write("s=%r;x=%r;exec(s)"%(s,x))';x='s=%r;x=%r;x=x%%(s,x);exec(s)';x=x%(s,x);exec(s)

```

Try it online!

Wanted to try a version that doesn't read the source code. Turned out not a bad as I thought, and it's only 30 or so bytes behind the version that *does*. The explanation for how it works is mostly the same as the other answer, but it initialises x differently since it can't just read the source code.

# Answer
> 1 votes
# Java 10, 370 bytes

```
String s;v->{if(s==null){s="String s;v->{if(s==null){s=%c%s%1$c;s=s.format(s,34,s);}else{int r=s.length();r*=Math.random();char c=127;c*=Math.random();s=s.substring(0,r)+(c%%3<2?c:%1$c%1$c)+s.substring(r+(c%%3>0?1:0));}}";s=s.format(s,34,s);}else{int r=s.length();r*=Math.random();char c=127;c*=Math.random();s=s.substring(0,r)+(c%3<2?c:"")+s.substring(r+(c%3>0?1:0));}}

```

Try it online.

### Explanation:

```
String s;               // Class-level String variable to store the modifying source code
v->{                    // Method without parameter nor return-type
  if(s==null){          //  If this is the first execution of this function:
    s="String s;v->{if(s==null){s=%c%s%1$c;s=s.format(s,34,s);}else{int r=s.length();r*=Math.random();char c=127;c*=Math.random();s=s.substring(0,r)+(c%%3<2?c:%1$c%1$c)+s.substring(r+(c%%3>0?1:0));}}";
                        //   Set `s` to the unformatted source-code
    s=s.format(s,34,s);}//   And then to the formatted source-code
else{                   //  For any following executions of this function:
  int r=s.length();r*=Math.random();
                        //   Random index in range [0, length_of_modified_source_code)
  char c=127;c*=Math.random();
                        //   Random ASCII character in unicode range [0, 127)
  s=                    //   Replace the current String `s` with:
    s.substring(0,r)    //    The first [0, `r`) characters of the modified source code `s`
    +(c%3<2?            //    If the random option is 0 or 1:
           c:"")        //     Append the random character
        +s.substring(r  //    Append the rest of the modified source code `s`, but:
          +(c%3>0?      //     If the random option is 1 or 2:
             1:0));}}   //      Skip the first character of this second part

```

### General explanation:

**-part:**

* The String `s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* (`%%` is used to format the modulo-`%`).
* `s.format(s,34,s)` puts it all together.

Here a basic Java quine program.

**Challenge part:**

* `String s;` is the source code we'll modify on class-level.
* `int r=s.length();r*=Math.random();` is used to select a random index of the source code in the range `[0, length_of_modified_source_code)`.
* `char c=127;c*=Math.random();` is used to select a random ASCII character (including unprintables) in the unicode range `[0, 126]`.
* `c%3` is used to select a random option of either 0, 1 or 2. Option 0 will add the random character before index `r`; option 1 will replace the character at index `r` with the random character; and option 2 will remove the character at index `r`.

---
Tags: code-golf, quine, stateful
---


title: Convert text to key presses

text:
# Question
Title: Convert text to key presses
I am a robot. I bought this keyboard because of its easy rectangular layout:

```
~`   !1   @2   #3   $4   %5   ^6   &7   *8   (9   )0   _-   +=
tab  Qq   Ww   Ee   Rr   Tt   Yy   Uu   Ii   Oo   Pp   {[   }]    \|
     Aa   Ss   Dd   Ff   Gg   Hh   Jj   Kk   Ll   :;   "'   [-enter-]
          Zz   Xx   Cc   Vv   Bb   Nn   Mm   <,   >.   ?/
                         [========= space =========]

```

To print human text, I need to convert it to commands that my manipulators can interpret. My left manipulator hovers over the `Shift` key. My right manipulator, at the beginning, hovers over the `~` key. The commands that my manipulators understand are:

```
S      : press the shift key
s      : release the shift key
L      : move the right manipulator left by 1
R      : move the right manipulator right by 1
U      : move the right manipulator up by 1
D      : move the right manipulator down by 1
P      : press the key under the right manipulator
p      : release the key by the right manipulator

```

Write code to convert any ASCII message to a list of commands. The input can contain any number of the 95 printable ASCII characters; possibly also TAB and newline characters. The output should be the list of the commands to the manipulators.

So, for example, to type `Hello World!`, the commands are

```
SRRRRRRDDPp
sLLLUPp
RRRRRRDPp
Pp
UPp
LLLLDDDPp
SLLLUUUPp
sRRRRRRRPp
LLLLLPp
RRRRRDPp
LLLLLLPp
SLLUUPp

```

I reset the manipulators to initial state before printing each message.

There are some mechanical hazards that should be avoided by proper programming:

1. No moving (`LRUD`) allowed when printing (`P`) is engaged
2. No jamming of manipulators: when a manipulator is engaged (`S` or `P`), the next command for this manipulator should be disengaging (`s` or `p`), and vice-versa
3. No unnecessary shifting: between each two shift (`s`, `S`) commands, there should be a `P` command

So, to print `~~`, commands `SPpPp` are valid, while `SPpsSPp` are not
4. No moving out of bounds: no movement command should try to move the right manipulator more than 13 spaces to the right or 4 to the bottom of the initial position (or any spot to the top or left)

Additional notes:

* Pressing a disabled key (command sequence like `DDPp`) results in no keys pressed and is allowed.
* Pressing `Shift`+`Tab` has no effect, but `Shift`+`Space` and `Shift`+`Enter` have the same effect as without `Shift`.
* Pressing on any spot on the space bar and the `Enter` key has the same effect.
* Whitespace keys in output have no meaning, but can be used to format it in a beautiful way.

# Answer
> 5 votes
# Python 2, ~~338~~ ~~337~~ ~~335~~ ~~331~~ 325 bytes

x=y=s=0
for c in input():p='`1234567890-=`	qwertyuiop[]|`asdfghjkl;\'\n```zxcvbnm,./``````` ~!@#$%^&*()_+~~QWERTYUIOP{}\\~ASDFGHJKL:"\n~~~ZXCVBNM<>?~~~~~~~ '.find(c);S=[p>61,s][c in' \n'];p%=62;Y=p/14;X=[max(x,12),min(max(x,5),10),p%14]['\n '.find(c)];print'sS'[S]*(s^S)+'LR'[X>x]*abs(X-x)+'UD'[Y>y]*abs(Y-y)+'Pp';x,y,s=X,Y,S
</code></pre>

Try it online!

---

Moves directly from each character to the next.

Explanation:

* `S=[c in K,s][c in' \n']`, checks if the next character should be Upper- or lowercase. If `c` is a space or newline, the case remains the same.
* `X=[max(x,12),min(max(x,5),10),p%15]['\n '.find(c)]`. If `c` is a space or newline, the closest x-coordinate to the current is chosen(as the keys span multiple columns)
* `print'sS'[S]*(s!=S)+'LR'[X>x]*abs(X-x)+'UD'[Y>y]*abs(Y-y)+'Pp'`, prints the case switch, the number of x-coordinate moves, the number of y-coordinate moves, and finally `Pp`, for each character

---

Shorter version, if the shortest path is not required:

# Python 2, ~~294~~ ~~293~~ ~~291~~ ~~287~~ 281 bytes

<pre><code>x=y=s=0
for c in input():p='`1234567890-=`	qwertyuiop[]|`asdfghjkl;\'\n```zxcvbnm,./``````` ~!@#$%^&*()_+~~QWERTYUIOP{}\\~ASDFGHJKL:"\n~~~ZXCVBNM<>?~~~~~~~ '.find(c);S=[p>61,s][c in' \n'];p%=62;X,Y=p%14,p/14;print'sS'[S]*(s^S)+'LR'[X>x]*abs(X-x)+'UD'[Y>y]*abs(Y-y)+'Pp';x,y,s=X,Y,S

Try it online!

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

Takes input as an array of characters.

```
s=>s.map(c=>(y=i-(i=(j=`\`~1!2@3#4$5%6^7&8*9(0)-_=+00\t0qQwWeErRtTyYuUiIoOpP[{]}|\\00aAsSdDfFgGhHjJkKlL;:'"
${1e6}zZxXcCvVbBnNmM,<.>/?${1e13} `.indexOf(c))>>1),g=k=>'LRUD'[n=k?y/14:y%14,k^=n<0].repeat(n<0?-n:n))()+g(2)+['sS'[j-s&c!=' '&c!=`
`?s^=1:2]]+'Pp',i=s=0)

```

Try it online!

# Answer
> 1 votes
# .COM opcode, ~~108~~ 104 bytes

```
0000h: B4 00 CD 16 BE 50 01 83 C6 03 3A 24 77 F9 0F B6
0010h: DC 03 5C 01 B4 02 CD 16 B4 02 68 00 01 A8 03 B2
0020h: 53 74 08 81 36 20 01 20 01 CD 21 84 DB 74 0B 4B
0030h: B2 52 E8 F4 FF B2 4C CD 21 C3 84 FF 74 0C FE CF
0040h: B2 44 E8 E4 FF B2 55 CD 21 C3 B2 50 CD 21 B2 70
0050h: CD 21 C3 0D FE 00 1B F1 00 1C F0 01 28 E3 01 29
0060h: D7 FF 35 D6 02 39 CC 03

```

Take input from keyboard with CapsLock off

Badly golfed though

```
        org 100h
        mov ah, 0
        int 16H
        mov si, table-3
tabing: add si, 3
        cmp ah, [si]
        ja tabing
        movzx bx, ah
        add bx, [si+1]
        mov ah, 2
        int 16H
        mov ah, 2
        push 100H
        test al, 3
        mov dl, 'S'
cmd:    jz fun
        xor [cmd-1], word 0x120
        int 21H
fun:    test bl, bl
        jz bl0
        dec bx
        mov dl, 'R'
        int 21H
        call fun
        mov dl, 'L'
        int 21H
        ret
bl0:    test bh, bh
        jz bh0
        dec bh
        mov dl, 'D'
        int 21H
        call fun
        mov dl, 'U'
        int 21H
        ret
bh0:    mov dl, 'P'
        int 21H
        mov dl, 'p'
        int 21H
        ret
macro key begin, end, U, L {
        db end
        dw U*256+L-begin
}
table:
        key 0x02, 0x0D, 1, 0
        key 0x10, 0x1B, 1, 1
        key 0x1C, 0x1C, 2, 12
        key 0x1E, 0x28, 2, 1
        key 0x29, 0x29, 0, 0
        key 0x2C, 0x35, 3, 2
        key 0x39, 0x39, 4, 5

```

---
Tags: code-golf, keyboard
---


title: Tips for golfing in MATL

text:
# Question
Title: Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

# Answer
> 8 votes
# Know the predefined literals

Although some of them keep information when copied to the clipboard, they all have a predefined value.

* `F`, pushes **0** (actually *False*)
* `T`, pushes **1** (actually *True*)
* `H`, pushes **2** (predefined clipboard value)
* `I`, pushes **3** (predefined clipboard value)
* `K`, pushes **4** (predefined clipboard value)
* `J`, pushes **0 + 1j** (predefined clipboard value)

Not sure if I have covered all predefined values though.

# Answer
> 6 votes
# Move things from after the loop to within the loop, to exploit implicit end

Loop `end` statements, `]`, can be **left out** if there is no code after them. They are filled by the MATL parser implicitly.

So if you can move things from after the loop to within the loop you can to save the final `]`.

As a specific example, the following code finds how many trailing zeros there are in the factorial of a number `N` (see it here):

* The code loops from `1` to `N`.
* For each of those numbers it computes its prime factors, and determines how many times `5` is present.
* The answer is the accumulated number of times `5` appears (this works because for each `5` there is at least one `2`).

The first idea was `:"@Yf5=]vs` (note that there are statements after the loop):

```
:      % Range from 1 to implicit input
"      % For each number in that vector
  @    %   Push that number
  Yf   %   Vector of prime factors (with repetitions)
  5=   %   True for entries that equal `5`, and `false` for the rest
]      % End for
v      % Concatenate all vectors as a column vector
s      % Sum. Implicitly display

```

Since `v` by default concatenates all stack contents, it can be moved into the loop. And since addition is associative, `s` can be moved too. That leaves `]` at the end of the code, and thus it can be omitted: `:"@Yf5=vs`:

```
:      % Range from 1 to implicit input
"      % For each number in that vector
  @    %   Push that number
  Yf   %   Vector of prime factors (with repetitions)
  5=   %   True for entries that equal `5`, and `false` for the rest
  v    % Concatenate all vectors so far as a column vector
  s    % Sum. Inplicitly end loop and display

```

# Answer
> 6 votes
# The `&` Meta-Function (Alternative Input / Output Specification)

The traditional way to specify the number of input arguments to pass to a function is to use the `$` meta-function

```
2$:     % Two-input version of :

```

Similarly, to specify the number of output arguments you can use the `#` meta-function specifying either the number of output arguments,

```
2#S     % Two-output version of sort

```

or if you pass a number that is *greater than* the number of output arguments defined for a function, *only* the `mod(N, numberOfOutputs) + 1` output is supplied.

```
4#S     % Get only the second output of sort

```

You can additionally specify a logical array as the input to `#` to retrieve only specific output arguments.

```
TFT#u   % Three output version of unique and discard the second output

```

All of these input / output specifications are handy *but* they drive up your byte-count very quickly. To deal with this, MATL introduced the `&` meta-function in the 17.0.0 release. This `&` meta-function acts as a shortcut for a particular input or output specification for a function. Let's see what that means.

In our example above, we wanted to use the two-input version of `:` (creates a vector of equally-spaced values). While the default number of input arguments to `:` is `1` (creates an array from `[1...N]`), it is *very* common that a user would want to specify the start value of the range which requires the second input. So for `:`, we have defined `&` to be a shortcut for `2$`.

```
10      % Push 10 to the stack
12      % Push 12 to the stack
2$:     % Create an array: [10, 11, 12]

```

Now becomes the following, *saving a byte*!

```
10 12 &:

```

## How can we determine what the alternate number of arguments is?

The input / output specification that `&` translates to is **function specific** such that we optimize the byte-savings.

The input / output argument section of the help description for each function has been updated to indicate what this alternative number of inputs / outputs is (if any). The possible number of input or output arguments are displayed as a range and the default values for each are shown in parentheses. The input / output spec that can be substituted with `&` is shown after the `/` character within the parentheses.

Here is the input / output argument section of the help description for `:`

```
 +- Min-Max range of # of inputs
 |        +----- Alt. Default # of inputs
 |        |
 V        V
1--3 (1 / 2); 1 <--- Possible / Default # of outputs
      ^
      |
  Default # of inputs

```

## How did you determine what `&` means for each function?

Very carefully. Using the StackExchange API, we were able to download all MATL answers that have ever been used in a PPCG challenge. By parsing each of the answers, we were then able to determine the frequency with which each input / output spec was used for each function. Using this information we were then able to objectively identify the input / output specification the `&` meta-function should represent for each function. Sometimes there was no clear winner, so many functions currently don't have `&` defined.

Here is the script we used (unfortunately it's written in MATLAB and *not* MATL).

And here is an example of the histogram of `$`/`#` usage

# Answer
> 6 votes
# Get familiar with MATL's truthy/falsy definitions

While `true` (`T`) and `false` (`F`) clearly represent truthy and falsy output, respectively, the widely agreed upon definition of truthy/falsy gives us a little bit more flexibility in MATL.

The definition states:

```
if (x)
    disp("x is truthy");
else
    disp("x is falsy");
end

```

So we can write a quick MATL truthy/falsy test which will loop through all inputs and display whether they were considered to be truthy or falsy

```
` ? 'truthy' } 'falsey' ]DT

```

Here is an online version.

**What this means in MATL**

What this actually translates to in MATL (and therefore in MATLAB and Octave) is that a condition is considered to be true if **if it is non-empty and real components of all its values are non-zero**. There are two parts to this that should be emphasized.

1. **Non-zero**: This means precisely that, not equal to zero (`==`). This includes positive numbers, negative numbers, non-null characters, etc. You can easily check by converting a given value to a `logical` value (`g`) or you can use `~~`

```
F           % Falsy
T           % Truthy
0           % Falsy
1           % Truthy
2           % Truthy
-1          % Truthy
'a'         % Truthy
' '         % Truthy (ASCII 32)
char(0)     % Falsy  (ASCII 0)

```
2. **All values**: Typically we think of scalars as being true or false, but in MATL, we can evaluate scalars, row vectors, column vectors, or even multi-dimensional matrices and they are considered to be truthy if and only if every single value is non-zero (as defined above), otherwise they are falsy. Here are a few examples to demonstrate

```
[1, 1, 1]           % Truthy
[1, 0, 0]           % Falsey
[1, 1, 1; 1, 1, 1]  % Truthy
[1, 0, 1; 1, 1, 1]  % Falsey
'Hello World'       % Truthy

```

The one edge case, as mentioned above, is an empty array `[]`, which is always considered to be falsy (example)

**How can I use this to golf better?**

If the challenge simply mentions that your output should be truthy or falsy, you can likely exploit the definition above to shave a few bytes off of your answer. To save confusion, it is recommended that you include a link to the online truthy/falsy test above in your answer to help explain how MATL truthy/falsy values work.

A couple of specific examples:

* An answer ending in `A`. If the challenge requires a truthy or falsy output and you end your answer in `all` (`A`) to create a scalar, you can remove this last byte and your answer will remain correct (unless the output is `[]` since `[]` is `false` but `[]A` is `true`).
* Ensuring that an array contains only one unique value: Uses `&=` in place of `un1=`. If all values in an array are equal, a broadcasted element-wise equality comparison will yield an `N x N` matrix of all ones. If all values are not equal, this matrix will contain some `0` values and therefore be considered falsy.

# Answer
> 5 votes
# Implicit Input

Most functions accept some number of input. These inputs are taken from the top of the stack. If the top of the stack does not contain enough arguments, it will draw the remaining argument from the input. (See Section 7.3 in the documentation) I'd like to cite the original explanation:

> Implicit inputs can be viewed as follows: the stack is indefinitely extended below the bottom, that is, at positions 0, −1, −2, ...with values that are not initially defined, but are resolved on the fly via implicit input. These inputs are asked from the user only when they are needed, in the order in which they are needed. If several inputs are required at the same time they follow the normal stack order, that is, the input that is deepest in the (extended) stack is entered first.

# Answer
> 5 votes
# For loop of size n-1

Consider replacing

```
tnq:"...

```

with

```
td"...

```

to save up to an entire byte or more.

# Answer
> 4 votes
# Logical arrays can often be used as numeric arrays

You can often use "`TF`" notation instead of array literals of zeros and ones. For example, `FTF` is the same as `[0,1,0]`, only that `FTF` produces `logical` values, not `double` values. This is usually not a problem, as any arithmetical operation will treat logical values as numbers. For example, `FTFQ` gives `[1,2,1]` (`Q` is "increase by 1").

In some cases, conversion of a number to binary may be shorter. For example, `[1,0,1]`, `TFT` and `5B` are the same; again with the caution that the latter two are `logical` values.

---

A case where the difference between `TF` (logical) and `[1 0]` (numeric) matters is when used as indices. An array of type `logical` used as an index means: pick elements corresponding to `T`, discard those corresponding to `F`. So `[10 20]TF)` produces `10` (select the first element), whereas `[10 20][1 0])` produces `[10 20]` (the index `[1 0]` has the interpretation of `1:end`, that is, pick all elements of the array).

# Answer
> 3 votes
# Some functions are extended compared with MATLAB or Octave

If you come from MATLAB or Octave, you'll find many MATL functions are similar to functions in those languages. But in quite a few of them functionality has been extended.

As an example, consider MATLAB's `reshape` function, which in MATL corresponds to `e`. The code snippets `reshape([10 20 30 40 50 60], 2, 3)` and `reshape([10 20 30 40 50 60], 2, [])` respectively mean "reshape the row vector `[10 20 30 40 50 60` into a 2×3 matrix", or "into a 2-row matrix with as many columns as needed". So the result, in both cases, is the 2D array

```
10    30    50
20    40    60

```

Something like `reshape([10 20 30 40 50 60], 2, 2)` or `reshape([10 20 30 40 50 60], 5, [])` would give an error because of incompatible sizes. However, MATL will remove elements in the first case (try it online!) or fill with zeros in the second (try it online!) to produce, respectively,

```
10 30
20 40

```

and

```
10 60
20  0
30  0
40  0
50  0

```

Other functions that have extended functionality in comparison with their MATLAB counterparts are (non-exhaustive list) `S` (`sort`), `Yb` (`strsplit`), `m` (`ismember`), `h` (`horzcat`), `v` (`vertcat`), `Zd` (`gcd`), `Zm` (`lcm`), `YS` (`circshift`), `YA` (`dec2base`), `ZA` (`base2dec`), `Z"` (`blanks`).

# Answer
> 3 votes
# Shorter way to define an empty numeric array, if the stack is empty

To push an empty numeric array you normally use `[]`. However, if the stack is empty you can save a byte using `v`. This function by default concatenates all stack contents vertically, so if the stack is empty it produces the empty array.

You can see it in action for example here.

# Answer
> 2 votes
# Get the index of the first non-zero element, if any

The `f` function gives the indices of all non-zero elements of an array. Often you want the index of the *first* nonzero element. That would be `f1)`: apply `f` and pick its first element. But if the original array doesn't contain any non-zero value `f` will output an empty array (`[]`), and trying to pick its first element will give an error.

A common, more robust requirement is to obtain the index of the first element *if there is at least one*, and `[]` otherwise. This could be done with an `if` branch after `f`, but that's byte-expensive. A better way is `fX<`, that is, apply the minimum function `X<` to the output of `f`. `X<` returns an empty array when its input is an empty array.

Try it online! (Note that an empty array is not displayed at all). Or see an example of this at work here.

# Answer
> 2 votes
# Efficiently defining numeric array literals

Here are a few ways that can be used to save bytes when defining numeric array literals. Links are given to example answers that use them. These have been obtained using the analytics script created by @Suever.

### Concatenation and predefined literals

For arrays with small numbers you can sometimes use concatenation (functions `h` and `v`), as well as predefined literals to avoid using spaces as separators: compare `[2 4]`, `2 4h` and `2Kh`, all of which define the array `[2 4]`. Similarly, `2K1v` with an empty stack defines `[2; 4; 1]`. Example.

### Letters within numeric array literals

For slightly larger numbers you can save spaces exploiting the fact that some letters have numeric meanings within array literals. So instead of `[3 5 2 7;-4 10 12 5]` you can use `[IAHC;dX12A]`. Example.

Specifically, within array literals,

* `O`, `l`, `H` `I` `K` have their usual meanings `0`, ..., `4`
* `A`, ..., `E` mean `5`, ..., `9`
* `X` means `10`
* `a`, ... `d` mean `-1`, ..., `-4`
* `J` and `G` mean `1j` and `-1j`
* `P` means `pi`
* `Y` means `inf`
* `N` means `NaN`.

### String and consecutive differences

For larger numbers, defining a string and computing its consecutive differences (with `d`) can help: instead of `[20 10 35 -6]` you can use `'!5?b\'d`. This works because `d` uses the code points of the chars for computing the differences. Example.

# Answer
> 1 votes
# Generate a range as long as a given array

*TL;WR*: use `f` instead of `n:` if the array only has nonzero elements.

---

It is often the case that one needs to generate an array `[1 2 ... L]` where `L` is the number of elements of a given array. The standard way to do that is `n:`. For example, the code `tn:*` takes a numeric vector as input and computes each entry multiplied by its index.

If the given array is *guaranteed to only contain nonzero entries* (for example, it is formed by positive integers, or is a string with printable characters), `n:` can be replaced by `f`, which produces an array with the indices of nonzero entries. So the above code becomes `tf*`, which saves 1 byte.

Some more elaborate examples: , , .

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


title: Create an "H" from smaller "H"s

text:
# Question
Title: Create an "H" from smaller "H"s
# Challenge

Create a function or program that, when given an integer `size`, does the following:

If `size` is equal to 1, output

```
H H
HHH
H H

```

If `size` is greater than 1, output

```
X X
XXX
X X

```

where `X` is the output of the program/function for `size - 1`

(If you prefer, you may have the base case correspond to `0`, so long as you specify in your answer)

Any of the following output formats are acceptable, whichever is more convenient for you:

* A string of the required structure with any two distinct characters corresponding to `H` and `space`
* A two-dimensional array with the required structure, with any two distinct values corresponding to `H` and `space`
* An array/list of strings, with one line of the output in each string, with any two distinct values corresponding to `H` and `space`

Leading spaces are allowed, as long as there is a constant amount of leading spaces on each line. The two distinct output characters can be dependent on anything you choose, as long as they are different.

Specify what output format your code is returning.

# Test Cases

`1`

```
H H
HHH
H H

```

`2`

```
H H   H H
HHH   HHH
H H   H H
H HH HH H
HHHHHHHHH
H HH HH H
H H   H H
HHH   HHH
H H   H H

```

`3`

```
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H HH HH HH HH HH HH HH HH H
HHHHHHHHHHHHHHHHHHHHHHHHHHH
H HH HH HH HH HH HH HH HH H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H

```

This is , so the lowest byte count for each language wins!

# Answer
> 29 votes
# Wolfram Language (Mathematica), 46 bytes

```
Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&

```

Returns a 2d array of `0`s and `1`s.

Try it online!

# Answer
> 21 votes
## Canvas, ~~14~~ 12 bytes

```
H；［⌐⌐∔＊×∔；３＊＋

```

Try it here!

Explanation:
```
Code    |Instruction                                                         |Stack
--------+--------------------------------------------------------------------+-------------------------
        |Push input to stack (implicit)                                      |I
H       |Push "H" to stack                                                   |I,"H"
；      |Swap the top two stack items                                        |"H",I
［      |The following ToS (input) times:                                    |X
    ⌐⌐  |Duplicate ToS (result from last loop ("H" if first loop)) four times|X,X,X,X,X
    ∔   |Join vertically                                                     |X,X,X,X\nX
    ×   |Prepend                                                             |X,X,XX\nX
    ∔   |Join vertically                                                     |X,X\nXX\nX
    ；  |Swap top two stack items                                            |X\nXX\nX,X
    ３＊|Repeat three times vertically                                       |X\nXX\nX,X\nX\nX
    ＋  |Join horizontally                                                   |X<space>X\nXXX\nX<space>X
        |End loop (implicit)                                                 |X
        |Print ToS (implicit)                                                |

```

Where `I` is the input, `X` is the pattern generated by the previous loop ("H" for the first loop), and `<space>` is the empty space on the first and third row of the pattern, added implicitly by .

*-2 bytes thanks to dzaima!*

# Answer
> 19 votes
# MATL, ~~12~~ 11 bytes

```
t:"[ACA]BX*

```

Given input `n`, this outputs a matrix containing `0` and `n`.

Try it online!

To convert this into a character matrix of `H`and space add `g72*c` in the header. Try it online too!

Or add `]1YC` to see the matrix displayed graphically. Try it at MATL Online!

### Explanation

```
t          % Input (implicit): n. Duplicate
:          % Range. Gives the array [ 1 2 ... n]
"          % For each (that is, do n times)
  [ACA]    %   Push the array [5 7 5]
  B        %   Convert to binary. Gives the 3×3 matrix [1 0 1; 1 1 1; 1 0 1]
  X*       %   Kronecker product
           % End (implicit). Display (implicit)

```

# Answer
> 16 votes
# Stax, 16 15 bytes

```
╛c_mê║6{│◙ÖmπV"

```

Run and debug it

This is the ascii representation of the program with comments. This program builds up the H sideways, and then transposes once at the end.

```
'H]                 ["H"]
   {         },*    repeat block specified number of times
    c               copy the matrix
     {3*m           triplicate each row
         |S         surround; prepend and append like b + a + b
           |C       horizontally center rows with spaces
                M   transpose back to original orientation
                 m  output each row

```

Bonus 14 byte program \- uses its input as the output character. Theoretically, this would not produce the right shape at 10, since it has 2 digits, but attempting to run that crashes my browser.

# Answer
> 11 votes
# Ruby, 72 bytes

Output is a list of strings, one string per line.

```
f=->n{n<1?[?H]:[*a=(x=f[n-1]).map{|i|i+' '*i.size+i},*x.map{|i|i*3},*a]}

```

Try it online!

# Answer
> 11 votes
# APL (Dyalog Classic), 14 bytes

```
×/¨∘.≥⍨2|,⍳⎕⍴3

```

Try it online!

evaluated input n

`,⍳⎕⍴3` all n-tuples with elements from 0 1 2

`2|` mod 2

`×/¨∘.≥⍨` form a matrix by comparing every pair of tuples a and b - if all elements of a are ≥ the corresponding elements of b, it's a 1, otherwise 0

# Answer
> 10 votes
# Haskell, 50 bytes

```
f 0=[[1]]
f n=[x++map(*c)x++x|c<-[0,1,0],x<-f$n-1]

```

Try it online!

Makes a grid of 0's and 1's. One character longer for spaces and H's.

# Haskell, 51 bytes

```
f 0=["H"]
f n=[x++map(min c)x++x|c<-" H ",x<-f$n-1]

```

Try it online!

# Answer
> 9 votes
# Jelly, ~~17~~ ~~16~~ 15 bytes

```
381B«€s3Z€ẎF€µ¡

```

This is a full program that prints a 2D array of **1**'s and **0**'s.

Try it online! or see the output with **H**'s and spaces.

# Answer
> 8 votes
# Java (JDK), 126 bytes

```
n->{int s=1,H[][]=new int[n+=Math.pow(3,n)-n][n],x;for(;s<n;s*=3)for(x=n*n;x-->0;)H[x/n][x%n]|=~(x/n/s%3)&x%n/s%3&1;return H;}

```

Try it online!

Returns an `int[][]` with `0` for `H` and `1` for `space`. This actually "carves" a wall of `H`'s instead of "piling" `H`'s.

## Explanations

```
n->{                        // An int to int[][] lambda function
  int s=1,                  //  size of the carvings.
      H[][]=new int[n+=Math.pow(3,n)-n][n],
                            //  change n to 3^n, through +=...-n to avoid an explicit cast
                            //  and create the 2D array to return, filled with 0s
      x;                    //  counter for the 2D array
  for(;s<n;s*=3)            //  for each size
    for(x=n*n;x-->0;)       //   for each cell
      H[x/n][x%n] |=        //     assign 1 to a cell of the array if...
        ~(x/n/s%3)          //      it is located in the "holes" of the H
        &x%n/s%3            //
        &1;                 //
  return H;                 //  return the array
}                           // end the lambda

```

## Credits

# Answer
> 8 votes
# SOGL V0.12, 13 bytes

```
┌.{³2∙⁴┼+;3∙┼

```

Try it Here!

# Answer
> 8 votes
# , 64 bytes

```
function(n)Reduce(`%x%`,rep(list(matrix(c(1,1,1,0,1,0),3,3)),n))

```

Try it online!

Reduces by Kronecker product, as a shameless port of Luis Mendo's answer.

The footer prints the result nicely, but this is an anonymous function which returns a `matrix` of `1` for `H` and `0` for space.

# Answer
> 7 votes
# , 22 bytes

```
éHÀñäLgvr PGï3PkyHGpH

```

Try it online!

Hexdump:

```
00000000: e948 c0f1 e416 4c67 7672 2050 47ef 3350  .H....Lgvr PG.3P
00000010: 6b79 4847 7048                           kyHGpH

```

This is basically the exact same approach as the Sierpinski carpet and The Fractal Plus on Anarchy Golf.

# Answer
> 7 votes
# Python 2, 70 bytes

```
f=lambda r:-r*'H'or[x+[x,' '*3**r][b]+x for b in 1,0,1for x in f(r-1)]

```

Try it online!

Function outputs a list of strings.

---

# Python 2, 84 bytes

```
r=input()
for i in range(3**r):x,s=' H';exec"s+=[x,s][i%3%2]+s;x*=3;i/=3;"*r;print s

```

Try it online!

Uses the same template as other 3\*3 fractal patterns:

# Answer
> 6 votes
# , ~~25~~ 22 bytes

```
,./^:2@(*/#:@5 7 5)^:]

```

Try it online!

```
        */               multiply by
          #:@5 7 5       the binary matrix shaped like H
,./^:2                   assemble the 4-dimensional result into a matrix
                   ^:]   do it input times

```

# Answer
> 6 votes
## Haskell, ~~73~~ ~~67~~ ~~64~~ 55 bytes

```
g#f=g<>f<>g
w=map.(id#)
(iterate(w(>>" ")#w id)["H"]!!)

```

This works only with the latest version of `Prelude`, because it exports `<>` from `Data.Semigroup`. To run it on TIO, add an import as done here: Try it online!

```
g#f=              -- function # takes two functions g and f and a list s
                  -- and returns
   g <> f <> g    -- g(s), followed by f(s) and another g(s)

w=                -- w takes a function and a list of lists
                  -- (both as unnamed parameters, because of pointfree style,
                  -- so let's call them f and l)
  map.(id#)       -- return map(id#f)l, i.e. apply (id#f) to every element of l

  w(>>" ")#w id   -- this partial application of # is a function that
                  -- takes the missing list (here a list of lists)
                  -- remember: (>>" ") is the function that replaces every element
                  -- of a list with a single space

iterate(   )["H"] -- starting with a singleton list of the string "H"
                  -- which itself is a singleton list of the char 'H'
                  -- repeatedly apply the above function
              !!  -- and pick the nth iteration

Example for ["H H", "HHH", "H H"], i.e.

   H H
   HHH
   H H

call the iterated function:
                    ( w(>>" ")         # w id       ) ["H H","HHH","H H"]

expand w:           ( map(id#(>>" "))  # map(id#id) ) ["H H","HHH","H H"]

expand outermost #: map(id#(>>" "))["H H","HHH","H H"] ++
                    map(id#id)     ["H H","HHH","H H"] ++
                    map(id#(>>" "))["H H","HHH","H H"]

expand map:         [(id#(>>" "))"H H",   (id#(>>" "))"HHH",   (id#(>>" "))"H H"] ++
                    [(id#id)     "H H",   (id#id)     "HHH",   (id#id)     "H H"] ++
                    [(id#(>>" "))"H H",   (id#(>>" "))"HHH",   (id#(>>" "))"H H"]

expand other #:     ["H H"++"   "++"H H", "HHH"++"   "++"HHH", "H H"++"   "++"H H"] ++
                    ["H H"++"H H"++"H H", "HHH"++"HHH"++"HHH", "H H"++"H H"++"H H"] ++
                    ["H H"++"   "++"H H", "HHH"++"   "++"HHH", "H H"++"   "++"H H"]

collaps ++:         ["H H   H H", "HHH   HHH", "H H   H H",
                     "H HH HH H", "HHHHHHHHH", "H HH HH H",
                     "H H   H H", "HHH   HHH", "H H   H H"]

which is printed line by line:

  H H   H H
  HHH   HHH
  H H   H H
  H HH HH H
  HHHHHHHHH
  H HH HH H
  H H   H H
  HHH   HHH
  H H   H H

```

Edit: -9 bytes thanks to @Potato44.

# Answer
> 6 votes
# Vim - 66 56 54 bytes

`A` `@` `c` `H` `esc` `"` `r` `d` `^` `q` `c` `{` `ctrl-v` `}` `"` `a` `y` `g` `v` `r` `space` `g` `v` `d` `"` `a` `P` `P` `"` `a` `P` `V` `G` `"` `b` `y` `P` `g` `v` `ctrl-v` `$` `d` `"` `a` `P` `.` `.` `G` `"` `b` `p` `q` `@` `r`

The input is taken as a number in the buffer.

# Answer
> 5 votes
# Perl 5, ~~46~~ ~~44~~ ~~43~~ ~~41~~ 40 bytes

1 based counting. Uses `0` and `1` for `H` and space, has a leading `1` (space)

```
say//,map/$'/^1,@;for@;=glob"{A,.,A}"x<>

```

Based on a classic idea by mtve.

Try it online!

# Answer
> 4 votes
# Python 2, 143 bytes

```
def g(a,x,y,s):
	if s:s/=3;[g(a,x+k/3*s,y+k%3*s,s)for k in 0,2,3,4,5,6,8]
	else:a[x][y]=1
def f(s):s=3**s;a=eval("s*[0],"*s);g(a,0,0,s);print a

```

Try it online!

-30 bytes thanks to recursive

wrapper code is for nice formatting. it works fine if you remove it

# Answer
> 4 votes
# APL (Dyalog Unicode), 38 34 bytesSBCS

```
({(⍵,(0×⍵),⍵){⍺⍪⍵⍪⍺}⍵,⍵,⍵}⍣⎕)1 1⍴1

```

Output is a 2-dimensional array with `1` representing H and `0` representing space.

Try it online!

# Answer
> 4 votes
# Charcoal, ~~30~~ 29 bytes

```
HＦＥＮＸ³ι«Ｊ⁰¦⁰Ｃ⁰ιＣιιＴ⊗ι⊗ι‖ＯＯ→↓ι

```

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

```
H

```

Print the original `H`.

```
ＦＥＮＸ³ι«

```

Loop over the first `size` powers of 3.

```
Ｊ⁰¦⁰

```

Move the cursor back to the origin. `Trim` needs this, as both the original printing of the `H` and the reflection below move the cursor.

```
Ｃ⁰ι

```

Copy the previous iteration downwards, creating a domino.

```
Ｃιι

```

Copy the result down and right, creating a tetromino.

```
Ｔ⊗ι⊗ι

```

Trim the canvas down to an `L` shape triomino.

```
‖ＯＯ→↓ι

```

Reflect the canvas horizontally and vertically with overlap, completing the iteration.

Charcoal is better at some fractals than others. Here's a similar idea, but in almost half the size:

```
HＦＮ«⟲Ｃ²⁶‖ＯＯLＸ³ι

```

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

# Answer
> 4 votes
# PHP 7, ~~125~~ 109 bytes

a different approach: Instead of nesting and flattening the result recursively, this just loops through the rows and columns and uses a 3rd loop to find out if to print `H` or `_`.

Edit: Saved a lot by combining the row/column loops to one, though it took a bit to get the decrease for the inner loop correct. Requires PHP 7 for the power operator.

Try them online!

---

```
for($z=3**$argn;$z*$z>$q=$p;print$c."
"[++$p%$z])for($c=H;$q;$q-=$q/$z%3*$z,$q/=3)if($q%3==1&&$q/$z%3-1)$c=_;

```

prints the result. Run as pipe with `-nR`.

## qualified function, ~~147~~ 130 bytes

```
function r($n){for($z=3**$n;$z*$z>$q=$p;$r.=$c."
"[++$p%$z])for($c=H;$q;$q-=$q/$z%3*$z,$q/=3)if($q%3==1&&$q/$z%3-1)$c=_;return$r;}

```

returns a single string. Run with default config (no `php.ini`).

# Answer
> 3 votes
# Jelly, 25 bytes

```
,’b3U×"3S_4A1e
3*çþ`ị⁾ HY

```

Try it online!

---

Although this is longer than the existing Jelly submission, it tries to generate each character independently just from the coordinate.

In particular, if the coordinate is `(x,y)` (1-indexing), the first link returns `0` and `1` corresponds to `H` and  respectively.

```

,                Pair. Get (x,y)
 ’               Decrement. Get (x,y) (0-indexing)
  b3             Convert to base 3 digits.
    U            Upend. So next operations can pair the corresponding digits.
     ×"3         Multiply the first element (list) by 3.
        S        Sum (corresponding digit together). Let the sum be **s**.
         _4A1e   Check if any of **abs(s-4)** is 1. Equivalently, check
                 if there is any **3** or **5** in the list of **s**.

```

Also, the 5 bytes `ị⁾ HY` are used for formatting, so this program (20 bytes) is also valid (but the output doesn't look as nice):

```
,’b3U×"3S_4A1e
3*çþ`

```

# Answer
> 3 votes
# T-SQL, ~~267~~ 261 bytes

```
DECLARE @N INT=3DECLARE @ TABLE(I INT,H VARCHAR(MAX))INSERT @ VALUES(1,'H H'),(2,'HHH'),(3,'H H');WITH
T AS(SELECT 1 A,3 P,I J,H S FROM @ UNION ALL SELECT A+1,P*3,J*P+I,REPLACE(REPLACE(S,' ','   '),'H',H)FROM @,T
WHERE A<@N)SELECT S FROM T WHERE A=@N ORDER BY J

```

# Answer
> 2 votes
# PHP 7, 153 bytes

```
    function p($n){$r=["H H",HHH,"H H"];if(--$n)foreach(p($n)as$s){$r[+$i]=$r[$i+6*$p=3**$n]=str_pad($s,2*$p).$s;$r[3*$p+$i++]=$s.$s.$s;}ksort($r);return$r;}

```

Run with default config (no `php.ini`) or try it online.

# Answer
> 2 votes
# Perl, 64 bytes

```
//;$_ x=3,$.=s|.+|$&@{[$$_++/$.&1?$&:$"x$.]}$&|g for($_=H.$/)x$'

```

Requires `-p`, input is taken from stdin. Output is an H of `H`s.

Try it online!

# Answer
> 2 votes
# PHP (5.6+), 94 bytes

```
<?for(;$H>$e*=3or$e=($i+=$e&&print"$s
")<${$s=H}=3**$argn;)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

```

Used with `-F` command line option. Assumes interpreter defaults (`-n`). Will not work on versions previous to 5.6, due to the power operator.

**Sample usage**

```
$ echo 3|php -nF h-carpet.php
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H HH HH HH HH HH HH HH HH H
HHHHHHHHHHHHHHHHHHHHHHHHHHH
H HH HH HH HH HH HH HH HH H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H

```

Try it online!

# Answer
> 1 votes
# CJam - 103 97 87 76 bytes

```
{H{ae_,S*}%}:Il~a:A];{A_W={)(a9*+:A;[[HIH][HHH][HIH]]{z~}%}{);:A;"H"}?}:H~N*

```

This program does a quite verbose "handcoded" recursion. No smart matrix multiplications. Throughout the recursion, on top of the stack there is an array gathering the output gained from the parent calls. Right after each set of recursive calls the output of the recursive calls needs to be zipped together, to make sure the output is correct when the stack is printed linearly at the end of the program. The stack of arguments being passed down the recursion is kept in the variable `A`.

Try online

# Answer
> 1 votes
# K (ngn/k), 18 bytes

```
{~|/a<\:'a:1=!x#3}

```

Try it online!

# Answer
> 1 votes
# Japt, 23 bytes

```
_·£[X³XX³]Ãy c ·û}gQq)y

```

Try it online!

### Unpacked & How it works

```
Z{ZqR mXYZ{[Xp3 XXp3]} y c qR û}gQq)y

Z{    Declare a function that accepts a string...
  ZqR   Split by newline...
  mXYZ{   and map each row into...
    [Xp3 XXp3]  an array of [X.repeat(3), X, X.repeat(3)]
  }
  y   Transpose the resulting 2D array
  c   Flatten
  qR  Join with newline
  û   Center-pad each row to the longest
}
gQq)  Apply the above function to '"' recursively
y     Transpose the resulting 2D string

```

Using the transposed pattern

```
III
 I
III

```

is far easier to handle than the original `H` pattern, at least in Japt where the `I` can be done with string repeat and center-padding.

# Answer
> 0 votes
# C++11 - 138 bytes

Not sure if this answer has a valid syntax here however.

```
#define A a?1:0
template<int N>struct H{H<N-1>h[9];H(int a):h{A,0,A,A,A,A,A,0,A}{}};template<>struct H<0>{char h;H(int a):h{a?'H':' '}{}};

```

Ungolfed with working code

```
#include <iostream>

#define A a?1:0

template<int N>
struct H
{
  H<N-1> h[9];

  H(int a) : h{A,0,A,A,A,A,A,0,A}
  {}
};

template<>
struct H<0>
{
  char h;

  H(int a) : h{a?'H':' '}
  {}
};

int pow(int a, int b)
{
  int res=1;

  for (int i=1; i<=b; ++i)
    res *= a;

  return res;
}

template<int N>
char getHvalue(int i, int j, H<N> &hn)
{
  int n3=pow(3, N-1);

//std::cout << N << " " << i << " " << j << std::endl;

  return getHvalue(i%n3, j%n3, hn.h[i/n3*3+j/n3]);
}

template<>
char getHvalue<0>(int, int, H<0> &hn)
{
  return hn.h;
}

int main()
{
  H<0> h0(1);

  std::cout << getHvalue(0, 0, h0) << std::endl;

  std::cout << "\n====================\n" << std::endl;

  H<1> h1(1);

  for (int i=0; i<3; ++i) {
    for (int j=0; j<3; ++j)
      std::cout << getHvalue(i, j, h1);
    std::cout << std::endl;
  }

  std::cout << "\n====================\n" << std::endl;

  H<2> h2(1);

  for (int i=0; i<9; ++i) {
    for (int j=0; j<9; ++j)
      std::cout << getHvalue(i, j, h2);
    std::cout << std::endl;
  }

  std::cout << "\n====================\n" << std::endl;

  H<3> h3(1);

  for (int i=0; i<27; ++i) {
    for (int j=0; j<27; ++j)
      std::cout << getHvalue(i, j, h3);
    std::cout << std::endl;
  }

  return 0;
}

```

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


title: The 9 Billion Names of God

text:
# Question
Title: The 9 Billion Names of God
The 9 Billion Names of God is a short story by Arthur C. Clarke. It's about a group of Tibetan monks whose order is devoted to writing down all the possible names of God, written in their own alphabet. Essentially, they are devoted to writing every possible permutation of their alphabet, restricted by a few rules. In the story, the monastery hires some engineers to write a program to do all the work for them. Your goal is to write that program.

Rules:

* The monk's alphabet uses 13 characters (according to my estimations). You may use `ABCDEFGHIJKLM` or some other set of 13 characters.
* The minimum length of a possible name is 1 character. The maximum length is 9 characters.
* No character may repeat more than 3 times in succession. `AAABA` is a valid name, but `AAAAB` is not.
* Your program should print out (to a file) every possible name in sequence from `A` to `MMMLMMMLM`, separated by any character not in the alphabet (newlines, semi-colons, whatever).
* This is code-golf, and you can use any language. The shortest solution by June 1st 2014 wins.

Edit: The names should start with `A` and end with `MMMLMMMLM`, progressing through all the billions of names sequentially. But the particular sequence is up to you. You can print out all the 1-letter names first, then all the 2-letter names, etc. Or you can print all the names starting with `A`, then all the ones starting with `B`, or some other pattern. But a human should be able to read through the file and confirm they are all there and in whatever logical order you choose, assuming they have the time.

# Answer
> 34 votes
# Ruby, 46

```
?A.upto(?M*9){|s|s[/(.)\1{3}|[N-Z]/]||puts(s)}

```

My original, similar solution was longer and wrong (it output base13 numbers, which isn't quite all of them due to leading zeroes), but I'll leave it here because it got votes anyway.

```
1.upto(13**9){|i|(s=i.to_s 13)[/(.)\1{3}/]||puts(s)}

```

# Answer
> 24 votes
# C 140 ~~177 235~~

Good old procedural style, no fancyness.
It counts (no write) 11,459,252,883 names in 8 minutes.
Next edit with the runtime and size of names file. Watch the sky...
**Runtime** 57 minutes, file size 126,051,781,713 (9 chars+crlf per row). Please tell me the monks' email address, so that I can send them the zipped file, for manual check...

**Edit** Golfed a little more, reworked the check for repeated letters.
Still not the shortest, but at least this one terminates and generates the required output.
Runtime 51 min, file size 113,637,155,697 (no leading blanks this time)

A side note: obviously the output file is very compressible, still I had to kill 7zip, after working 36 hours it was at 70%. Weird.

```
char n[]="@@@@@@@@@@";p=9,q,r;main(){while(p)if(++n[p]>77)n[p--]=65;else for(r=q=p=9;r&7;)(r+=r+(n[q]!=n[q-1])),n[--q]<65&&puts(n+q+1,r=0);}

```

**Ungolfed**

```
char n[]="@@@@@@@@@@";
p=9,q,r;
main()
{
    while (p)
    {
        if (++n[p] > 77)
        {
            n[p--] = 65; // when max reached, set to min and move pointer to left
        }
        else
        {
            for (r=q=p=9; r & 7 ;) // r must start as any odd number
            {
                r += r+(n[q]!=n[q-1])); // a bitmap: 1 means a difference, 000 means 4 letters equal
                n[--q] < 65 && puts(n+q+1,r=0);
            }
        }
    }
}

```

# Answer
> 19 votes
# Golfscript, ~~58~~ 47 characters

```
"A"13
9?,{13base{65+}%n+}%{`{\4*/,}+78,1/%1-!},

```

Thanks to Peter Taylor, I am spared from the seppuku from not beating the Ruby solution! Run the code up to 10 yourself, and here is proof it skips the four-in-a-row numbers.

# Answer
> 18 votes
# Bash+Linux command line utils, 43 bytes

```
jot -w%x $[16**9]|egrep -v "[0ef]|(.)\1{3}"

```

This uses a similar technique to my answer below, but just counts in base 16, and strips out all "names" containing `0`, `e` or `f` as well those with more than 3 same consecutive digits.

Convert to the monk's alphabet as follows:

```
jot -w%x $[16**9]|egrep -v "[0ef]|(.)\1{3}" | tr 1-9a-d A-M

```

---

# Bash+coreutils (dc and egrep), 46 bytes

**Edit - corrected version**

```
dc<<<Edo9^[p1-d0\<m]dsmx|egrep -v "0|(.)\1{3}"

```

This'll take a while to run but I think its correct.

`dc` counts downwards from 14^9 to 1 and outputs in base 14. egrep filters out the numbers with more than 3 consecutive same digits. We also filter out any names with "0" digits, so we get the correct set of letters in the names.

The question specifies that any alphabet may be used, so I am using \[1-9\]\[A-D\]. But for testing, this can be transformed to \[A-M\] using tr:

```
dc<<<Edo9^[p1-d0\<m]dsmx|egrep -v "0|(.)\1{3}" | tr 1-9A-D A-M

```

This yields the sequence:

```
MMMLMMMLM MMMLMMMLL MMMLMMMLK ... AC AB AA M L K ... C B A

```

*Note this `dc` command requires tail recursion to work. This works on dc version 1.3.95 (Ubuntu 12.04) but not 1.3 (OSX Mavericks).*

# Answer
> 10 votes
## APL (59)

```
↑Z/⍨{~∨/,↑⍷∘⍵¨4/¨⎕A[⍳13]}¨Z←⊃,/{↓⍉⎕A[1+(⍵/13)⊤¯1⌽⍳13*⍵]}¨⍳9

```

Written in its own alphabet :) It's a bit long. It also takes a long time to run with `9`, try it with a lower number to test if you want.

Explanation:

* `{`...`}¨⍳9`: for each number  from 1 to 9:
    + `⍳13*⍵`: get all numbers from 1 to `13^⍵`
    + `¯1⌽`: rotate the list to the left by 1 (so we have `13^⍵`, `1`, `2`, ..., `13^⍵-1`, which turns into `0, 1, 2 ...` modulo `13^⍵`).
    + `(⍵/13)⊤`: encode each number in base 13 using  digits
    + `⎕A[1+`...`]`: add one (arrays are 1-indexed) and look up in `⎕A` (the alphabet)
    + `↓⍉`: turn the matrix into a vector of vectors along the columns.
* `Z←⊃,/`: join each inner vector of vectors together, giving us a list of possible names (but it doesn't meet the rules yet).
* `{`...: for each name, test if it meets the 4-repeated-chars rule:
    + `4/¨⎕A[⍳13]`: for each character, generate a string of 4 of that character
    + `⍷∘⍵¨`: for each string, test if it is present in
    + `∨/,↑`: take the logical *or* of all these tests,
    + `~`: and invert it, so that `1` means that it meets the rules and `0` means it doesn't.
* `Z/⍨`: select from `Z` all the elements that meet the ruels
* : display each one on a separate line

# Answer
> 9 votes
# Perl, 70 68 66 50 characters

```
$"=",";map/(.)\1{3}/||say,glob$i.="{@a}"for@a=A..M

```

Usage:

```
$ perl -E 'code' > output_file

```

The nice thing is that the prints are buffered, so you get all 1-character solutions printed first, followed by 2-character words and so on.

# Answer
> 9 votes
## Perl - 35 bytes

```
#!perl -l
/(.)\1{3}|[N-Z]/||print for A..1x9

```

Counting the shebang as one byte.

This is a loose translation of histocrat's answer.

`A..1x9` is a bit of an oddity; this is shorthand for `'A'..'111111111'`. The accumulator will never actually reach the terminal value (it contains only upper-case letters), but it will still terminate once it becomes longer than *9* characters long. This can be tested, for example, by using `1x4` instead.

# Answer
> 6 votes
# Pyg (Waaay too long, for a language made for golfing)

*whispers*: 101...

```
Pe(*ItCh(((J(x)for x in ItPr("ABCDEFGHIJKLM",repeat=j)if not An((i*3 in x)for i in x))for j in R(14))))

```

Even though this is close to how I would actually do it in Python:

```
from itertools import *
for i in range(14):
    for j in ("".join(k) for k in product("ABCDEFGHIJKLM",repeat=i) if not any((i*3 in k) for i in k)):
        print j

```

Minus the long line complication of course ;)

# Answer
> 3 votes
# Pyth, 34 characters

```
Kf<T"n"GJKFbJI>lb9Bb~Jm+bdfXVb*Y3K

```

Explanation:

```
Kf<T"n"G        K = list of letters in the alphabet before n.
JK              J = copy of K
FbJ             For b in J:
I>lb9B          If length of b > 9: break
b               print(b)
~J              J+=
~Jm+bd          J+=map(lambda d:b+d,
       XVb*Y3   index of Y*3 in reversed(b)
      fXVb*Y3K  filter for non-zero for Y in K on function index of Y*3 in reversed(b)
~Jm+bdfXVb*Y3K  J+=map(lambda d:b+d, filter(lambda Y:index of Y*3 in reversed(b), K))

```

# Answer
> 2 votes
# Python 2 - 212 bytes

```
from itertools import chain,product as p
a='ABCDEFGHIJKLM'
q={c*4 for c in a}
c=0
for n in chain(*(p(*([a]*l)) for l in range(1,10))):
 n=''.join(n)
 if not any(u in n for u in q):print n
 c+=1
 if c==10**9:break

```

# Answer
> 0 votes
# Japt, 21 bytes

```
Ep9 osE kè/0|(.)\1{3}

```

Try it online! (the link only computes up to `14**4`.)

### How it works

```
Ep9 osE kè/0|(.)\1{3}/

Ep9  14**9
osE  Range from 0 to n (exclusive), mapped through base-14 conversion
kè   Remove elements that match at least once...
/0|(.)\1{3}/  the regex that matches a zero or four times same char.

```

Assumes a standard ECMAScript 2017 implementation as the JS layer (and enough memory to store the array), where an `Array` object can have maximum of `2**53-1` length.

---
Tags: code-golf, permutations
---


title: Function clipboard: paste

text:
# Question
Title: Function clipboard: paste
*This challenge is related to some of the MATL language's features, as part of the May 2018 Language of the Month event.* *Associated challenge:* Function clipboard: copy.

---

# Introduction

MATL's *function clipboard* stores ("copies") the inputs to the four most recent calls to normal, input-taking functions. *Normal* functions are the most common type of functions in MATL. *Input-taking* means that the function takes at least one input. The stored clipboard contents can be pushed onto the stack ("pasted").

This challenge will take the clipboard contents as input. It will be assumed that all functions that have produced that clipboard state took one or more positive integers as inputs. So the clipboard state can be represented by a list of lists of numbers. (For more information on how the clipboard is actually filled see the related challenge; but that's not necessary for the current one).

### Interpreting the clipboard contents

**Example 1**

The *first* inner list refers to the *most recent* function call, and so on, Thus the clipboard state

```
[[11, 28], [12, 16], [4], [5, 6]]

```

indicates that the last function call took two inputs, namely `11`, `28`; the second-last call took inputs `12`, `16`; etc. (This clipboard state is produced by the code in the first example of the related challenge).

**Example 2**

If *there have not been enough function calls*, some trailing inner lists in the clipboard will be empty:

```
[[7, 5], [], [], []]

```

(This is produced by a program that simply adds `7` and `5`).

**Example 3**

Function calls can have *any number of inputs*, but always at least `1` (functions taking no inputs do not change the clipboard state). So the following is also possible.

```
[[3], [2, 40, 34], [7, 8, 15], []]

```

### Accessing the clipboard contents

The contents of the function clipboard are pushed onto the stack using MATL's function `M` (which, by the way, is not a normal function, but a clipboard function). This function takes a positive integer as input, and pushes some of the clipboard contents onto the stack, as follows. With reference to the clipboard state in example 1:

```
[[11, 28], [12, 16], [4], [5, 6]]

```
* `1M` returns *all inputs* to the most recent function call. So, for the considered example, it gives `11`, `28`.
* Similarly, `2M`, `3M` and `4M` return all inputs to the second, third and fourth most recent function calls. So `2M` gives `12`, `16`; `3M` gives `4`; and `4M` gives `5`, `6`.
* Numbers beyond `4` select *individual inputs* to function calls that took *more than one* input. So `5M` returns the *last* input to the *most recent* such call. In our case this gives `28`. `6M` returns the *preceding* individual input, which is `11`. `7M` returns the last input of the second-last call, that is, `16`, and `8M` gives `12`. Now, `9M` gives `6`. Note how input `4` is skipped because it was the *only* input in its function call. Lastly, `10M` gives `5`.

For the clipboard state in example 3:

```
[[3], [2, 40, 34], [7, 8, 15], []]

```
* `1M` gives `3`. `2M` gives `2`, `40`, `34`. `3M` gives `7`, `8`, `15`.
* `4M` has *undefined behaviour* (for the purposes of this challenge), because there have only been three function calls.
* `5M` gives `34`. `6M` gives `40`. `7M` gives `2`. `8M` gives `15`. `9M` gives `8`, `10M` gives `7`.
* `11M`, `12M`, ... also have *undefined behaviour*.

## The challenge

**Input**:

* the clipboard state, as a list of lists, or any other reasonable format;
* a positive integer *n*.

**Output**: the result of calling function `M` with *n* as input. The output will be one or several numbers with an unambiguous separator, or in any reasonable format such as a list or array.

Clarifications:

* The clipboard state consists of four lists of numbers. Some of the trailing lists may be empty, as in examples 2 and 3. If preferred, you can input the clipboard without those trailing empty lists. So example 3 would become `[[3], [2, 40, 34], [7, 8, 15]]`.
* All numbers in the clipboard will be positive integers, possibly with more than one digit.
* The number *n* is guaranteed to be valid. So for example 3 above, `n` cannot be `4` or `11`.

Additional rules:

## Test cases

```
Clipboard state
Number
Output(s)

[[11, 28], [12, 16], [4], []]
2
12, 16

[[11, 28], [12, 16], [4], []]
5
28

[[7, 144], [12], [4, 8], [3, 4, 6]]
1
7, 144

[[7, 144], [12], [4, 8], [3, 4, 6]]
10
4

[[30], [40], [50, 60], [70, 80, 90]]
2
40

[[30], [40], [50, 60], [80, 90]]
7
90

[[15], [30], [2, 3, 5], [4, 5, 10]]
3
2, 3, 5

[[15], [30], [2, 3, 5], [4, 5, 10]]
7
2

```

# Answer
> 3 votes
# Jelly, 8 bytes

```
ḊƇUẎ⁸;⁹ị

```

Try it online!

# Answer
> 4 votes
# Haskell, ~~56 51~~ 47 bytes

~~-5~~-9 bytes thanks to Laikoni (pattern match to ensure length \> 1 and using `do`-notation over list comprehension)!

```
c!n=([]:c++do l@(_:_:_)<-c;reverse$pure<$>l)!!n

```

Try it online!

### Pointfree, ~~58~~ 55 bytes

-3 bytes thanks to Laikoni (moving `([]:)` and replacing `id`)!

Alternatively we could use this pointfree version

`(!!).(([]:)<>map pure.(>>=reverse).filter((1<).length))`.

# Answer
> 3 votes
# APL (Dyalog Unicode), 17 bytes

```
{⍺⊃⍵⍪∊⊖¨⍵⌿⍨1<≢¨⍵}

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 57 bytes

```
a=>n=>a.map(e=>e[1]&&a.push(...[...e].reverse()))&&a[n-1]

```

Try it online!

This is an anonymous, curried function. Run it with `( function code )(clipboard)(n)`

## Explanation

```
a=>n=>{
    // The strategy is to append the individual clipboard inputs to the end of a,
    // after the function calls (lists). We then return a[n-1] to offset JavaScript's
    // zero indexing.
    a.map(e=>{
        e[1]&& // if this list has more than one element...
            a.push(...[...e].reverse()) // add each element to a, in reverse order.
            // reverse() modifies the original array, so we have to use [...e] to "clone" e
    })
    return a[n-1]
}

```

# Answer
> 2 votes
# Stax, ~~12~~ ~~14~~ 13 bytes

```
àJ├∙ε╝F▀ÿi☻Ia

```

Run and debug it

Explanation:

```
vsc{%vfr$r+@]|u Full program, unpacked, implicit input
vs              Decrement the number and get the list
  c{  f         Copy and filter:
    %v            Length not equal to 1?
       r$r      Reverse, flatten, and reverse again
          +     Concat orig array and and modified array
           @]|u Index, wrap into array, uneval

```

## Stax, 12 bytes

```
Å{b≈\☼╣Δ@░ ‼

```

Unpacked:

```
{vsc{%vfr$r+@}

```

This is a block, so I can get rid of the `]|u`, but I don't know if this is valid as it's packing a block.

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

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

```
a=>m=>a[m-1]||(g=r=>(r=r|a[k][1]&&a[k].pop())?--m<5?r:g(1):g(!++k))(k=0)

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~60~~ 56 bytes

thanks to Jonathan Allan for -4 bytes.

```
lambda l,n:(l+sum([b[::-1]for b in l if b[1:]],[]))[n-1]

```

Try it online!

# Answer
> 2 votes
# Java 8, 110 bytes

A lambda (curried) taking the clipboard state as an `int[][]` and the number as an `int` and returning `int` or `int[]` (a single number may be returned through either type).

```
s->n->{if(--n<4)return s[n];else{int i=0,l;for(n-=4;(l=s[i].length)<=n|l<2;i++)n-=l>1?l:0;return s[i][l+~n];}}

```

Try It Online

## Ungolfed

```
s ->
    n -> {
        if (--n < 4)
            return s[n];
        else {
            int i = 0, l;
            for (
                n -= 4;
                (l = s[i].length) <= n | l < 2;
                i++
            )
                n -= l > 1 ? l : 0;
            return s[i][l + ~n];
        }
    }

```

# Answer
> 2 votes
# 05AB1E, 12 bytes

```
Díʒg<Ā}˜«s<è

```

Try it online!

**Explanation**

```
D              # duplicate input list
 í             # reverse each
  ʒg<Ā}        # filter, keep only elements that are longer than 1
       ˜       # flatten
        «      # append to original list
         s<    # decrement the second input
           è   # get the element in the list at that index

```

# Answer
> 2 votes
# Husk, 12 bytes

```
!S+(m;ṁ↔f(¬ε

```

Try it online!

### Explanation

Pretty much a direct port of the Haskell answer:

```
!S+(m;ṁ↔f(¬ε  -- example inputs: [[1],[2,3],[4],[5,6,7],[]] 7
 S+           -- concatenate itself with itself modified by
        f(    -- | filter
           ε  -- | | length 1
          ¬   -- | | not
              -- | : [[2,3],[5,6,7],[]]
      ṁ       -- | map and flatten
       ↔      -- | | reverse
              -- | : [3,2,7,6,5]
              -- | map
              -- | | pure
              -- | : [[3],[2],[7],[6],[5]]
              -- : [[1],[2,3],[4],[5,6,7],[],[3],[2],[7],[6],[5]]
!             -- index into it: [2]

```

# Answer
> 2 votes
# , 58 bytes

```
function(M,n)c(M,unlist(lapply(M[lengths(M)>1],rev)))[[n]]

```

Try it online!

Takes `M` as a `list` of vectors `c()`; so replacing `[[` with `list(`, `[` with `c(` and `]` with `)` should transform the test cases into R test cases.

For inputs `n<=4` with "undefined behavior", returns `NULL` and for other invalid inputs, throws a "subscript out of bounds" error.

```
function(M,n)
                                        [[n]]	# take the nth element of
c(M,                                   )	# M concatenated with:
    unlist(                           )		# the individual elements of
           lapply(               ,rev)		# in-place reversals of
                  M[lengths(M)>1]		# elements of M with length > 1

```

# Answer
> 2 votes
# , 33 22 bytes

-11 bytes (1/3 shorter) thanks to FrownyFrog's solution!

```
{0;],|.&.>;/@;@#~1<#&>

```

Try it online!

## My initial solution:

# , 33 bytes

```
<:@[{(,[:<"0@;[:|.&.>(1<#)&>#])@]

```

Not happy - I'm pretty sure it can be golfed much further.

## Explanation:

A dyadic function, taking the clipboard state as its rigth argument, the left argument is `n`

`<:@[` subtract 1 from the left argument

`{` selects the `i`th element (calculated above) from the list on its right

`(...)` the entire list

`#` copy

`]` from the list of clipboard state

`(1<#)` the sublists with length greater than 1

`|.&.>` rotate each copied sublist

`<"0@;` raze and box - puts each number into a separate box

`,` append the new list to the list of clipboard state

`@]` makes the entire verb in (...) monadic

Try it online!

# Answer
> 2 votes
# \+ coreutils, ~~53 45 43 42~~ 40 bytes

-9 bytes thanks to DJMcMayhem (using `VGÇ /d` over `:,$g/^[^ ]*$/d`, `D@"dd` over `"aDÀdd` and `!!` over `:.!`)!

My very first attempt at  (tips welcome!), the below code is using circled characters (eg.  for `\xf`) for readability:

```
jäGⓞVGÇ /d
ⓞò!!tr \  \\n|tac
jòHD@"ddjdG

```

Try it online!

### Hexdump

```
00000000: 6ae4 470f 5647 c720 2f64 0a0f f221 2174  j.G.VG. /d...!!t
00000010: 7220 5c20 205c 5c6e 7c74 6163 0a6a f248  r \  \\n|tac.j.H
00000020: 4440 2264 646a 6447                      D@"ddjdG

```

## Explanation

The first line contains *n* and the lines below contain the entries of the clipboard, each entry is separated by spaces if there were multiple inputs:

```
j                        " move to the beginning of the clipboard entries
 äG                      " duplicate the clipboard
   ⓞ                    " <C-o> move cursor to the beginning of the 2nd copy
     VG                  " select everything from cursor to the end of buffer and ..
       Ç /d              " .. delete every line that doesn't contain a space

ⓞ                       " <C-o> move cursor to the beginning of the 2nd copy (now without single arguments)
  ò                   ò  " do the following until the end of buffer
   !!                    "   on the current line execute the shell command
     tr \  \\n           "   replace spaces with newlines
              |tac⮠     "   and reverse the lines
                    j    "   move to next line

H                        " go to the beginning of buffer (where n is)
 D                       " delete n (stores it in register ")
  @"                     " that many times ..
    dd                   " .. remove the line
      j                  " move cursor to next line
       dG                " delete everything from here to the end of buffer

```

# Answer
> 1 votes
# Red, 91 bytes

```
func[b n][a: copy[]foreach c b[if 1 < length? c[append a reverse copy c]]pick append b a n]

```

Try it online!

# Answer
> 1 votes
# C (gcc), 176 bytes

```
#define p printf("%d ",
int*_,i;f(x,n)int**x;{if(n<5){for(_=x[2*n-2];_-x[2*n-1];++_)p*_);}else{n-=4;for(i=0;i<8;i+=2)if(n&&x[i]+1-x[i+1])for(_=x[i+1];_-x[i]&&n;--_,--n);p*_);}}

```

Try it online!

Takes the array as a list of 4 start/end pointer pairs, then n.

Description:

```
#define p printf("%d ",  // This gives us the short-hand for printing
int*_,                   // This defines _ as a pointer to int
i;                       // This defines i as an integer
f(x,n)int**x;{           // This defines f as a function taking int **x and int n
                         // NOTE: x is {start, end, start, end, start, end, start, end}
if (n<5) {               // This is for the 1-4 case
  for(_=x[2*n-2];        // Loop _ from the 'end pointer'
  _-x[2*n-1];++_)        // Until the 'start pointer'
  p*_);                  // Using the short-hand, print *_
}else{                   // This is for the 5+ case
  n-=4;                  // Cut n to improve indexing
  for(i=0;i<8;i+=2)      // Loop over each 'start pointer index'
    for(_=x[i+1];        // Loop _ from the 'end pointer'
        _-x[i]&&n;       // Until the 'start pointer' or n becomes 0
        --_,--n);        // Decreasing n each time
  p*_);}}                // _ now points to the 'correct' index, so print it

```

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