# Question
Title: Simulate reproduction in a population of oozes
Reproductive strategy of oozes can be summarized as follows:

> o O 8 oo

A population of oozes at generation N is described by a string, for example:

```
ooooo88ooOoOo8Ooooo8OOoo8Oo8Oo8oo8oooooo8OOooO88o

```

To compute the population at generation N+1, take one character randomly, and replace it by the result of ooze evolution:

* If `o`, replace by `O`
* If `O`, replace by `8`
* If `8`, replace by `oo`

Generation 0 is the one-character string `o`. Your program or function should get a positive number N, and output the population of oozes at generation N. At each generation, each ooze should have the same chance (to within 1% accuracy) to evolve.

Test cases (actual results may vary due to randomness):

```
1 -> O
2 -> 8
3 -> oo
4 -> Oo
5 -> OO
10 -> OO8
20 -> oo8oooo
30 -> oOoooOO8O
100 -> 8o8oO8OOooOo8OOoo88oOO8OOO
200 -> 88OOo8oooo8OOoooOoOOO8O8OO88o8Oo8oooOooooooOo8OooO888
1000 -> 8Ooooo88OO8o8O8oooOOoOOO88oOoO88OOoO8OOOooOOo8OO88O8OO8OO8ooo8oOO8OoooO88OooooooooOo8oooOO8OO8Oo8Oooo8O88oooOooO8Oo8ooOOOOo8OooOo8OoooooooO8oOooooOooOO8oOO8ooo8Ooooo8ooo8ooOOooO8OOoO8oO8oo88ooo8oO8OO8o888oO8OOoO8o8ooO8O88OOOoO8oooO8OoOoOo88O88oo88ooo8oO8o8oOooOo

```

---

If your solution has running time of O(n), please specify it explicitly!

# Answer
# Jelly, ~~21~~ 16 bytes

```
1F‘JX$¦ḃ3Ʋ¡ị“oO8

```

Try it online!

A full program that takes `n` as its argument and implicitly outputs the state of the oozes after that many generations.

Thanks to @cairdcoinheringaahing for saving a byte!

## Explanation

```
1                 | Literal 1
         Ʋ¡       | Repeat the following the number of times given by the argument
 F                | - Flatten
  ‘  $¦           | - Increment the item at the index given by:
   J              |   - Sequence along the list
    X             |   - Random number fron the sequence
       ḃ3         | Convert to bijective base 3
           ị“oO8” | Index into "oO8"

```
> 3 votes

# Answer
# Python 3, 114 bytes

```
from random import*
def f(n,s=b'o'):k=randrange(len(s));return n and f(n-1,s[:k]+b'oO8o'[-~s[k]%3::3]+s[k+1:])or s

```

Try it online!

Interesting observation: the ascii values of `oO8` are `111`, `79`, and `56`, respectively. If you take these modulo 3, you get `0`, `1` and `2`.

---

Additional observation: you can validate the generation of your final string by substituting `'o'` with 3, `'O'` with 4 and `'8'` with 5; then taking the sum of your list and subtracting 3 from the total.

This works for all strings regardless of random variations, because each replacement in your string increases this sum by 1:

```
'o' (3) -> 'O'  (4)
'O' (4) -> '8'  (5)
'8' (5) -> 'oo' (3+3 = 6)

```

We then just need to correct for the offset of 3.

Validate it online!
> 23 votes

# Answer
# Ruby, ~~79 77 73 72~~ 61 bytes

```
->n,s=?o{n.times{s[w=rand(s.size)]=%w[O 8 oo][s[w].ord%3]};s}

```

Try it online!

-11 bytes thanks to Value Ink and Jitse
> 9 votes

# Answer
# APL (Dyalog Unicode), ~~40~~ ~~32~~ 31 bytesSBCS

Full program. Prompts for N from stdin.

```
'o8O'[{∊⌷∘3(1 1)2@(?≢⍵)⊢⍵}⍣⎕,1]

```

Try it online!

`'o8O'[``]` select the following characters from the string `"oO8"`:

`,1` the list `[1]`

prompt for N from stdin

`{``}⍣` apply the following anonymous lambda to `[1]`, that N times:

`⊢⍵` on the argument…

`@(``)`**at** position…

`≢⍵` the length of the argument

`?` random index in that range

… apply the following tacit function:

`⌷∘3(1 1)2` use the number to select from the list `[3,[1 1],2]`:

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

# Answer
# Pyth, 25 bytes

```
uXGJOlG@c"O 8 oo")C@GJQ\o

```

Try it online!

Written by @FryAmTheEggman, similar idea to my earlier post but much cleaner as it reduces instead of looping.

## How it works

```
uXGJOlG@c"O 8 oo")C@GJQ\o
u                     Q\o - Reduce 'o' Q=input times
   JOlG                   - With random number J in the range [0,length G),
                            where G is the previous list
 XG                       - Replace the element in G at index J...
       @c"O 8 oo")        - With an element of "O 8 oo" split by
                            whitespace, at index...
                  C@GJ    - ...of the codepoint of the element in G at index J

```

# Pyth, 38 bytes

```
K\oJ["oo"\o\O\8)VQ=kOlK=KXKk@JhxJ@Kk;K

```

Try it online!

My original solution, less sophisticated.

## How it works

```
K\oJ["oo"\o\O\8)VQ=kOlK=KXKk@JhxJ@Kk;K
K\o                                    - K = 'o', start
   J["oo"\o\O\8)                       - J = ['oo', 'o', 'O', '8']
                VQ                     - Loop Q=input times
                  =kOlK                - k = random number from 0..length of K
                       =K              - K equals...
                         XKk           - K with the element at index k replaced by...
                            @Jh        - The item in J at index+1 of...
                               xJ      - The index (in J) of...
                                 @Kk   - The element of K at index k
                                    ;K - End loop, print K

```
> 8 votes

# Answer
# 05AB1E, 26 bytes

```
'osFÐg<ÝΩ©è…oO8S„O8„ooª‡®ǝ

```

Try it online!
> 8 votes

# Answer
# , ~~109~~ ~~97~~ 93 bytes

```
for(i in 1:scan())T=append(T,switch(T[j],"O",O=8,"8"=c("o","o")),j<-sample(sum(T>0),1))[-j];T

```

Try it online!

Output as an array.

Thanks to Robin Ryder for golfing out 6 bytes, for pointing out a bug in a previous version, and for golfing out an additional 4 bytes.
> 7 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~172~~ ~~158~~ ~~150~~ ~~149~~ ~~144~~ ~~137~~ ~~130~~ 128 bytes

```
a=>{dynamic r=new Random(),g="o",i;while(a-->0)g=g.Remove(i=r.Next(g.Length),1).Insert(i,"O,8,oo".Split(',')[g[i]%3]);return g;}

```

Try it online!

-14 bytes thanks to @Jitse's observation about character modulus

-8 bytes by renaming a variable I forgot about

-1 byte by switching to a while loop

-5 bytes by not saving the current character to a variable

-7 bytes by switching to the interactive compiler

-7 bytes by chaining declarations and inlining assignment thanks to @my pronoun is monicareinstate

-2 bytes by changing to string split over character comparison thanks to @Olivier Grégoire for inspiration
> 6 votes

# Answer
# , 54 bytes

```
'oO8'{~(((1+2={)`[`(1"0@])}#(3|1+{)`[`]})~1?#)^:(]`0:)

```

Try it online!

Wholly different approach to shave off 2 bytes

# original solution

# , 56 bytes

```
'oO8'{~(({.,(i.@3(>:@i.{ ::0 0[){),>:@[}.])~1?#)^:(]`0:)

```

Try it online!

Had an equal byte solution, but adjusted it slightly using Adam's idea of doing all the calculation in pure integers, and saving the translation-to-string step till last, which I felt looked a bit cleaner.
> 6 votes

# Answer
# Perl 6, 55 bytes

```
{('o',{S:p(rand*.comb)[.]=<O 8 oo>[$/.ord%3]}...*)[$_]}

```

Try it online!

### Explanation

```
{                                                     }  # Anonymous block
     ,                                       ...*  # Infinite sequence
  'o'  # Start with string "o"
      {                                     }  # Compute next item by
       S  # replacing
        :p(rand*.comb)  # starting at random position
                      [.]  # any character
                         =<O 8 oo>  # with "O", "8" or "oo"
                                  [$/.ord%3]  # depending on ASCII code mod 3
 (                                               )[$_]  # nth item of sequence

```
> 6 votes

# Answer
# Perl 5, 79 bytes

```
sub f{$_[0]?do{$_=f(-1+pop);substr($_,rand length,1)=~y/oO8/O82/;s,2,oo,r}:"o"}

```

Try it online!

```
sub f {
  $_[0]
  ? do{
      $_ = f(-1+pop);
      substr($_,rand length,1) =~ y/oO8/O82/;
      s,2,oo,r
    }
  : "o"
}

srand(7) and print "$_ -> ",f($_),"\n" for 1..40

```
> 5 votes

# Answer
# Charcoal, 38 bytes

```
⊞υoＦＮ«≡⊟υo⊞υO¦O⊞υ8Ｆ²⊞υo≔‽ＬυιＵＭυ§υ⁺λι»υ

```

Try it online! Link is to verbose version of code. Outputs an array, which is like a string but vertical (+1 byte to output the array horizontally). Explanation:

```
⊞υo

```

Start with a single `o`.

```
ＦＮ«

```

Loop the given number of generations.

```
≡⊟υ

```

Remove the last character and switch on it.

```
o⊞υO

```

If it's an `o` then push an `O`.

```
O⊞υ8

```

If it's an `O` then push an `8`.

```
Ｆ²⊞υo

```

Otherwise push `o` twice.

```
≔‽ＬυιＵＭυ§υ⁺λι

```

Rotate the array by a random amount. This causes the oozes to be evolved in a random order.

```
»υ

```

Finally output the resulting array.
> 5 votes

# Answer
# Japt, ~~32~~ ~~31~~ 29 bytes

```
_gZÊö _Ä %3ª1ö2Ãc}g[]á)Ëg"oO8

```

Try it

```
 _               // function taking array
  gZÊö           // replace a random element with :
       _Ä %3     // element incremented mod 3
      ª1ö2Ã      // or [0,0]
            c}   // flattens

g[]á)            // run the function input times with initial value of array, return last element
      Ëg"oO8     // convert values to o O 8

```

Thanks to @Embodiment of Ignorance for reminding me I don't need = at beginning
> 5 votes

# Answer
# Python 2, 104 bytes

```
from random import*
l=['o']
exec"i=randrange(len(l));l[i:i+1]='oO8o'[-~ord(l[i])%3::3];"*input()
print l

```

Try it online!

Golfing Jitse's solution using the mutability of lists.
> 5 votes

# Answer
# Java (JDK), 138 bytes

```
n->{var s=new StringBuffer("o");for(int i;n-->0;s.replace(i*=Math.random(),i+1,"O,8,oo".split(",")[s.charAt(i)%3]))i=s.length();return s;}

```

Try it online!

## Credits
> 5 votes

# Answer
# Zsh, ~~75~~ 73 bytes

```
s=o
m=(oo 8 O)
repeat $1 ((n=1+RANDOM%$#s))&&s[n]=$m[m[(i)$s[n]]-1]
<<<$s

```

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

I want to focus here specifically:

```
$m[m[(i)$s[n]]-1]
   m[        ]     # from array $m:
     (i)           #   get the index of
        $s[n]      #   the nth character in the string (as a pattern)
                   #   if not found substitute 4 (length of array + 1)
              -1   # subtract one
$m[             ]  # substitute the element at that index

```
> 4 votes

# Answer
# JavaScript (ES10), 91 bytes

Similar to the ES6 version, but returns an array of characters.

```
n=>(g=P=>n--?g(P.flatMap(c=>i--?c:'8O'[c|c>g]||['o','o'],i=Math.random()*P.length|0)):P)`o`

```

Try it online!

---

# JavaScript (ES6),  ~~98 ... 94~~  93 bytes

```
n=>(g=P=>n--?g(P.replace(/./g,c=>i--?c:'8O'[c|c>g]||'oo',i=Math.random()*P.length|0)):P)('o')

```

Try it online!

### Commented

```
n => (                       // n = number of generations
  g = P =>                   // g is a recursive function taking the population string P
    n-- ?                    // decrement n; if it was not equal to 0:
      g(                     //   do a recursive call:
        P.replace(/./g, c => //     for each character c in P:
          i-- ?              //       if we haven't reached the requested position:
            c                //         leave c unchanged
          :                  //       else:
            '8O'[            //         replace with:
              c | c > g      //           'O' is c != 8 and c is lowercase
            ]                //           '8' is c != 8 and c is uppercase
            || 'oo',         //           'oo' if c = 8
          i = Math.random()  //       compute a random position i within the current
              * P.length | 0 //       population string
        )                    //     end of replace()
      )                      //   end of recursive call
    :                        // else:
      P                      //   return the final population
)('o')                       // initial call to g with P = 'o'

```
> 3 votes

# Answer
# Python 3.8, 91 bytes

```
f=lambda n,s='o':n and f(n-1,s[:(k:=id(s)//7%len(s))]+'oO8o'[-~ord(s[k])%3::3]+s[k+1:])or s

```

Try it online!

I'll be perfectly honest, I don't know for sure that this is valid randomness. It seems like it to me, but I'm not sure how I'd determine one way or the other - if someone could confirm or deny, that'd be much appreciated.

Assuming validity, this is a modification of Jitse's answer that gets rid of the import. `id(s)` gives a different integer every time, but just taking it modulo `len(s)` gave results that were too consistent. Integer dividing the id by 7 seemed to do the trick, but again, I'm not sure how to verify.

If this turns out not to be valid, I'll delete immediately.
> 3 votes

# Answer
# Red, 93 bytes

```
func[n][s: copy"o"loop n[replace at s i: random length? s s/:i select[#"o"#"O"#"8":oo]s/:i]s]

```

Try it online!
> 2 votes

# Answer
# K (oK), 51 bytes

```
{"oO8"x{{,/(x#t),((1;2;0 0)t@x),(x+1)_t}1?#t:x}/,0}

```

Try it online!

No doubt this can be done much shorter / more elegant (using ammend?). I'm somewhat happy that it works at least.
> 2 votes

# Answer
# Retina, ~~29~~ 27 bytes

```
K`o
"$+"{@T`\oo`\O80`.
0
oo

```

Try it online! Edit: Saved 2 bytes when I realised how I could combine `@` with `T`. Explanation:

```
K`o

```

Replace the input with the initial generation.

```
"$+"{

```

Repeat the remaining stages for the given number of generations.

```
@T`\oo`\O80`.

```

The `O` is a metacharacter and needs to be escaped. The `o` is also a metacharacter, so the first `o` is literal, while the second `o` represents `O80` from the destination pattern. This therefore transliterates the characters `oO8` to `O80`. The final `.` means that each character is treated as a separate match for the purposes of the `@` operator, which chooses one match (i.e. character) at random to be transliterated.

```
0
oo

```

Fix up any `0` to `oo`. (This stage does not need to be conditional.)
> 2 votes

# Answer
# Python 3, 142 bytes

```
from random import*
def f(i,x='o'):i-=1;s=randint(0,len(x)-1);o={'o':'O','O':'8','8':'oo'};x=x[:s]+o[x[s]]+x[s+1:];return x if i<1else f(i,x)

```
> 1 votes

# Answer
# Icon, 85 bytes

```
procedure f(n)
s:="o"
1to n&s[p:=?*s]:=["O",8,"oo"][find(s[p],"oO8")]&\z
return s
end

```

Try it online!
> 1 votes

# Answer
# C (gcc), 101 bytes ~~104 117 bytes~~

```
char*h,g[9999];l;f(a){*g='o';for(l=1;a--;(*h="O8o"[*h%3])-'o'?:bcopy(h,h+1,l++))h=g+rand()%l;g[l]=0;}

```

Try it online!

**(Many thanks to ceilingcat for the awesome code golfing help and ideas!)**

Ok, except for large generation count buffer overflow and the fact that I seeded random outside the code, this now works. Making g bigger could put the overflow size above what an int can hold if needed.

### Commented

```
char *h,g[9999]         // Work pointer and a fixed size buffer.
l;                      // int length of string (number of slimes)
f(a){                   // a is generation
  *g='o'                // Set first value.
  for(l=1;              // Length is 1.
   a--;                 // consume a generation
   (*h="O8o"[*h%3])     // Use the mod 3 trick to index into the next symbol and assign the new slime character.
   -'o'?:               // if we went back to 'o', grow the string
   bcopy(h,h+1,l++))    // move all the values up in in array to length (including new 'o' symbol) Note: bcopy() can overlap src and dest.
    h=g+rand()%l;       // for each loop, find which slime to evolve and point h to it.
  g[l]=0;}              // NUL Terminate the g buffer to make it a string.

```
> 1 votes

# Answer
# Lua, ~~106~~ ~~101~~ 110 bytes

**Changed Code to function format + 9 bytes**

```
e={"O",8,"oo"}for i=1,t do s=math.random(1,#o)o=o:sub(1,s-1)..e[o:sub(s,s):byte()%3+1]..o:sub(s+1)end return o

```

Try it online!
> 1 votes

# Answer
# C (gcc) (with `-m32` compiler flag), 174 172 bytes

Thanks to ceilingcat for the suggestions.

Not competing (there are already shorter versions in C), but this uses a different method.

Instead of using a hard-coded output buffer, I use a linked list on the stack to hold each cell's state and traverse the list to locate cells to mutate. If the cell splits in two, the function calls itself to hold the new cell state and adds itself into the list chain. As the list is not necessarily linear on the stack, the last function prints the list of cells (intermediate callers set their list start to `NULL` after control returns to them to prevent unwanted output.)

```
g(i,j,s,p)int*s,*p;{int a[2]={},r;for(j++?*a=*p,*p=a:(s=a);i--;++p[1]>2?p[1]=0,g(i,j,s,a),s=i=0:0)for(r=rand(p=s)%j;r--;p=*p);for(;s;s=*s)printf(L"oO8"+s[1]);}f(i){g(i,0);}

```

Try it online!
> 1 votes

# Answer
# APL(NARS), chars 62, bytes 124

```
{⍵{⍺=0:⍵⋄(⍺-1)∇(⍵↑⍨k-1),(('oO'⍸k⊃⍵)⊃"O"'8'"oo"),⍵↓⍨k←?≢⍵},'o'}

```

test:

```
  h←{⍵{⍺=0:⍵⋄(⍺-1)∇(⍵↑⍨k-1),(('oO'⍸k⊃⍵)⊃"O"'8'"oo"),⍵↓⍨k←?≢⍵},'o'}
  h 0
o
  h 4
oO
  h 10
8OO
  h 100
8oOOO8ooOO8oOOoO8oOooooO8OO
  h 200
8OO888Ooo8OO8oO88O8oo8oooooOo8ooO8OooOO88OoO8O8o8Oo

```

but it has problems if the argument is \>500, the 73 chars code below has not these problems:

```
r←f w;k
r←,'o'
→0×⍳0>w-←1⋄r←(r↑⍨k-1),(('oO'⍸k⊃r)⊃"O"'8'"oo"),r↓⍨k←?≢r⋄→2

  f 1000
    O8oooo8OoooO8ooOO88oo88OOOoo8oOoO8888oo88ooOOOoooooo8oooOO8OooO8O8oOO8oOOOo88Oo
  Ooooo88O8o8ooooo8OOooOO8O8OOOoo8OoO8Oo88ooOOoooO888O8o8OoOOoooOo8oooo8OoO
  88Oooo8O8OoooooooOo88oo8oooooo8OOoO8oOO8Oo8oo8oO88oo8OOoOoOOoOoOoo8O88o8O
  88OoO8OOoOo8Oo8ooo8OoooooooooOOooO8oo88

```
> 1 votes

# Answer
# Lexurgy, 306 bytes

Uses `oO%` for ooze states. Since Lexurgy doesn't have a random feature, the program deterministically moves a pointer from right to left in the ooze string, incrementing the ooze at that pointer. Iteration stops when the generation counter hits 0.

Note: This seems to work all the way up to 83 generations; 84 or more generations has the interpreter complain about how the propagation doesn't converge to an endpoint.

```
Class u {o,O,%}
Class d {\1,\2,\3,\4,\5,\6,\7,\8,\9,\0}
p:
*=>`ol/_ $
e propagate:
@d=>{\0,\1,\2,\3,\4,\5,\6,\7,\8,s\9}/_ `
@d s=>{\0,\1,\2,\3,\4,\5,\6,\7,\8,\9} *
then:
\0 `=>*/$ _
\0=>*/$ _
then:
@u=>{O, %, oo}/_ l//$ ` _
then:
@u$1 l=>l $1
then:
*=>l/` l @u* _ $
l=>*/` _
s:
{s,l,`}=>*

```

Ungolfed explanation:

```
Class ooze {o, O, %}
Class next {O, %, oo}

Class digit {\1,\2,\3,\4,\5,\6,\7,\8,\9,\0}
Class dec   {\0,\1,\2,\3,\4,\5,\6,\7,\8,s\9}
Class dec2  {\0,\1,\2,\3,\4,\5,\6,\7,\8,\9}

# setup: generate initial digit-ooze sep, `o`, and pointer
pre:
* => `ol / _ $

# [gens left]`[oozes][growth pointer]

# while the input was changed last iteration...
evolve-once propagate:
# decrement the generation counter
@digit => @dec / _ `
@digit s => @dec2 * # handle carries
then:
# remove leading 0s
\0 ` => * / $ _
\0 => * / $ _
then:
# grow an ooze if it's right before the growth pointer
# but not when there's no generations left
@ooze => @next / _ l // $ ` _
then:
# move the growth pointer to the left
@ooze$1 l => l $1
then:
# move the growth pointer to the end if it's at the left side of the ooze string
* => l / ` l @ooze* _ $
l => * / ` _
# remove extraneous characters
strip:
{s,l,`} => *

```
> 0 votes

---
Tags: code-golf, random
---


title: Square-free words of a length

text:
# Question
Title: Square-free words of a length
A square-free word is a word consisting of arbitrary symbols where the pattern \\$XX\\$ (for an arbitrary non-empty word \\$X\\$) does not appear. This pattern is termed a "square". For example, `squarefree` is not square-free (using the lowercase letters as the alphabet), as the square `ee` appears; but `word` is square-free. Additionally, note that \\$X\\$ does not have to be a single symbol, so `1212` is not square-free, as `12` is repeated.

If the alphabet used has exactly one symbol, there are only two square-free words: the empty word, and the word of exactly one symbol.
For a binary alphabet, e.g. \\$\\{0,1\\}\\$, there are a finite number of square-free words: the empty word, \\$0, 1, 01, 10, 010, 101\\$. All other words made from just two symbols will contain a square.
However, for an alphabet of three or more symbols, there are an infinite number of square-free words. Instead, we can consider the number of words of length \\$n\\$ for an alphabet of \\$k\\$ characters:

| \\$\downarrow\\$ Alphabet length \\$k\\$ Word length \\$n\\$ \\$\rightarrow\\$ | \\$0\\$ | \\$1\\$ | \\$2\\$ | \\$3\\$ | \\$4\\$ | \\$5\\$ | \\$6\\$ |
| --- | --- | --- | --- | --- | --- | --- | --- |
| \\$1\\$ | \\$1\\$ | \\$1\\$ | \\$0\\$ | \\$0\\$ | \\$0\\$ | \\$0\\$ | \\$0\\$ |
| \\$2\\$ | \\$1\\$ | \\$2\\$ | \\$2\\$ | \\$2\\$ | \\$0\\$ | \\$0\\$ | \\$0\\$ |
| \\$3\\$ | \\$1\\$ | \\$3\\$ | \\$6\\$ | \\$12\\$ | \\$18\\$ | \\$30\\$ | \\$42\\$ |
| \\$4\\$ | \\$1\\$ | \\$4\\$ | \\$12\\$ | \\$36\\$ | \\$96\\$ | \\$264\\$ | \\$696\\$ |
| \\$5\\$ | \\$1\\$ | \\$5\\$ | \\$20\\$ | \\$80\\$ | \\$300\\$ | \\$1140\\$ | \\$4260\\$ |
| \\$6\\$ | \\$1\\$ | \\$6\\$ | \\$30\\$ | \\$150\\$ | \\$720\\$ | \\$3480\\$ | \\$16680\\$ |

For example, there are \\$36\\$ different squarefree words of length \\$3\\$ using a alphabet of \\$4\\$ symbols:

```
121 123 124 131 132 134 141 142 143 212 213 214 231 232 234 241 242 243 312 313 314 321 323 324 341 342 343 412 413 414 421 423 424 431 432 434

```

For a ternary alphabet, the lengths are given by A006156. Note that we include the zero word lengths for \\$k = 1, 2\\$ in the table above.

---

This is a (mostly) standard challenge. You must take one input \\$k\\$, representing the length of the alphabet. Alternatively, you may accept a list (or similar) of \\$k\\$ distinct symbols (e.g. single characters, the integers \\$1, 2, ..., k\\$, etc.). You can then choose to do one of the following:

* Take a non-negative integer \\$n\\$, and output the number of square-free words of length \\$n\\$, using an alphabet with \\$k\\$ symbols
* Take a positive integer \\$n\\$ and output the first \\$n\\$ elements of the sequence, where the \\$i\\$th element is the number of of square free words of length \\$i\\$ using an alphabet of \\$k\\$ symbols
    + Note that, as \\$i = 0\\$ should be included, \\$n\\$ is "offset" by 1 (so \\$n = 3\\$ means you should output the results for \\$i = 0, 1, 2\\$)
* Take only \\$k\\$ as an input, and output indefinitely the number of square free words of increasing length, starting at \\$i = 0\\$, using the alphabet of \\$k\\$ symbols.
    + For \\$k = 1, 2\\$ you may decide whether to halt after outputting all non-zero terms, or to output `0` indefinitely afterwards

This is , so the shortest code in bytes wins.

## Test cases

Aka, what my sample program can complete on TIO

```
 k => first few n
 1 => 1,  1,   0,    0,     0,      0,      0,     0,     0, ...
 2 => 1,  2,   2,    2,     0,      0,      0,     0,     0, ...
 3 => 1,  3,   6,   12,    18,     30,     42,    60,    78, ...
 4 => 1,  4,  12,   36,    96,    264,    696,  1848,  4848, ...
 5 => 1,  5,  20,   80,   300,   1140,   4260, 15960, 59580, ...
 6 => 1,  6,  30,  150,   720,   3480,  16680, 80040, ...
 7 => 1,  7,  42,  252,  1470,   8610,  50190, ...
 8 => 1,  8,  56,  392,  2688,  18480, 126672, ...
 9 => 1,  9,  72,  576,  4536,  35784, 281736, ...
10 => 1, 10,  90,  810,  7200,  64080, ...
11 => 1, 11, 110, 1100, 10890, 107910, ...
12 => 1, 12, 132, 1452, 15840, 172920, ...
13 => 1, 13, 156, 1872, 22308, 265980, ...
14 => 1, 14, 182, 2366, 30576, 395304, ...
15 => 1, 15, 210, 2940, 40950, 570570, ...

```

# Answer
# Vyxal `s`, 9 bytes

```
ÞẊǎ:∷d=Ṡ†

```

Try it Online!

# Vyxal, 10 bytes

```
ÞẊǎ:∷d=Ṡ†∑

```

Try it Online!

```
ÞẊ         # Cartesian product; all ways to choose n items from k
  -----    # Next bit contains only vectorising elements, applied to each
  ǎ:       # Get substrings and duplicate
    ---    # Next bit over each substring
    ∷      # Get the second half
     d     # Double it
      =    # Is it equal to the original?
           # (If it is, that word's a square)
       Ṡ   # Sum each result - truthy if any are equal and word contains squares
        †  # NOT each result - those that are squarefree
         ∑ # Sum the result (s flag)

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), 40 bytes

```
Count[Or@@@Tuples@##,_?(FreeQ[x_||x_])]&

```

Try it online!

Takes a list of \\$k\\$ distinct non-Boolean symbols and a non-negative integer \\$n\\$.
> 6 votes

# Answer
# JavaScript (ES7), 90 bytes

Expects `(k)(n)` and returns the number of square-free words of length \\$n\\$, using \\$k\\$ symbols.

```
k=>n=>eval("for(i=t=k**n;i--;)t-=/(-.*),\\1/.test([...Array(n)].map((_,j)=>~(i/k**j%k)))")

```

Try it online!

### How?

The symbols are depicted with the decimal representation of the ones' complements of non-negative integers (\\$-1\\$, \\$-2\\$, \\$-3\\$, ... and so on) and implicitly joined with commas when the array is coerced to a string.

Hence the regular expression to detect squares: `/(-.*),\1/`.
> 4 votes

# Answer
# Pyth, 17 bytes

```
lf!:T"(.+)\\1"0^F

```

Test suite

Takes input as a list/tuple of the alphabet as a string and the word length as an integer.

##### Explanation:

```
lf!:T"(.+)\\1"0^F  | Full code
lf!:T"(.+)\\1"0^FQ | with implicit variables filled
-------------------+--------------------------------------------------------------------------------------------------------
               ^FQ | Repeated cartesian product (get all combinations of elements of the alphabet of the appropriate length)
 f                 | Filter this list for elements T such that
  !:T         0    |  T does not match the regex pattern
     "(.+)\\1"     |   which searches for a repeated substring
l                  | Print the length of the filtered list

```
> 4 votes

# Answer
# Brachylog, ~~19~~ 16 bytes

```
{gʰj₎∋ᵐ¬{s~jb}}ᶜ

```

Try it online!

*-3 thanks to Fatalize actually reading the challenge*

Input as a list `[alphabet of n characters, k]`.

Phenomenally slow, and I still can't help thinking there's a somewhat shorter way to brute-force the words.

```
{             }ᶜ    Count how many ways it's possible to
     ∋ᵐ             choose an element from each of
 gʰj₎               k copies of the supplied alphabet
       ¬{    }      such that it is impossible to
         s          find a substring
          ~j        which is something concatenated to itself
            b       which is non-empty.

```

The empty list is considered a substring of itself but nothing else, so this is correct for \\$n\>0\\$ without the `b`.

# Brachylog, 16 bytes

```
gʰj₎ẋ{sᶠ~jˢcĖ}ˢl

```

Try it online!

More or less the same thing, but handling \\$n=0\\$ slightly differently might offer an opportunity to shave something off, maybe...

```
    ẋ               Get the Cartesian product of
gʰj₎                k copies of the supplied alphabet,
     {       }ˢ     then keep only the tuples for which
      sᶠ            the list of all substrings
        ~jˢ         filtermapped from "squares" to their halves
           c        concatenated
            Ė       is the empty list.
               l    How many remain?

```

The empty list is considered a substring of itself but nothing else, so this is correct for \\$n\>0\\$ without the `c`.
> 4 votes

# Answer
# Haskell, 118 bytes

```
s []=1>0
s l=and[take n l/=take n(drop n l)|n<-[1..length l]]&&s(tail l)
n!k=length$filter s$mapM id$replicate n[1..k]

```

Try it Online!
> 4 votes

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

```
k=>g=(n,e,i=k)=>n?i&&g(n-1,[e,i])+g(n,e,i-1):!/(,.*)\1/.test(e)

```

Try it online!

# JavaScript (Node.js), 82 bytes

```
(k,r=0)=>g=(n,e)=>n?[...Array(k)].map((_,i)=>g(n-1,[e,i]))|r:r+=!/(,.*)\1/.test(e)

```

Try it online!

Something like Arnauld's solution but recursive.

`[e,i]` finally returns `,1,2,1` which provides convenience for checking, no need to add minus sign.
> 4 votes

# Answer
# Jelly, 10 bytes

```
ṗµẆ;"ḟƑ$)S

```

Try it online!

Went through no fewer than six 11-byters before finally reaching par, and turns out it's pretty much just what Dennis did on the linked challenge...

```
 µ      )     Map over
ṗ             the Cartesian power of the arguments:
  Ẇ           The list of the word's contiguous substrings
   ;"  $      with each one concatenated to itself,
      Ƒ       is it unchanged by
     ḟ        removing every substring of the word?
         S    Sum the results.

```
> 3 votes

# Answer
# Husk, 10 bytes

```
#ȯΠṁoẊ≠½Qπ

```

Try it online! or Try first elements of first few test cases

Input is arg1=`k`, arg2=`n`. Outputs number of square-free words of length `n`, using an alphabet with `k` symbols.

```
         π  # Cartesian arg2-th power of range [1..arg1]
#ȯ          # how many truthy elements of the following function:
        Q   #   get all contiguous sublists
   ṁo       #   and for each of them:
       ½    #     split them in half
     Ẋ≠     #     and check if both halves are unequal
  Π         #   now take the product of all of that
            #   (so product is zero if any sublist contained
            #   non-unequal halves, non-zero [truthy] otherwise)

```
> 3 votes

# Answer
# 05AB1E, 11 bytes

```
ãεŒε2äË≠]PO

```

Inputs \\$n\\$ and a list in the range \\$\[1,k\]\\$ and outputs the single result.

Try it online or verify all test cases.

**Explanation:**

```
ã         # Get the second (implicit) input-list [1,k] to the cartesian power of
          # the first (implicit) input-integer n, creating a list of all n-sized
          # sublists with elements from [1,k]
 ε        # Map over each inner list:
  Œ       #  Get all its sublists
   ε      #  Map over each sublist:
    2ä    #   Split it into two equal-sized halves
      Ë≠  #   Check that both halves are NOT equal
 ]        # Close the nested maps
  P       # Take the product of each inner list
   O      # Take the sum to get the amount of truthy values
          # (after which this is output implicitly as result)

```
> 3 votes

# Answer
# Retina, 43 bytes

```
1A`
$
;
"$+"+%Lv$`(.).*;
$>`$1$'
A`(.+)\1
;

```

Try it online! No test suite due to the way the program uses history. Takes input as `n` on the first line and a string of `k` letters (any printable ASCII except semicolon) on the second. Explanation:

```
1A`

```

Delete `n` from the buffer.

```
$
;

```

Append a marker.

```
"$+"+%Lv$`(.).*;
$>`$1$'

```

Generate the Cartesian product.

```
A`(.+)\1

```

Remove all square results.

```
;

```

Count the remaining results.
> 2 votes

# Answer
# Ruby, 64 bytes

```
->n,k{([*1..n]*k).permutation(k).uniq.count{|w|w*?_!~/(.+)_\1/}}

```

Try it online!
> 2 votes

# Answer
# Python 3, 106 bytes

```
lambda k,n:sum(not re.search(r'(.+)\1',''.join(p))for p in i.product(k,repeat=n))
import itertools as i,re

```

Try it online!

Inputs a string of \\$k\\$ distinct characters and a positive integer \\$n\\$.
Returns the number of square-free words of length \\$n\\$ for alphabets of length \\$k\\$.
> 2 votes

---
Tags: code-golf, sequence, combinatorics
---


title: Which character to change (Cops)

text:
# Question
Title: Which character to change (Cops)
Robbers Thread
Cops, your task is to chose a program that prints a string (you can choose). Although, if you change 1 character in your code, it should print another string.

But there's a twist: You should make your code hard to read, so that the robbers can't find your "changeable" character.

The winner cop is the user, with the shortest answer that wasn't cracked for a week.
If your submission wasn't cracked for a week, please reveal your character.

Cops, please include the output that should be printed if that specific character is changed in your code.

I will declare the winner cop and robber a week after this challenge is posted.

### Example submission (very easy to understand)

```
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes, prints a and b

1[`a`|`b

[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=1%5B%60a%60%7C%60b&inputs=&header=&footer=)

```

# Answer
# Python 3, 51 bytes, cracked by xnor

```
r=(1,)*8**9
r=r,len,
r=r,str,sum
print(len(str(r)))

```

Try it online!

The code outputs `402653253`. The changed code should instead output `134217728`.

I hope my `8**9` will make it difficult for any brute-force methods to work. Good luck!
> 15 votes

# Answer
# Python 2, 23 bytes (cracked by dingledooper)

```
print min(0,0)>min(0,0)

```

Try it online!

Should print `True`. Please don't brute force, I think it's a nice puzzle to solve.

---

**Bonus puzzle!**

**Python 2, 23 bytes**

```
print min(0,0)<min(0,0)

```

Try it online!

Should print `True`. Unfortunately this has an unintended solution of `print~min(0,0)<min(0,0)`, let's just pretend that doesn't exist.
> 10 votes

# Answer
# , 54 bytes, cracked by Dominic van Essen

```
a=b=c=2
for(a in 0:b)pi=pi+exists("c")/4
intToUtf8(pi)

```

Try it online!

The string to output is `"R"`.

---

> The solution is to replace the first line with `a=b=co2`: Try it online! The built-in dataset `co2` is then assigned to `a` and `b`. When calling `0:b`, only the first element of `co2` is kept (with a warning); it is worth `315.42`, which leads after the `for` loop to `pi=82.246`. This is rounded down to `82` by `intToUtf8`.
> 6 votes

# Answer
# Vyxal, 5 bytes, Cracked by pxeger

```
lyoal

```

Try it Online!

Take two.

Should output `name 'this_function' is not defined` and nothing else.

May not work in future versions of Vyxal as this is a bug that must be destroyed.

My intended solution was `lyxal`, which rickrolls you but first outputs the intended text, as you can see in this version, which adds a NOP.

I then realised `lyoax` works as well.

So yeah, interesting puzzle.
> 5 votes

# Answer
# Rattle, 5 bytes, Cracked by Shaggy

```
d\|!p

```

Try it Online!

This program outputs the string `d`. With one character changed, it should output the exact string `['d', '']`

> Cracked version:
>
> `d&|!p`
>
> Explanation:
>
> In the original code, `d\` is the value of a variable and `!p` is the code. `!p` is a program which prints the value at the top of the stack after parsing any input and variables. In this code, `d\` gets parsed to `d` (in this case, `\` is null).
>
> In the cracked code, the program stays the same but the variable is `d&`. The `&` operator in the variable acts as a separator, so the variable gets parsed to a list containing `'d'` and `''` (the second value is a null string). Then, the program converts this list to a string and outputs it.
> 5 votes

# Answer
# Pip, 6 bytes, Cracked by Daniel H.

```
-PI-PI

```

Try it online!

Outputs `-6.283185307179586`. The cracked version should output `3.141592653589794`.

---

> `PI` is `3.141592653589793`
> `-PI` is `-3.141592653589793`
> `PZ-PI` is `-3.14159265358979397985356295141.3-` (palindromize)
> `-PZ-PI` is `3.141592653589794` (casts to float, rounds ...939 to ...94)
> 5 votes

# Answer
# , 44 bytes, cracked by Dominic van Essen

```
a=b=2
for(a in 0:b)pi=a+a-pi
el(LETTERS[pi])

```

Try it online!

The string to output is `"R"`.

This is (deliberately) similar to my previous answer, but the solution uses a different trick.

> The solution is to replace `0:b` with `0xb` in the `for` loop: Try it online!. The number `Oxb` is 11 in hexadecimal. The loop is then just a single call for `a=11`, leading to `pi = 11+11-pi = 18.858...`, which gets rounded down to `18`. The 18th letter is `R`.
> 5 votes

# Answer
# Vyxal `vKOJdaBoVWT`, 17 bytes (safe)

```
₀h`f⋏⋏`½\zd+∑⇧¨U²

```

Try it Online!

Solution should output `FFIZZBUZZIFIZZBUZZZFIZZBUZZZFIZZBUZZBFIZZBUZZUFIZZBUZZZFIZZBUZZZFIZZBUZZ`.

Intended Solution:

> `₀h`f⋏⋏`½\zd+∑⇧/U²`
> All of the flags are valid flags, but the only one that actually did anything important was the `d` flag, which does a deep sum of the top of the stack before printing.
> The main obfuscated part of the program, `₀h`f⋏⋏`½\zd+∑⇧`, simply makes the string `FIZZBUZZ`.
> When executed online, `¨U` does nothing, and then `²` splits the string, which is put back together by the flag.
> In the solution, `/` causes the string to be wrapped. As a result, `w` would have also worked. `U` uniquifies the list, which does nothing since there's only one element. Now, `²` is acting on a list instead of a string, so it multiplies the string by itself, which creates a list that is summed by the flag and printed.
> 5 votes

# Answer
# Vyxal, 7 bytes, Cracked by Shaggy

```
kaka[|←

```

Try it Online!

Uses a quite obscure hack. Should print `z` if changed correctly.

Shaggy found exactly my intended solution - `kaka(|←`.

The 'obscure hack' I mentioned is Vyxal's 'ghost variable'. Vyxal's variables are referenced by `→name` and `←name`, but you can give one no name.

`(...)` is Vyxal's loop construct, but you can add a variable name with `(name|...)` and that variable will contain the current iteration. This also works with no name, so `(|...)` sets the ghost variable to whichever iteration, then  gets the current iteration number. Vyxal's structures autocomplete, so `(|...` without a closing paren is fine.

You're iterating over `ka`, which is the lowercase alphabet, so at the end the stack looks like `a , b, c... z`. Finally, Vyxal's implicit output takes care of the rest, returning the `z`.
> 4 votes

# Answer
# Vyxal `o`, 13 bytes, cracked by A username

```
`₴ḟ `₴`Buzz`F

```

Try it Online!

Solution should print `FizzBuzz`.

Intended solution:

> ``₴ḟ `k`Buzz`F`
> I discovered a parsing bug where you could put a string between the two parts of a diagraph, and the diagraph would still work. In this case, the program is being parsed as ``₴ḟ ``Buzz`kF`. The first two strings, which are `Fizz`  and `Buzz`, don't matter at all, and instead, the final diagraph simply pushes `FizzBuzz`.
> 4 votes

# Answer
# Vyxal, 34 bytes (safe)

```
u₁7₌I"
∑C$3Ǎ⇧
*C₍⇧⇩+
Ė_"v⇩÷
CĖ›½½∑

```

Try it Online!

Solution should output `29`.

Solution:

> ```
> u₁7₌I"
> ∑C$3Ǎ⇧
> *C₍⇧⇩+
> Ė_"v⇩÷øCĖ›½½∑
> ```

Explanation:

> Replaces the last newline with `ø`, which causes the string to be wrapped in `»`, which is the delimiter for compressed numbers. The string is then decompressed by executing it as Vyxal code with the `Ė` command, then it is incremented, halved twice, and the digits are added together, equaling 29.
> 4 votes

# Answer
# , 51 bytes, cracked by Dominic van Essen

```
x=z=6
yy=0
while(x+yy-1>yy){x=x-1;z=z+1}
LETTERS[z]

```

Try it online!

The string to output is `"R"`. The previous version allowed for a crack I hadn't intended, found by pxeger. I hope this version is immune to that.

---

> The crack is to replace the while condition `x+yy-1>yy` by `x+yy->>yy`. This uses global leftwards assignment `->>`, replacing the value of `yy` at each iteration. That way, we go through the loop 12 times in total, leading to the intended value `z=18`. In real life, no one ever uses global leftwards assignment, nor should they!
> This challenge was inspired by a bug I often see in students' code, in which they expect `if(x<-1)...` to compare `x` to `-1`, but instead it assigns `1` to `x`. The way to avoid this bug is to type `if(x < -1)...` of course. IMO, this regular bug is the main argument against using `<-` instead of `=` for assignment (there are a few other arguments in the other direction).
> 4 votes

# Answer
# JavaScript (SpiderMonkey), 28 bytes, cracked by m90

```
a=9
if(a>0)a=0
a>9&&print(a)

```

Try it online!

Output `9` is expected.

~~A very easy trick. Maybe can be cracked soon (as it is quite short).~~

---

> Line Feed is a character.
> 4 votes

# Answer
# \>\<\>, 227 bytes, Cracked by m90

```
 \   ÇÇÇÇÇÇÇÇ
/!\; ÇÇÇÇÇÇÇÇ
\n/!<ÇÇÇÇÇÇÇÇ
 !   ÇÇÇÇÇÇÇÇ
 >  ^ÇÇÇÇÇÇÇÇ
\\2   \! \/! ~! \
 ÇÇÇ\ v! ~      /
 ÇÇÇÇÇ\'"a"\ÇÇÇÇÇ
 ÇÇÇÇÇÇÇÇ\ /ÇÇÇÇÇ

```

Try it online!

The output must be `199`

~~I'm not sure if some robbers can crack...~~ Cracked in 6 Days, Same Solution.
> 4 votes

# Answer
# brainfuck (cell-size 32, no change on EOF), 2,970,327,283 bytes

```
(...)[->(...)<]>.

```

> It's a start.

> This seems like a very boring CnR, any answer will either be trivially brute forceable or take advantage of some weird unicode + halting problem thing that makes it very tedious and not really easily doable by a human anyway. -Dotcomma Programs

Happy new year! The first `(...)` contains 2950107175 `+`s, and the second `(...)` contains 20220101 `+`s. It prints  right now - make it print .

This is the only brainfuck answer I could write.
> 4 votes

# Answer
# Vyxal, 20 bytes, cracked by Aaron Miller

```
`Ẇ₁¹kḢ`:∧λf⇧\#¯ḣ⌐ƒż1

```

Try it Online!

Alright. My turn.

You need to make this epic lambda output `who is joe joe mama`.

---

If you thought that the lambda actually did anything, then you were wrong. The first string in the program is to act as a distraction, as the answer is that everything after the `:` is the compressed version of the output string.
> 3 votes

# Answer
# Vyxal `O`, 28 bytes (safe)

```
⁺⟇C‛bf½+ṅĖp⇩D∇⇧$⇧∇∇⇧WṄ3ẇḢht₴

```

Try it Online!

Solution:

> `⁺⟇C‛bf½+ṅĖpøD∇⇧$⇧∇∇⇧WṄ3ẇḢht₴`

Explanation:

> Changes the lowercasing and triplicating to dictionary compression. The dictionary compressed string is `₴ḟ₴ḣ`, which contains the target string. From there, the rest of the program just does a bunch of random junk to it and winds up with  which is the target string. The  at the end of the program is just a red herring. :)
> 3 votes

# Answer
# Jelly, 11 bytes, cracked by Aaron Miller

```
“Y$Ḥß»“¿<ȧ»

```

Try it online!

The output should be `hyper-neutrino` cause I'm lazy

> `“Y$Ḥß““¿<ȧ»` is a list of compressed strings `[“Y$Ḥß», “», “¿<ȧ»]`.
>
> * `“Y$Ḥß»` decompresses to `hyper-` (and is a suboptimal compression, specifically to confuse hyper and get him overthinking about the compression engine :P)
> * `“»` decompresses the the empty string, which doesn't then affect the output
> * `“¿<ȧ»` decompresses to `neutrino`
>
> Then, Jelly smash-prints the string `["hyper-", "", "neutrino"]` into `hyper-neutrino`
> 3 votes

# Answer
# Python 2, 72 bytes, cracked by the default.

```
print pow(2,2**1337133713371337,195889276175237072760362930940173700767)

```

Expected output:

```
188867410716634269084427012487211003700

```
> 3 votes

# Answer
# Japt, 5 bytes, cracked by user

My turn! Coming up with C&R entries in Japt is always tricky because ... of reasons that would help you solve this! :p (and 'cause I suck at it!) Also, the longer a programme is, the more chance there is for an unintended crack or 2 but, the shorter it is, the easier it is to crack. So this will probably be easily cracked.

Original outputs `0` (as a string), cracked version should output `s`.

```
¤ùÅÔÌ

```

Try it online!
> 3 votes

# Answer
# Japt, 24 bytes

Hoping this one might be *slightly* more challenging than my first attempt but I somehow doubt it. The original outputs `1`, the cracked version should output `11` (both as strings).

```
@TwXµY *!ZøX ªX+YÑ}gB Ìs

```

Try it online!
> 3 votes

# Answer
# , 45 bytes, cracked by pajonk

```
a=b=c=2
for(a in 1:b)c=c*pi
el(LETTERS[-c:0])

```

Try it online!

The string to output is `"R"`.

This is an homage to Robin Ryder's series of challenges, although I think his ones were cleverer...
> 3 votes

# Answer
# , 59 bytes, cracked by Dominic

```
a=as.numeric
bb=strrep(11,1)
"if"(a(bb),LETTERS[a(bb)],"R")

```

Try it online!

The string to output is `"R"`.

Definitely no match for @Robin's challenges here, but when already this thread is full of  submissions, why not another one?

---

Intended crack: Try it online!
> 3 votes

# Answer
# Python 3, 226 bytes - cracked by Zachary Cotton

```
import operator as o
import inspect as i
a,d = 37,lambda n:n if len(str(n))==1else d(sum(map(int,str(n))))
for k, v in{d(sum(map(ord, n))): f for n, f in i.getmembers(o,i.isbuiltin)[::11]}.items():
 a = int(v(a,k**2))
print(a)

```

Try it online!

It currently prints `520`, but it should print `5521`. I hope you will enjoy this. I think once you find out the parts of the puzzle, you should be able to see what to change.
> 3 votes

# Answer
# APL (Dyalog Unicode), 19 bytes; cracked by Bubbler

```
{(⍵ ⍵)(⍵ ⍵)(⍵ ⍵)},8

```

Prints  `8 8 8 8 8 8` : Try it online!

Change one character and make it print `1` instead!
> 3 votes

# Answer
# APL (Dyalog Extended), 8 bytes; cracked by Bubbler

```
≢∊⎕A⍨¨⎕A

```

Prints `676`: Try it online!

Change one character and make it print `286` instead!
> 3 votes

# Answer
# Yggdrasil, 3 bytes, cracked by A username

```
;.:

```

Try it online!

Solution should print `..:`.
> 3 votes

# Answer
# brainfuck, 29 bytes, Cracked by ovs

```
.+[.[->+>+<<]+[>--<+++++]>+<]

```

Try it online!

Should output

```
�:sIX=1
×}ð :kAH%  ÊoÕàQÍº#y8M!
ÇmÐÙEºñ(µyÊßEÀ¡ý:Ó©]
·]°©õ:Ë¡EéÊOµ ñ-ºÙøm
§My¥ºûQèÕYÊ¿%A]:3 Ø}ñ
=pIU:+ÈeÉÊ/`ºã9¸á
-Pº[±¨õ9Ê@á½:iÑ
w0éµ:a©Êu 1íºCxÁ
g
¹eº»hÊå

```

SE swallowed some unprintables, so here's a hexdump:

```
00000000: 0001 c29d 3a73 4958 3d31 0ac3 977d c3b0  ....:sIX=1...}..
00000010: 09c2 953a 6b41 4825 09c3 8a6f c395 c3a0  ...:kAH%...o....
00000020: 51c3 8dc2 ba23 7938 4d21 0ac3 876d c390  Q....#y8M!...m..
00000030: c399 45c2 bac2 9bc3 b128 c2b5 79c3 8ac3  ..E......(..y...
00000040: 9f45 c380 c2a1 c3bd 3ac3 93c2 a918 5d11  .E......:.....].
00000050: 0ac2 b75d c2b0 c2a9 c3b5 3ac3 8bc2 a108  ...]......:.....
00000060: 45c3 a9c3 8a4f c2b5 20c3 b12d c2ba c283  E....O.. ..-....
00000070: c399 c3b8 6d01 0ac2 a74d c290 79c2 a5c2  ....m....M..y...
00000080: bac3 bb51 c3a8 c395 59c3 8ac2 bf25 c280  ...Q....Y....%..
00000090: 415d 3a33 09c3 987d c3b1 0ac2 973d 7049  A]:3...}.....=pI
000000a0: 553a 2b01 c388 65c3 89c3 8a2f c295 60c2  U:+...e..../..`.
000000b0: 91c2 8dc2 bac3 a339 c2b8 c28d c3a1 0ac2  .......9........
000000c0: 872d 5019 05c2 ba5b c2b1 c2a8 c3b5 39c3  .-P....[......9.
000000d0: 8ac2 9f05 40c3 a1c2 bd3a c293 69c2 98c2  ....@....:..i...
000000e0: 9dc3 910a 771d 30c3 a9c2 b53a c28b 61c2  ....w.0....:..a.
000000f0: 88c2 85c2 a9c3 8a0f 7520 31c3 adc2 ba43  ........u 1....C
00000100: c299 78c2 adc3 810a 670a 10c2 b965 c2ba  ..x.....g....e..
00000110: c2bb 1168 1519 c38a 7fc3 a5              ...h.......

```

And no, I don't know *how* I got this result.
> 3 votes

# Answer
# Pip, 5 bytes, cracked by Daniel H.

```
****t

```

Outputs `179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216`. (DON'T Try it online! This code requires the current version of Pip. You can run it here.)

The cracked version should output `42`.

---

The intended solution was

> `**E*t`

which is basically the same as Daniel's crack.

In hindsight,

> using an operator that's synonymous with `**`

may not have been the *best* idea, but the `42` output was too good to pass up.
> 2 votes

# Answer
# Vyxal, 24 bytes, Cracked by Aaron Miller.

```
kH:`string`D‟‟Ẋf∑vd∑qĖ₁Ẏ

```

Try it Online!

Output should be

```
HH\`\`HHmorningHHoccupationalHH\`\`ee\`\`eemorningeeoccupationalee\`\`ll\`\`llmorninglloccupationall

```

A mess.
> 2 votes

# Answer
# JavaScript (Node.js), 155 bytes, Cracked by hyper-neutrino

```
z=247275939563830539741033018025n
k=''
e='Hello, world'
while(z) k+=String.fromCharCode(Number(z%128n)),z/=128n;
console.log(eval([...k].reverse().join``))

```

Try it online!

The output should be `[Function: bound consoleCall]`.
> 2 votes

# Answer
# Rattle, 8 bytes, cracked by Aaron Miller

```
<[c]9I^p

```

Try it Online!

This code outputs the string `10`. With one character changed, it should output the string `100`.

Explanation of crack:

> "\<" decrements the pointer, which wraps around to slot 99. "\[c\]@" concatenates the value at this memory slot (0) to the value on top of the stack. This results in a string of 100 zeroes. "I^" takes the length of this string, giving 100. "p" converts 100 to a string and prints it.
> 2 votes

# Answer
# Vyxal `s`, 13 bytes, Cracked by Aaron Miller

```
khǍ⇩k•kFk¹↔sU

```

Try it Online!

Intended text: `bcfgjkmnpqstvxz`.
> 2 votes

# Answer
# Japt, 10 bytes, cracked by dingledooper

```
"1,2"k@X+2

```

Try it online!

The intended output is `3.4`. I have no idea how hard this is to crack, since I barely know any Japt, but hopefully it's not too easy.
> 2 votes

# Answer
# , 77 bytes, cracked by tsh

```
PO=0
TA=TO =min(0 * 0 * 0, FALSE, 0 * 0 * 0)
if(TA|TO&TA&TO)PO=18
LETTERS[PO]

```

Try it online!

As usual, the string to output is `"R"`.

---

A previous version of this challenge allowed an unintended crack, found by Dominic van Essen:

## , 71 bytes

```
PO=0
TA=TO =min(0 * 0 * 0, FALSE, 0 * 0 * 0)
if(TA|TO)PO=18
LETTERS[PO]

```

Try it online!
> 2 votes

# Answer
# Vyxal, 14 bytes, Cracked by Aaron Miller

```
‛ø»:K:Ẋf∑$βS2Ẏ

```

Try it Online!

Should output 14.

My intended solution was:

```
»ø»:K:Ẋf∑$βS2Ẏ

```

I'm quite surprised that changing the *word* worked, my intention was changing it to a *number*, where the output would be 1412 before slicing.
> 2 votes

# Answer
# \>\<\>, 536 bytes, Cracked by ovs

```
\\ /   \  /  9    \
/\     /  /\  /   \\
    / 1/  \       \\\
\\ //  \  \\  /    \\\
 \\  /\ / \\\/ \   \\\\
 ///  \\   \ \//   // \\
/ /\  \\\ \/ \\ \  \\/ /
\\ / \  \\     /\\ // /
//  /     \\\   \\ \ \  \
\\\  /\\/// \ \\// /  \ +
///\ /\/\/ //   /    /
\\/\\/\/\/ / /// / /3 / n\
// \\     /         \ / /
  \ \/\/\/ / // // \/ /  /
\\  //\/\/ / / /  / ;
   \//\/\\ /\/\ /     /
 \  \    \//\ /    \/
 /       //  \ ///
/\\/\/ /\///\\ //
  \/\/
  //\\//\/     \\
 \\  \/    /\/ /\\
\ \  \/  \\  /  //
  \  \/  \/
     \     /\/ \/

```

Try it online!

A literal maze of mirrors.

My intended solution was:

```

\\ /   \  /  9    \
/\     /  /\  /   \\
    / 1/  \       \\\
\\ //  \  \\  /    \\\
 \\  /\ / \\\/ \   \\\\
 ///  \\   \ \//   // \\
/ /\  \\\ \/ \\ \  \\/ /
\\ / \  \\     /\\ // /
//  /     \\\   \\ \ \  \
\\\  /\\/// \ \\// /  \ +
///\ /\/\/ //   /    /
\\/\\/\/\/ / /// / /3 / n\
// \\     /         \ / /
  \ \/\/\/ / // // \/ /  /
\\  //\/\/ / / /  / ;
   \//\/\\ /\/\ /     /
 \  \    \//\ /    \/
 /       //  \ ///
/\\/\/ /\///\\ //
  \/\**X**
  //\\//\/     \\
 \\  \/    /\/ /\\
\ \  \/  \\  /  //
  \  \/  \/
     \     /\/ \/

```
where the `X` is a `\`, and originally was a `/`.

Execution paths:

I'm not sure if this makes it more understandable or more confusing.

Red is path before the split, yellow is original, orange is correct path.
> 2 votes

# Answer
# Julia 1.x, 53 bytes, Cracked by Robin Ryder

```
show(sum(count.(==('1'),bitstring.(Int16[9973%36]))))

```

Try it online!

should output `5`
> 2 votes

# Answer
# JavaScript (REPL), 17 bytes

```
a=!![],a++,a+=![]

```

Edit : Actually output "2", should output 3 when the good char is modified

(not sure if the console.log was required or not...)

https://jsconsole.com/
> 2 votes

# Answer
# PHP 7.4.2 - 23 bytes

`echo md5("leetspeak!");`

Let's go for another try ! :)

This one should output

> 20bff2eab610b29d183a363727b9bfb5

if correctly modified

https://wtools.io/php-sandbox
> 2 votes

# Answer
# Python 3, 44 bytes, cracked by Dlosc

```
a=6
b=++a++a++++a++a
a=5*5/5**2
print(b*a-b)

```

Try it online!

## Cracked code by Dlosc:

# Python 3, 44 bytes

```
a=6
b=++a++a++++a++a
a=5*5/5**2
print(b*1-b)

```

Try it online!
> 2 votes

# Answer
# IPython, 9 bytes

```
print(1)#

```

Should print nothing. I rate this easy and hard.
> 2 votes

# Answer
# APOL, 70 bytes (Easy)

```
ƒ(56 ¿(%(I(I(∈ )) 4) ¿(F :(33:3():33::()) ¿(F 2  ¿(≐(∈) 2 3))))((X)) )

```

The cracked output is:

```
[None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2, None, 2, 2, 2]

```
> 2 votes

# Answer
# Python 3, 35 bytes

```
a=-123**6;b=-456**6;print(a*b|b//a)

```

Try it online!

Might be a bit simple, but I had fun writing it. Output should be `31132910605162826264952179236`
> 2 votes

# Answer
# Jelly, 254 bytes (cracked by the default.)

```
“5gỊƑ!ṆḥḌ³`⁻Ɓc?Ạ°þạḅI§Ɠ¦mṪ9ʂ:Nȯx1®Ḟ ƭḣTsÄẉṭ7|ẏẋzⱮɦḲ⁵.ṗbÐɱ8Ñ3"Øȧ¡Ė÷ʠ\¬ṇƥṀœṙRṅẈɓẒ#Ẏỵ⁼Ȧ©MỴƤ⁷ẹ⁴ż;OṃċẊnFḶ¤ȤḟỤẇçİ/ƒjƬhƙA2PẸtX¿ṢḢṡyiṂCd)ÆṣĠʋŒ-ė~YZ⁾ĿṘ²ŀ'ṄLȷU£BSƲɼṛñ½ȥÞ6pḂæ×ẆɠG4ịı$EƊ¹¥ḃɗ}DK]u*ġṚk⁹ɲḊµṾW+,ȧwß⁺⁸0ọv(<Ɲṁḍl=Q+ð@Çø[Żṫoera&Ọ¢Vḷ¶Ṗ€ƈḋ{⁶ƇĊqḄHḳJ⁽Ȯ%>^ḤṠfƘṬ‘Œ¿

```

Try It Online!

The output should be:

```
690699296939718117350621606422816362267173158421165414491974510998788124940831200375657067696758989277663531427881606883007285313136136830578271394860909143130892610035752665368298072483371326623846259135567658705756844088966332891398225673436164647788793408591250973256547482034045337013090045826070073469995435050529779518827764039871801756995315995194485429761879045854501788974715014302780100588547060896111645050429507146677667643527115067082983636640551198432670539417621925424456729027

```

I imagine this shouldn't be difficult, even just to brute-force with Jelly's SBCS like someone in chat pointed out. I am working on a solution that will be slow to verify so that it is not brute-forceable (even though I don't think any of the other solutions have been brute-forced, I want to try this just for proof of concept), and using permutations or powersets is probably a good approach.

---

The intended intended solution was to reverse the permutation index. However, for whatever reason, generating a random permutation of 1..250 and indexing into the codepage gave me a duplicate, so I'm not sure if I copy-pasted the wrong string or I'm just really fucking stupid.

Either way, brute-force crack would be the only valid solution since I messed up the format.
> 1 votes

# Answer
# , 48 bytes, cracked by pxeger

```
x=z=6
y=0
while(x+y-1>y){x=x-1;z=z+1}
LETTERS[z]

```

Try it online!

Once again, the string to output is `"R"`.

I think and hope the solution is unique, but I might have missed something. Edit: indeed I had missed something...
> 1 votes

# Answer
# Brainf\***, 51 bytes - cracked by dingledooper

```
++++++++++[>+++++++++++<-]>++.-------.+++++.++++++.

```

Try it Online!

Right now it outputs `pint`. Can you make it output `ohms`?
> 1 votes

# Answer
# , 7 bytes, cracked by Adám

```
13024e0

```

Try it online!

Outputs `13024`. Cracked solution should output `69420` instead.
> 1 votes

# Answer
# Labyrinth, 7 bytes, cracked by m90

```
999
!!@

```

Try it online!

Outputs `99`. Change it to `9900`.
> 1 votes

---
Tags: code-golf, string, source-layout, cops-and-robbers
---


title: Shanghai ascii game sticks

text:
# Question
Title: Shanghai ascii game sticks
Remove one stick and output the stack updated.

# Description

You can remove only sticks on top( completely drawn).

You can assume:

* there are 5 sticks on the table.
* there's one and only one stick you can remove.
* sticks are recognizable : there aren't overlapping sticks on the same orientation and there aren't sticks joined which form a longer line.
* input should be not ambiguous, there should be only one valid solution as pointed out by @Arnauld comment, for example this input is not valid
* Trailing /leading spaces doesn't matter.

Sticks are 4 chars long and are placed vertically or horizontally.

```
   |          ————
   |
   |
   |

```

**Test cases** \[Before, after\]

```
["
 |||
 —|——
 |||
 |||—
      ",
"
 | |
 ————
 | |
 |—|—
      "],
["
 |||
 —|——
 |||
 |||——

       ",
"
 | |
 ————
 | |
 |—|——

       "],
["
 |||
 —|——
 |||
 |||———

        ",
"
 | |
 ————
 | |
 | |———

        "],
["
    |
 ———|
 |———
 |  |
 |————
       ",
"
    |
 ———|
 |———
 |  |
 |
       "],
["
   |
   |
   |
  ————
  | |
  | |
  |———
    |
          ",
"
   |
   |
   |
  ||
  | |
  | |
  |———
    |
          "],
["

   |
  ————
   ——|—
   |———
     |

         ",
"

   |
   | |
   ——|—
   |———
     |

         "],
["

 | |
 ————|
 | |———
 | | |
     |

        ",
"

 | |
 | | |
 | |———
 | | |
     |

        "],
["

 ———|
  ——|—
   —|——
    |———

         ",
"

 ————
  ————
   ————
    ————

         "],
["
   |
  —||—
   ||
  ————
  | |
  |
  |
         ",
"
   |
  —||—
   ||
  |||
  | |
  |
  |
         "],
["

 |——— |
 |  | |
 |  | |
 ———| |

        ",
"

 |———
 |  |
 |  |
 ———|

        "]

```

**Input specifications**
You can add trailing and leading whitespaces / lines as your wish, , I hope this can help focusing on the task by avoiding data bounds checking.

here is a small program to get input data in some formatting. In the header section you can change some characters like array bounds and others.
Data is in the form of a square matrix and the image is surrounded by whitespaces.

# Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT, return it as a function result or error message/s.
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

Sandbox

# Answer
> 4 votes
# Charcoal, 102 bytes

```
ＷＳ⊞υιυ≔ΦＬυ№§υι×-⁴η≔Σηζ¿η‖Ｔ↗«≔Ｅθ⭆υ§λκυ≔ΣΦＬυ№§υι×|⁴ζ»Ｊζ⌕§υζ×§-|¬η⁴Ｆ⁴↓§ -⊙ＥＥrlＫＤχ✳κ…κ⌕Ｅκ›μ ⁰∧›⁵Ｌκ№κ-¿η‖Ｔ↗

```

Try it online! Link is to verbose version of code. Takes input as a list of strings containing spaces, minus signs or pipes. Explanation:

```
ＷＳ⊞υι

```

Input the game.

```
υ

```

Output the game to the canvas.

```
≔ΦＬυ№§υι×-⁴η≔Σηζ

```

Try to locate a horizontal stick.

```
¿η

```

If one was found, then...

```
‖Ｔ↗

```

... reflect the canvas transforming between minus signs and pipes, ...

```
«

```

Otherwise, ...

```
≔Ｅθ⭆υ§λκυ

```

... transpose the game array (sadly without transforming), ...

```
≔ΣΦＬυ№§υι×|⁴ζ

```

... and find a vertical stick.

```
»Ｊζ⌕§υζ×§-|¬η⁴

```

Jump to the stick's current location on the canvas.

```
Ｆ⁴↓§ -⊙ＥＥrlＫＤχ✳κ…κ⌕Ｅκ›μ ⁰∧›⁵Ｌκ№κ-

```

Overwrite the pipes of the (possibly transformed) stick with spaces, unless there are at most four consecutive non-blank characters (including the pipe itself) including at least one minus sign on at least one side of the pipe, in which case overwrite with a minus sign instead.

```
¿η‖Ｔ↗

```

Transform the canvas back if necessary before it's implicitly printed.

---
Tags: code-golf, ascii-art, path-finding
---


title: Output a Pyramid (or Highway)

text:
# Question
Title: Output a Pyramid (or Highway)
Given a non-empty string s, with even length, and a positive integer n, representing its height, compose a pyramid using the following rules:

The pyramid should contain n non-empty lines; trailing newlines are allowed. For each 1 \<= i \<= n, the i-th line should contain the string with each individual character repeated in-place i times; abcd repeated 3 times as such becomes aaabbbcccddd. Each line should be centered with padding spaces so that the middle of each line is vertically aligned. Trailing spaces at the end of each line are permitted. You can also have up to one leading newline but no other whitespace before the first line.

The input string is not guaranteed to be a palindrome.

# Test Case

```
s = 'o-o  o-o', n = 10:

                                    o-o  o-o
                                oo--oo    oo--oo
                            ooo---ooo      ooo---ooo
                        oooo----oooo        oooo----oooo
                    ooooo-----ooooo          ooooo-----ooooo
                oooooo------oooooo            oooooo------oooooo
            ooooooo-------ooooooo              ooooooo-------ooooooo
        oooooooo--------oooooooo                oooooooo--------oooooooo
    ooooooooo---------ooooooooo                  ooooooooo---------ooooooooo
oooooooooo----------oooooooooo                    oooooooooo----------oooooooooo

```

# Answer
# 05AB1E, 9 bytes

```
γ².D)ƶJ.C

```

Try it online!

---

`γ` was, in no short amount, inspired by Adnan's answer; but `S` would also work.

---

```
γ          # Split into runs.    | ['0','-','0']
 ².D)      # Push n times.       | [['0','-','0'],['0','-','0'],['0','-','0']]
     ƶ     # Lift by index.      | [['0','-','0'],['00','---','00'],['000','---','000']]
      J    # Inner join.         | ['0-0','00--00','000---000']
       .C  # Center.             | Expected output.

```
> 12 votes

# Answer
# 05AB1E, 11 bytes

```
F²γN>×J}».C

```

Uses the **05AB1E** encoding. Try it online!
> 12 votes

# Answer
# Jelly, ~~14~~ 13 bytes

```
LH×Ḷ}Ṛ⁶ẋżxÐ€Y

```

Try it online!

### How it works

```
LH×Ḷ}Ṛ⁶ẋżxÐ€Y  Main link. Arguments: s (string), n (integer)

L              Get the length l of s.
 H             Halve it, yielding l/2.
   Ḷ}          Unlength right; yield [0, ... n-1].
  ×            Compute [0, l/2, ..., l(n-1)/2].
     Ṛ         Reverse; yield [l(n-1)/2, ..., l/2, 0].
      ⁶ẋ       Space repeat; create string of that many spaces.
         xÐ€   Repeat in-place each; repeat the individual characters of s
               1, ..., n times, yielding an array of n strings.
        ż      Zipwith; pair the k-th string of spaces with the k-th string of
               repeated characters of s.
            Y  Sepatate the resulting pairs by linefeeds.

```
> 8 votes

# Answer
# C# (.NET Core), 139 137 136 130 bytes

```
using System.Linq;s=>n=>Enumerable.Range(0,n).Select(i=>"".PadLeft((n+~i)*s.Length/2)+string.Concat(s.Select(c=>new string(c,i))))

```

Try it online!

Returns an enumeration of `string`s with the lines of the drawing. Once joined the result is like this:

```
                        ಠ_ಠ  ಠ_ಠ
                    ಠಠ__ಠಠ    ಠಠ__ಠಠ
                ಠಠಠ___ಠಠಠ      ಠಠಠ___ಠಠಠ
            ಠಠಠಠ____ಠಠಠಠ        ಠಠಠಠ____ಠಠಠಠ
        ಠಠಠಠಠ_____ಠಠಠಠಠ          ಠಠಠಠಠ_____ಠಠಠಠಠ
    ಠಠಠಠಠಠ______ಠಠಠಠಠಠ            ಠಠಠಠಠಠ______ಠಠಠಠಠಠ
ಠಠಠಠಠಠಠ_______ಠಠಠಠಠಠಠ              ಠಠಠಠಠಠಠ_______ಠಠಠಠಠಠಠ

```
* 2 bytes saved thanks to Kevin Cruijssen!
* 1 byte saved thanks to Value Ink!
* 6 bytes saved thanks to LiefdeWen!
> 8 votes

# Answer
## Cheddar, ~~71~~ 64 bytes

*Saved 7 bytes thanks to @ValueInk*

```
(s,n)->(1|>n=>i->(s.len*(n-i)/2)*" "+s.sub(/./g,"$&"*i)).asLines

```

Try it online! I will add explanation in a bit

Explanation

```
(string, count)->(
   1 |> count          // 1..count, the amount of rep/char per line
     => i -> (         // Map over the range
        s.len*(n-i)/2  // Calculate amount of spaces and repeat by it.
     )*" "
     + s.sub(/./g,"$&"*i) // replace each character, duplicate the amount of times `*i`
).asLines              // return the above joined with newlines

```
> 7 votes

# Answer
# Python 2, ~~75~~ 77 bytes

```
s,n=input()
for i in range(n):print''.join(c*-~i for c in s).center(len(s)*n)

```

Try it online!
> 5 votes

# Answer
# Ruby, 58 bytes

```
->s,n{(1..n).map{|i|s.gsub(/./){$&*i}.center s.size*n}*$/}

```

Try it online!
> 5 votes

# Answer
# Java 11, ~~188~~ ~~186~~ ~~185~~ ~~183~~ ~~181~~ ~~173~~ ~~171~~ 133 bytes

```
s->n->{var r="";for(int l=s.length()/2,x=l*n,i=0;i++<n;r+="\n"){r+=" ".repeat(x-i*l);for(var c:s.split(""))r+=c.repeat(i);}return r;}

```

-2 bytes (185 → 183) due to a bug-fix (it was outputting `n+1` lines instead of `n`). Doesn't happen often that a bug-fix saves bytes. :)
-2 bytes (183 → 181) thanks to *@OlivierGrégoire*
-2 bytes (173 → 171) thanks to *@ceilingcat*

Try it online.

**Explanation:**

```
s->n->{                    // Method with String & integer parameters and String return
  var r="";                //  Return-String, starting empty
  for(int l=s.length()/2,  //  Halve the length of the input-String
          x=l*n,           //  Set `x` to halve the length multiplied by the input
          i=0;i++<n;       //  Loop `i` in the range (0,n):
      r+="\n"){            //    And after every iteration, add a new-line
    r+=" ".repeat(x-i*l);  //   Add the appropriate amount of trailing spaces
    for(var c:s.split("")) //   Inner loop over the characters of the String:
      r+=c.repeat(i);}     //    Repeat each character `i` amount of times
  return r;}               //  Return the result-String

```
> 5 votes

# Answer
# Javascript, 105 bytes

```
(s,n)=>Array(N=n).fill().reduce(a=>a+'\n'+' '.repeat(--n*s.length/2)+s.replace(/./g,_=>_.repeat(N-n)),'')

```

After a few years off, the Stretch Maniac is back, hopefully slightly more educated this time.
> 4 votes

# Answer
## JavaScript (ES6), 85 bytes

Takes input in currying syntax `(string)(height)`. Includes a leading newline.

```
s=>g=(n,p=`
`)=>n?g(n-1,p+' '.repeat(s.length/2))+p+s.replace(/./g,c=>c.repeat(n)):''

```

### Demo

```
let f =

s=>g=(n,p=`
`)=>n?g(n-1,p+' '.repeat(s.length/2))+p+s.replace(/./g,c=>c.repeat(n)):''

o.innerHTML = f('o-o  o-o')(10)
```

```
<pre id=o></pre>
```
> 4 votes

# Answer
# Charcoal, 19 bytes

```
Ｆ⁺¹Ｎ«Ｊ±×ι÷Ｌη²ιＦηＦικ

```

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

```
Ｆ⁺¹Ｎ«       for (Plus(1, InputNumber())) {

```

We need lines repeated `1..n` times. The easiest way to achieve this is to loop from 0 to n, as loop 0 is basically a no-op.

```
Ｊ±×ι÷Ｌη²ι       JumpTo(Negate(Times(i, IntDivide(Length(h), 2))), i);

```

Position the cursor so that the resulting line is centred.

```
ＦηＦικ           for (h) for (i) Print(k);

```

And this is how simple printing each character repeated `i` times is.
> 4 votes

# Answer
# SOGL V0.12, 14 bytes

```
ā.∫dI*Hd⁄»±IFž

```

Try it Here!
> 4 votes

# Answer
# Japt `-R`, ~~20~~ ~~19~~ ~~14~~ 8 bytes

```
õ@VmpXÃû

```

Try it
> 3 votes

# Answer
# Haskell, ~~79~~ ~~73~~ 69 bytes

* Saved 4 bytes thanks to nimi

```
s#n=unlines[(' '<$[1,3..(n-m)*length s])++((<$[1..m])=<<s)|m<-[1..n]]

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog), ~~33~~ 31 bytes

*2 bytes golfed thanks to @ZacharyT by removing unnecessary parentheses*

```
{↑((' '/⍨(.5×≢⍵)×⍺-⊢),⍵/⍨⊢)¨⍳⍺}

```

Try it online!

### Explanation

The right argument  is the string and the left argument  is the number.

```
{↑((' '/⍨(.5×≢⍵)×⍺-⊢),⍵/⍨⊢)¨⍳⍺}
                             ⍳⍺      Range 1 .. ⍺
  (                        )¨        For each element (let's call it i) do:
                      ⍵/⍨⊢          Replicate ⍵ i times
  (                 ),               Concatenated with
         (.5×≢⍵)×⍺-⊢                (⍺-i)×(len(⍵)×0.5)
   ' '/⍨                                spaces
 ↑                                    Convert the resulting array to a 2D matrix

```
> 3 votes

# Answer
**SWI Prolog, 398 bytes**

It is not the most compact solution (maybe somewhere reinventing the wheel instead of using built-in procedures), but it appers to work.

```
w(0).
w(X):-write(' '),Y is X-1,w(Y).
s(S,N):-string_length(S,X),Y is div(X,2)*N,w(Y).
d(S,N,R):-atom_chars(S,A),e([],A,N,R).
e(B,[H|T],N,R):-l(B,H,N,I),e(I,T,N,R).
e(B,[],_,B).
a([], L, L).
a([H|T],L,[H|R]):-a(T,L,R).
l(L,_,0,L).
l(L,I,N,R):-M is N-1,l(L,I,M,T),a(T,[I],R).
o([]):-nl.
o([H|T]):-write(H),o(T).
p(S,N):-p(S,N,N).
p(_,0,_).
p(S,N,L):-Q is N-1,p(S,Q,L),d(S,N,R),W is L-N,s(S,W),o(R).

```

Test:

```
?- p("o-o  o-o",10).
                                    o-o  o-o
                                oo--oo    oo--oo
                            ooo---ooo      ooo---ooo
                        oooo----oooo        oooo----oooo
                    ooooo-----ooooo          ooooo-----ooooo
                oooooo------oooooo            oooooo------oooooo
            ooooooo-------ooooooo              ooooooo-------ooooooo
        oooooooo--------oooooooo                oooooooo--------oooooooo
    ooooooooo---------ooooooooo                  ooooooooo---------ooooooooo
oooooooooo----------oooooooooo                    oooooooooo----------oooooooooo
true .

```

Explanation:

**w** and **s** writes proper amount of leading spaces:

```
w(0).
w(X):-write(' '),Y is X-1,w(Y).
s(S,N):-string_length(S,X),Y is div(X,2)*N,w(Y).

```

**d** manages the "duplication" of characters and **e** is it's recursive facility:

```
//d(String, Number of repetitions, Result)
d(S,N,R):-atom_chars(S,A),e([],A,N,R).
e(B,[H|T],N,R):-l(B,H,N,I),e(I,T,N,R).
e(B,[],_,B).

```

**a** and **l** append to the result (maybe there exists a built in procedure?):

```
a([], L, L).
a([H|T],L,[H|R]):-a(T,L,R).
l(L,_,0,L).
l(L,I,N,R):-M is N-1,l(L,I,M,T),a(T,[I],R).

```

**o** creates the output:

```
o([]):-nl.
o([H|T]):-write(H),o(T).

```

and finally the **p** is the *main method*:

```
p(S,N):-p(S,N,N).
p(_,0,_).
//p(String, Current level, Number of levels) :- go to the bottom, create pyramide level, write whitespaces, write the level
p(S,N,L):-Q is N-1,p(S,Q,L),d(S,N,R),W is L-N,s(S,W),o(R).

```
> 3 votes

# Answer
# PHP, 113 bytes:

```
for([,$s,$n]=$argv;$i++<$n;)for(print($f=str_pad)("
",($n-$i)*strlen($s)/2+!$p=0);~$c=$s[$p++];)echo$f($c,$i,$c);

```

Run with `php -nr '<code>' '<string>' <N>` or test it online.

**breakdown**

```
# import input, loop $i from 1 to $n
for([,$s,$n]=$argv;$i++<$n;)
    # 1. print newline and padding, reset $p
    for(print($f=str_pad)("\n",($n-$i)*strlen($s)/2+!$p=0);
    # 2. loop $c through string
        ~$c=$s[$p++];)
        # print repeated character
        echo$f($c,$i,$c);

```
> 2 votes

# Answer
# , ~~125~~ 95 bytes

```
function(S,n)for(i in 1:n)cat(rep(' ',(n-i)/2*nchar(S)),rep(el(strsplit(S,'')),e=i),sep="",'
')

```

Try it online!

### Explanation:

It's pretty straightforward, splitting the string and repeating the elements `i` times each `rep(s,e=i)` (`e` is short for `each`) as we loop. The tricky part is `rep('',(n-i)/2*length(s)+1)`. This is the padding string, but it's a bunch of empty strings. I need to add 1 because otherwise the result is `character(0)`, a zero-length vector, and `cat`, which by default separates its elements with spaces, misaligns the final line.
> 2 votes

# Answer
# CJam, 36 bytes

```
l_,2/:T;]li:F{[_U)*zSTFU)-**\N]\}fU;

```

Try it online!
> 2 votes

# Answer
# T-SQL, 223 bytes

```
DECLARE @ char(99),@n INT,@i INT=1,@j INT,@p varchar(max)SELECT @=s,@n=n FROM t
R:SET @j=0SET @p=SPACE((@n-@i)*len(@)/2)C:SET @j+=1SET @P+=REPLICATE(SUBSTRING(@,@j,1),@i)IF @j<LEN(@)GOTO C
PRINT @p SET @i+=1IF @i<=@n GOTO R

```

Input is via pre-existing table **t** with columns **s** and **n**, per our IO standards.

Not much to explain, it's a pretty straightforward nested loop, using `@i` for the rows and `@j` to walk through the characters of the string which are `REPLICATED` `@i` times:

```
DECLARE @ char(99),@n INT,@i INT=1,@j INT,@p varchar(max)
SELECT @=s,@n=n FROM t
R:
    SET @j=0
    SET @p=SPACE((@n-@i)*len(@)/2)
    C:
        SET @j+=1
        SET @P+=REPLICATE(SUBSTRING(@,@j,1),@i)
    IF @j<LEN(@)GOTO C
    PRINT @p
    SET @i+=1
IF @i<=@n GOTO R

```
> 2 votes

# Answer
# Python 2, ~~79~~ 77 bytes

```
s,n=input();m=n
while m:m-=1;print' '*(m*len(s)/2)+''.join(i*(n-m)for i in s)

```

Try it online!

Edit: -2 bytes courtesy @FlipTack
> 2 votes

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

```
L€×.c

```

First input is \\$n\\$, second input is \\$s\\$ as character-list.

Try it online.

**Explanation:**

```
L      # Push a list in the range [1, first (implicit) input-integer]
 €     # Map over each integer:
  ×    #  Repeat each character in the (implicit) second input-list the integer
       #  amount of times as string
   .c  # Join each inner list to a string; then each string by newlines;
       # and then centralize each line by padding leading spaces
       # (after which it is output implicitly as result)

```
> 2 votes

# Answer
# Mathematica, 97 bytes

```
(c=Characters@#;T=Table;Column[T[""<>T[""<>T[c[[i]],j],{i,Length@c}],{j,#2}],Alignment->Center])&

```

**input**

> \["o-o o-o", 10\]
> 1 votes

# Answer
## LOGO, ~~97~~ 95 bytes

```
to f :s :n
for[i 1 :n][repeat(:n-:i)/2*count :s[type "\ ]foreach :s[repeat :i[type ?]]pr "]
end

```

Try the code on FMSLogo interpreter.

Define a function `f` which takes two inputs, `:s` and `:n`, then print the result.
> 1 votes

# Answer
# Tcl, ~~143~~ ~~142~~ ~~141~~ 138 bytes

```
proc p s\ n {set p [expr [set w [expr [string le $s]/2]]*$n];time {incr p $w;puts [format %$p\s [regsub -all . $s [append r \\0]]]} $n;cd}

```

Test:

```
% p "o-o  o-o" 5
                o-o  o-o
            oo--oo    oo--oo
        ooo---ooo      ooo---ooo
    oooo----oooo        oooo----oooo
ooooo-----ooooo          ooooo-----ooooo

```

Remark: the "cd" at the end of the procedure prevents time's result to be printed out below the pyramid, but changes the current directory - a side effect that's not explicitly forbidden.

Thanks to sergiol for a hint to save one byte.... and another hint to save one more byte.

Thanks to aspect (on tcl chat) for another 3 bytes saved!
> 1 votes

# Answer
# Swift, 232 bytes

Probably could be better, but I don't have much time to refactor.

This answer uses Swift 4, so it can't currently be run online.

```
var p:(String,Int)->String={s,i in let r=(1...i).map{n in return s.map{return String(repeating:$0,count:n)}.joined()};return(r.map{return String(repeating:" ",count:(r.last!.count-$0.count)/2)+$0}as[String]).joined(separator:"\n")}

```
> 1 votes

# Answer
# Java 8, 164 148 bytes

```
s->n->{String o="";for(int i=0,m,j;i++<n;){o+="\n";for(m=0;m++<(n-i)*s.length()/2;)o+=" ";for(char c:s.toCharArray())for(j=0;j++<i;)o+=c;}return o;}

```

Explanation:

```
s->n->{
    String o = "";                                  //empty output string
    for (int i = 0, m, j; i++ < n; ) {              //for each row
        o += "\n";                                  //append a new line
        for (m = 0; m++ < (n - i)*s.length()/2; )   //for amount of spaces = inversed row_number * half length
            o += " ";                               //append a space
        for (char c : s.toCharArray())              //for each char of the string
            for (j = 0; j++ < i; )                  //row_number times
                o+=c;                               //append char
    }
    return o;
}

```
> 1 votes

# Answer
## Rust, 107 bytes

```
|a:&str,b|for i in 0..b{println!("{:^1$}",a.split("").map(|s|s.repeat(i+1)).collect::<String>(),a.len()*b)}

```

playpen link

Defines an anonymous function that takes a string slice and number, printing the wanted pattern to standard output. It assumes that the string slice only contains ASCII characters, but the challenge never specifies that full unicode support is necessar. To be correct for unicode as well would require 117 bytes:

```
|a:&str,b|for i in 0..b{println!("{:^1$}",a.split("").map(|s|s.repeat(i+1)).collect::<String>(),a.chars().count()*b)}

```

The explanation is rather simple:

```
|a:&str,b|                             // arguments, compiler can't infer the type of a unfortunately
    for i in 0..b {                    // iterate from row 0 to row b - 1
        println!(
            "{:^1$}",                  // print a line containing arg 0, centered with the width specified as arg 1
            a.split("")                // split the string into slices of one character
                .map(|s|s.repeat(i+1)) // for each slice, yield a string containing row+1 times that slice
                .collect::<String>(),  // concatenate each of the strings into one string
            a.len()*b                  // total length should be the length of the string times the amount of rows
        )
    }

```
> 1 votes

# Answer
# SOGL V0.12, 8 bytes

```
∫dč*∑}¹╚

```

Try it Here!

Explanation:

```
∫dč*∑}¹╚
∫    }    iterate over 1..input, pushing counter
 d        push the variable D, which sets itself to the next input as string
  č       chop into characters - a vertical array
   *      multiply horizontally by the counter
    ∑     join the array together
      ¹   wrap all that in an array
       ╚  center horizontally

```

I didn't feel like updating my old answer here as it uses a different method and uses a new(er than the challenge) feature -
> 1 votes

# Answer
# C (gcc), 123 bytes

```
i,j,c;p(char*s,int n){for(i=0;i<n;){printf("\n%*s",strlen(s)/2*(n-++i),"");for(c=0;s[c];c++)for(j=0;j++<i;)putchar(s[c]);}}

```

Try it online!

## Pretty Code:

```
// declare variables gcc-style
i,j,c;
p(char *s, int n){
    // for every n
    for(i=0;i<n;){
        // print [ strlen(s)/2 * (n-(i+1)) ] spaces
        printf("\n%*s",strlen(s)/2*(n-++i),""); // increment i instead of (i+1)
        // for every character in the input string
        for(c=0;s[c];c++)
            // for every repetition required
            for(j=0;j++<i;)
                // print the current character
                putchar(s[c]);
    }
}

```
> 1 votes

# Answer
# Excel VBA, 98 Bytes

Anonymous VBE immediate window function that take input as string from `[A1]` and int from `[B1]` then outputs to the VBE immediate window

```
For i=1To[B1]:?Spc([Len(A1)/2]*([B1]-i));:For j=1To[Len(A1)]:?String(i,Mid([A1],j,1));:Next:?:Next

```
> 0 votes

# Answer
# Vyxal `C`, 2 bytes

```
ɾ•

```

Try it Online!

```
ɾ  # 1...n
 • # Repeat each char of input by each of those
   # (C flag) center and join by newlines

```
> 0 votes

# Answer
# Canvas, 6 bytes

```
⁷；１＊］ｒ

```

Try it here!
> 0 votes

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


# Question
Title: The right way to return [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Here is the program to return `[[0, 0, 0], [0, 1, 0], [0, 0, 0]]`

```
[[0]*3,[0,1,0],[0]*3]

```

Try it online!

Can you shorten this code?

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

```
[b:=[0]*3,[0,1,0],b]

```

Try it online! Note that modifying the first subarray also modifies the third subarray, so this would not be suitable in that case.
> 7 votes

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


title: How many times can I skip a stone?

text:
# Question
Title: How many times can I skip a stone?
Let's have a list of positive integers

```
[6,1,9,3,7,4,6,3,2,7,6,6]

```

this will represent a river. We would like to skip a stone across this river. We can throw the stone as far as we want and whatever number it lands on it will skip that many places. So if we start by throwing it 2 spaces, it will land on the `1` skip forward one place, land on the `9` skip forward 9 places, land on the final 6 and skip out of the river.

```
[6,1,9,3,7,4,6,3,2,7,6,6]
   ^
[6,1,9,3,7,4,6,3,2,7,6,6]
     ^
[6,1,9,3,7,4,6,3,2,7,6,6]
                       ^

```

The question for us is: "How do we throw the stone so it skips the largest number of times?" In the above case `2` skips 3 times and indeed we can see that this is the optimum.

Here's all the ways to throw the stone with the number of skips labeled:

```
[6,1,9,3,7,4,6,3,2,7,6,6]
 2 3 2 2 2 2 1 2 2 1 1 1

```

## Task

Given a list of positive integers as input output the maximum skips that can be achieved on that river.

This is so the goal is to make your source code as small as possible as measured in bytes.

## Test cases

```
[1] -> 1
[1,1,1] -> 3
[9,1,1,1] -> 3
[9,3,1,2,2,9,1,1,1] -> 5
[6,6] -> 1
[6,1,9,3,7,4,6,3,2,7,6,6] -> 3
[1,1,9,1,1] -> 3

```

# Answer
# 05AB1E, 11 bytes

```
.sε.Γ¬.$]ζg

```

Try it online! or Try all cases!

```
.sε       # map over the suffixes of the list
   .Γ     #   iterate until reaching a fixed point, collecting intermediate results:
     ¬.$  #     get the first value, and drop that many values from the front
ζ         # after the map: transpose, padding with spaces
 g        # get the length

```
> 11 votes

# Answer
# JavaScript (ES6), 49 bytes

```
a=>Math.max(...a.map(g=(v,i)=>v&&-~g(a[i+=v],i)))

```

Try it online!

We turn the input array into a list of number of skips for each starting point, using the recursive callback function `g`:

```
g = (          // g is a recursive function taking:
  v,           //   v = value at the current position
  i            //   i = current position
) =>           //
  v &&         // abort if v is undefined
  -~g(         // otherwise increment the result of a recursive call:
    a[i += v], //   add v to i and pass a[i] as the new value
    i          //   pass the new position
  )            // end of recursive call

```

We then return the maximum of this list.
> 10 votes

# Answer
# , 25 bytes

```
[:#[:+./ .*^:a:~#\=/~]+#\

```

Try it online!

We think of it as a graph problem.

Consider `1 1 9 1 1`

* `]+#\` Add `1 2 3 4 5` to the input:

```
2 3 12 5 6

```
* `#\=/` Create an equality table showing where that is equal to `1 2 3 4 5`:

```
    1 2 3 4 5
  +----------
 2| 0 1 0 0 0
 3| 0 0 1 0 0
12| 0 0 0 0 0
 5| 0 0 0 0 1
 6| 0 0 0 0 0

```

This is the adjacency of matrix of the directed graph showing connections between the indices.
* `[:+./ .*^:a:~` "OR" matrix multiply that graph with itself until we reach a fixed point, saving intermediate steps:

```
0 1 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0

0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

```
* `[:#` Return the length, which is also the length of the longest path:

```
3

```

## , Bonus port of ovs's answer, 25 bytes

```
[:>./<:@#@(({.}.])^:a:)\.

```

Try it online!
> 8 votes

# Answer
# Vyxal `G`, ~~20~~ 16 bytes

```
żƛ{D?L<|?i+1$}!⇩

```

Try it Online!

~~This feels too long~~ That's better.

## Explained

```
żƛ{D?L<|?i+1$}!⇩
ż                 # The range [1, len(input)] - this represents all possible starting throw lengths
 ƛ                # over each item N in that range:
  {D?L<|          #   while the top of the stack (the position of the rock on the lake) (initially N) is less than the length of the input: - this keeps the top of the stack on the stack
        ?i+       #     index into the input list at the current position of the rock and add the skip value to the position of the rock. This is what keeps track of how far the rock has travelled.
           1$     #     and push a 1 to the stack, placing it underneath the position of the rock - this keeps track of how many jumps have been made.
             }    #    end loop
              !⇩  #    push the length of the stack minus 2 - this is the number of jumps made accounting for the remaining rock positions.
                  # the -G flag returns the maximum number of jumps from the resulting list.

```
> 7 votes

# Answer
# Python 3, 61 57 54 53 bytes

-4 bytes thanks to @ovs

Further -3 bytes thanks to @xnor

And an additional -1 byte thanks to @ovs

```
f=lambda l,b=1:l>[]and max(1+f(l[l[0]:],-1),f(l[b:]))

```

Try it online!
> 6 votes

# Answer
# x86-16 machine code, 24 bytes

```
00000000: 33c0 33db 5399 4202 183b d97e f93b d07c  3└3█SÖB☻↑;┘~∙;╨|
00000010: 028b c25b 43e2 edc3                      ☻ï┬[CΓφ├

```

Listing:

```
33 C0       XOR  AX, AX                 ; AX = max skip count
33 DB       XOR  BX, BX                 ; BX = starting point offset
        THROW_LOOP:
53          PUSH BX                     ; save starting point
99          CWD                         ; clear skips counter for this throw (DX = 0)
        SKIP_LOOP:
42          INC  DX                     ; increment skip counter
02 18       ADD  BL, BYTE PTR[BX+SI]    ; add it's value to place offset
3B D9       CMP  BX, CX                 ; did it skip out of the river?
7E F9       JLE  SKIP_LOOP              ; if not, let it keep skipping
        END_SKIP:
3B D0       CMP  DX, AX                 ; is skip counter higher than best?
7C 02       JL   NOT_BEST               ; if not, try next starting offset
8B C2       MOV  AX, DX                 ; if so, save as current best score
        NOT_BEST:
5B          POP  BX                     ; restore starting point
43          INC  BX                     ; go to next starting point
E2 ED       LOOP THROW_LOOP             ; loop until end of array
C3          RET

```

Input array at `[SI]`, length in `CX`. Output most skips in `AX`.

Tests with DOS DEBUG (in Dark Mode):
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~71~~ ~~70~~ ~~68~~ ~~64~~ ~~62~~ ~~52~~ ~~50~~ 47 bytes

```
A|->Max[i=0;#0@@Check[!#+A[[#]],-1]+1&@++i&/@A]

```

–3 thanks to att!

Try it online!
> 4 votes

# Answer
# Jelly, 11 bytes

```
ṫ‘ḢƊƬÐƤẈṀ_2

```

A monadic Link accepting a list of integers that yields an integer.

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

### How?

Unfortunately, while  pops off and yields the head of a list it affects the original list given to `ÐƤ` (for suffixes of the list) as well as the suffix being dealt with at the time and so affects the remaining suffixes. Without the popping we need to increment for  (tail from) to do the correct thing so I've incremented all elements, tailed from each of those and then kept the head of those lists. Maybe there is a better way to do this challenge that will take less bytes...?

```
ṫ‘ḢƊƬÐƤẈṀ_2 - Link: list of integers, River
     ÐƤ     - for each suffix of River:
    Ƭ       -   collect input values while distinct, applying:
   Ɗ        -     last three links as a monad:
 ‘          -       increment all values
ṫ           -       tail (vectorises, so tail at from incremented value)
  Ḣ         -       head (the list that used the first incremented value)
       Ẉ    - length of each
        Ṁ   - maximum
         _2 - subtract two (the final [] and the 0 that heading [] (or 0) yields)

```

---

This one is 13 bytes, but maybe the idea can lead to a shorter solution?

```
JŒPịṖ⁼I{ʋƇ⁸ṪL

```
> 4 votes

# Answer
# Nibbles, 10 bytes (19 nibbles)

```
`/.,,$-,`.$+=~$_$~]

```

## Explanation

```
`/.,,$-,`.$+=~$_$~]
`/                ] Maximum of list:
  .                   Map over
   ,,$                each index i of the input:
        `.$             Iterate starting at j = i, collecting all values:
           +              Add
            =~$_          the j-th element of the input or 0 if out of bounds
                $         to j
       ,                Get length
      -          ~      Subtract 1

```
> 3 votes

# Answer
# Pyth, 21 bytes

```
eSmlP.u.x>NhN[)_d).__

```

Test suite

##### Explanation:

```
eSmlP.u.x>NhN[)_d).__  | Full code
eSmlP.u.x>NhN[)_d).__Q | with implicit variables filled
-----------------------+----------------------------------------------------------------------------------------------------------------
  m            _  .__Q | Map over the list of suffixes `d` of the input:
     .u         d)     |  Repeat the following on `N`, starting with `d`, until a repeated value is given, collecting results in a list:
         >NhN          |   `N` from index (the first value of `N`) on
       .x    [)        |   (or the empty list if an error is thrown)
   lP                  |  Length of the resulting list - 1
eS                     | Get the max value of the resulting list

```

The final 7 bytes can be omitted if input is taken as a list of suffixes (not allowed by challenge author).
> 3 votes

# Answer
# Husk, 11 bytes

```
←▲mȯLU¡S↓←ṫ

```

Try it online!

## Explanation

```
←▲mȯLU¡S↓←ṫ
          ṫ suffixes
  m         map each to
      ¡S↓←  infinite list: drop first element no. of elements
    LU      length of unique prefix
←▲          decrement maximum

```
> 3 votes

# Answer
# Jelly, 11 bytes

```
;0µ+J«LịƬ`L

```

Try it online!

Feels like there ought to be one more byte to shave off, perhaps dealing with the final step with something shorter than `;0µ`, but it at least ties.

```
;0µ            Append a 0 to the list.
   +J          Find the sum of each element and its 1-index
     «L        capped at the list's length.
       ịƬ`     Index this into itself (constant) until it doesn't change,
          L    and return the number of iterations that took.

```

`Ṗ’o¥\ċ1‘µÐƤṀ` and `’o¥\ÐƤI>-§Ṁ‘`, a byte longer and completely different, also work.
> 3 votes

# Answer
# C (gcc), ~~78~~ ~~77~~ 75 bytes

```
i;c;m;f(a,n)int*a;{for(m=0;n--;++a)for(c=i=0;i<=n;m=++c>m?c:m)i+=a[i];i=m;}

```

Try it online!

Inputs a pointer to an array of integers and its length (because pointers in C carry no length info).
Returns the maximum number of skips.
> 2 votes

# Answer
# Charcoal, 30 bytes

```
Ｆ⌈θ⊞θ⁰Ｆ⮌…Ｌθ§≔θι∧§θι⊕§θ⁺ι§θιＩ⌈θ

```

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

```
Ｆ⌈θ⊞θ⁰

```

Append sufficient zeros so that we never jump off the end of the array.

```
Ｆ⮌…Ｌθ

```

Iterate over the array in reverse order.

```
§≔θι∧§θι⊕§θ⁺ι§θι

```

Update each non-zero element with `1` more than the number of skips of its next skip.

```
Ｉ⌈θ

```

Output the maximum number of skips.
> 2 votes

# Answer
# Retina 0.8.2, 61 bytes

```
.+
,$&;
\d+
$*
+`,1(1)*;((?<-1>1*,)*(1*))
;1$3,$2
O^`1+
\G;?1

```

Try it online! Link includes test cases. Explanation:

```
.+
,$&;

```

Wrap the input list with an extra prefix `,` and a trailing marker `;`.

```
\d+
$*

```

Convert to unary.

```
+`

```

Repeat until the marker has reached the beginning of the array.

```
,1(1)*;((?<-1>1*,)*(1*))

```

Try to skip ahead to find how many additional skips to take. (If there aren't enough values then this just runs off the end of the array and finds no skips.)

```
;1$3,$2

```

Replace the current value with `1` more than the number of additional skips.

```
O^`1+

```

Sort the numbers of skips in descending order.

```
\G;?1

```

Convert the maximum to decimal.
> 2 votes

# Answer
# Brain-Flak `-r`, 106 bytes

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

```

Try it online!

Starting from the end (which is the top of the stack since I used the `-r` flag), computes the number of skips from each position as 1 more than the previously calculated number of skips from its destination. The implicit zeros on the right stack account for the initial running maximum and number of skips from positions beyond the river.

In each iteration, the left stack has the positions not handled yet, and the right stack has the running maximum on top, followed by the number of skips from already handled positions.

Full code breakdown later.
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~41~~ 39 bytes

-1 (-2) thanks to Roman

```
Depth[g=h@#;i=0;(g@i=g[++i+#]!)&/@#]-3&

```

Try it online!

```
      g=h@#;                            associate g with this input
            i=0;       ++i     &/@#     for indices i of input l:
                (g@i=g[  i+#]!)           g[i]->Factorial[g[i+l〚i〛]]
Depth[                             ]    depth
                                    -3  offset (-1 List, -2 g[_])

```
> 2 votes

# Answer
# T-SQL, 96 bytes

```
WITH c(a,b,x)as(SELECT*,1FROM t
UNION ALL
SELECT t.*,x+1FROM c,t
WHERE a+b=i)SELECT max(x)FROM c

```

**Try it online**
> 2 votes

# Answer
# BQN, 19 bytes

```
⌈´·{⟨⟩:0;1+⊑⊸↓}¨↓

```

Anonymous function that takes a list of integers and returns an integer. Run it online!

### Explanation

```
⌈´·{⟨⟩:0;1+⊑⊸↓}¨↓
                  ↓  Get the suffixes of the input list
   {            }¨   Apply this function to each of them:
    ⟨⟩:0                If the argument is an empty list, return 0
       ;               Else:
                        Take the argument
             ⊸↓          Drop a number of elements from it
            ⊑            equal to its first element
                         (If there aren't that many elements, the result is empty)
                        Call this function recursively with that shorter list
         1+              Add 1 to the result of the recursive call
⌈´·                  Get the maximum of the resulting list of integers

```

For example, with input `⟨1,1,9,1,1⟩`, the suffixes are `⟨⟨1,1,9,1,1⟩, ⟨1,9,1,1⟩, ⟨9,1,1⟩, ⟨1,1⟩, ⟨1⟩, ⟨⟩⟩`. When the inner function is called with the suffix `⟨1,9,1,1⟩`:

* `⟨1,9,1,1⟩` is not empty, so drop the first 1 element and recurse
    + `⟨9,1,1⟩` is not empty, so drop the first 9 elements and recurse
        - `⟨⟩` is empty, so return 0
    + Add 1 to 0 and return 1
* Add 1 to 1 and return 2

This is the number of skips that are possible starting from the second 1 in the original list.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 71 bytes

```
Max[l@Most@NestWhileList[#+w[[#]]&,#,#<=l@w&]&/@Range@(l=Length)[w=#]]&

```

Try it online!
> 1 votes

# Answer
# Pip, ~~30~~ 24 bytes

```
FnRglAE:Uv<n|1+(lv-n)MXl

```

Takes the input numbers as separate command-line arguments. Attempt This Online!

Implements the spec somewhat directly. Still searching for a golfier approach.
> 1 votes

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


title: Count the ways to transform

text:
# Question
Title: Count the ways to transform
A rigid transformation of a square array is a mapping from square arrays of a certain size to square arrays of the same size, which rearranges the elements of the array such that the distance to each other element remains the same.

If you printed out the matrix on a sheet of paper these are the transforms you could do to it without tearing or folding the paper. Just rotating or flipping it.

For example on the array:

\\$ \begin{bmatrix} 1 & 2 \\ 4 & 3 \end{bmatrix} \\$

There are 8 ways to rigidly transform it:

\\$ \begin{bmatrix} 1 & 2 \\ 4 & 3 \end{bmatrix} \begin{bmatrix} 2 & 3 \\ 1 & 4 \end{bmatrix} \begin{bmatrix} 3 & 4 \\ 2 & 1 \end{bmatrix} \begin{bmatrix} 4 & 1 \\ 3 & 2 \end{bmatrix} \begin{bmatrix} 3 & 2 \\ 4 & 1 \end{bmatrix} \begin{bmatrix} 4 & 3 \\ 1 & 2 \end{bmatrix} \begin{bmatrix} 1 & 4 \\ 2 & 3 \end{bmatrix} \begin{bmatrix} 2 & 1 \\ 3 & 4 \end{bmatrix} \\$

The first \\$4\\$ are just rotations of the matrix and the second \\$4\\$ are rotations of it's mirror image.

The following is *not* a rigid transform:

\\$ \begin{bmatrix} 2 & 1 \\ 4 & 3 \end{bmatrix} \\$

Since the relative position of \\$2\\$ and \\$3\\$ has changed. \\$2\\$ used to be opposite \\$4\\$ and next to \\$1\\$ and \\$3\\$, but now it is opposite \\$3\\$ and next to \\$1\\$ and \\$4\\$.

For some starting arrays "different" transforms will give the same array. For example if the starting array is all zeros, any transform of it will always be identical to the starting array. Similarly if we have

\\$ \begin{bmatrix} 1 & 0 \\ 1 & 0 \end{bmatrix} \\$

The transforms which mirror it and rotate it a half turn, although they gave different results on the first example, give the same result in this example.

There are never more than \\$8\\$ unique transforms, the \\$4\\$ rotations and \\$4\\$ mirror rotations. Even when we scale the matrix up. So the number of unique results is always less than or equal to 8. In fact a little bit of math can show that it is always 1, 2, 4, or 8.

## Task

Take a non-empty square array of non-negative integers as input and return the number of unique ways to continuously transform it.

This is so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

```
5
=> 1
0 0
0 0
=> 1
0 1
1 0
=> 2
0 1
0 0
=> 4
0 1
0 1
=> 4
2 1
1 3
=> 4
3 4
9 1
=> 8
1 2
1 0
=> 8
0 1 0
1 1 1
0 1 0
=> 1
0 2 0
0 0 0
0 0 0
=> 4
0 2 0
2 0 0
0 0 0
=> 4
0 2 0
6 0 0
0 0 0
=> 8

```

# Answer
> 4 votes
# Jelly, 8 bytes

```
UZƭ7Ð¡QL

```

Try it online!

`UZƭ` alternatively performs `U` (reverse each row) and `Z` (transpose).

Doing this 7 times and collecting all intermediate results with `7Ð¡` gets all 8 transforms: {identity, `U`, `UZ`, `UZU`, … `UZUZUZU`}, and `QL` (unique+length) counts distinct ones.

# Answer
> 3 votes
# BQN, 16 bytesSBCS

```
≠∘⍷·⌽¨⊸∾⍉∘⌽⍟(↕4)

```

Run online!

`⍉∘⌽⍟(↕4)` Get the 4 rotations.
`⌽¨⊸∾` Add the mirror image of each rotation.
`≠∘⍷` Count the unique matrices.

# Answer
> 3 votes
# , ~~97~~ ~~94~~ 83 bytes

Or **\>=4.1, 69 bytes** by replacing two `function` occurrences with `\`s.

```
function(m)length(unique(Map(function(i)m<<-t("if"(i%%2,m,t(m[ncol(m):1,]))),1:8)))

```

Try it online!

I'm happy with my discovery that `unique` works well on a list of matrices.

**Explanation:**

1. Repeat 8 times a function returning alternating between:
    1. transposition of previous matrix,
    2. previous matrix with reversed rows.
    * Double transposition is needed for the size-1 edge case.
2. How many unique matrices?

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
4FDøDí})Ùg

```

Try it online or verify all test cases.

**Explanation:**

```
4F      # Loop 4 times:
  D     #  Duplicate the current matrix
        #  (which will be the implicit input-matrix the first iteration)
   ø    #  Zip/transpose; swapping rows/columns
    D   #  Duplicate again
     í  #  Reverse each row
 })     # After the loop: wrap all nine matrices into a list
   Ù    # Uniquify this list of matrices
    g   # Pop and push the length
        # (after which it is output implicitly as result)

```

# Answer
> 2 votes
# Charcoal, 27 bytes

```
Ｆ⁴«⊞υθ⊞υ⮌θ≔ＥθＥ⮌θ§μλθ»Ｉ÷⁸№υθ

```

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

```
Ｆ⁴«

```

Repeat for each possible rotation.

```
⊞υθ⊞υ⮌θ

```

Push the array and its vertical reflection to the predefined empty list.

```
≔ＥθＥ⮌θ§μλθ

```

Rotate the array.

```
»Ｉ÷⁸№υθ

```

Count the number of times the array appears in the list. Each unique array in the list must appear that number of times. Divide that into `8` to give the number of unique arrays, and output the result.

# Answer
> 2 votes
# JavaScript (ES6),  ~~85~~  81 bytes

*Saved 4 bytes thanks to @l4m2*

```
f=m=>new Set([...f+1].map(c=>(m=m.map((_,y)=>m.map(r=>+c?r[y]:r.pop())))+0)).size

```

Try it online!

# Answer
> 2 votes
# Python, 58 bytes

```
lambda l:len({l:=(l[::-1],(*zip(*l),))[p]for p in(0,1)*4})
```

Attempt This Online!

Essentially a port of my answer to a related (hexagonal) challenge, It generates all 8 symmetries from 2 reflections (up-down and transpose).

# Answer
> 1 votes
# Pari/GP, 48 bytes

```
a->#Set([a=if(i%2,Mat(Vecrev(a)),a~)|i<-[1..8]])

```

Try it online!

A port of @loopy walt's Python answer.

---
Tags: code-golf, array, matrix, abstract-algebra
---