# Question
Title: Use a Finite Combo in Magic the Gathering to Produce Graham's Number
Produce Graham's Number in Magic the Gathering using the fewest number of cards and without using any infinite combos.

**Rules:**

1. Producing Graham's number means do anything that requires Graham's number to represent the game state. For example, you could produce Graham's number 2/2 zombie tokens, have Graham's number life, or have a creature with Graham's number in power and/or toughness.
2. You must get to Graham's number exactly. If you overshoot it, you need to have  mechanism to get back down.
3. You cannot use a combo that can be repeated indefinitely (commonly referred to as a "infinite combo"), as defined in CR 726. For example, you can't use Basalt Monolith enchanted by Power Artifact, or Squirrel Nest in combination with Earthcraft as either of these can be repeated an arbitrary number of times. You can use abilities repeatedly, such as the ability on Staff of Domination or Voltaic Construct, as long as there is some in-game limit on the number of times it can be repeated (other than the the rules requirement that you not repeat an optional loop forever). The key text from CR 726 (describing interactions that this challenge disallows) is the following:

> 726.1b Occasionally the game gets into a state in which a set of actions could be repeated indefinitely (thus creating a “loop”). In that case, the shortcut rules can be used to determine how many times those actions are repeated without having to actually perform them, and how the loop is broken.
4. If the combination involves any cards that let players "choose a number", such as Menacing Ogre, numbers greater than 256 cannot be chosen.
5. You must get to Graham's number in at most 256 turns. (Note that taking infinite extra turns is prohibited as that would be an infinite combo.)
6. You have 256 mana of any color available to you on each turn without it counting against your card limit. Mana beyond that requires you to add cards to do this.
7. You have a single opponent with 20 life. The opponent takes no actions, and does not lose from drawing from an empty deck (assume that they have a deck made of 300 basic lands). You cannot rely on the opponent making specific choices unless you have an effect that lets you control their choices.
8. You must start with a legacy legal deck. In particular, all cards used must be legal in the Legacy format. Additionally, standard deck building rules are in effect; i.e. no more than four copies of any card can be used unless that card specifies otherwise.
9. All of your cards start in either your hand or library (your choice which for any given card). To get a card into another zone requires an ability that moves it there.
10. The solution that uses the fewest number of cards from it's deck and sideboard to complete this task wins. Using a card means that having that card in your deck or sideboard is necessary to completing the combo. Playing the card is the most common "use" of a card, but using a card also includes using it's activated or triggered abilities from a zone outside of the battlefield (such as Decree of Savagery or Bridge from Below) If you use multiple copies of a card, each copy counts as a separate card. Cards that are in the deck merely to meet the 60 card minimum but otherwise are never used are not counted.

**Note:** Magic the Gathering is known to be Turing Complete, so I assert that this is both possible and as much a coding challenge as those set in Conway's Game of Life.

Inspired by: https://boardgames.stackexchange.com/q/57658/9999

For those who haven't played Magic the Gathering extensively, you don't need to know the entire rule set (which is quite long), as most of that deals with interactions between players, which isn't present for this challenge. The basic rules, supplemented by the comprehensive rules on spells and abilities (section 6) is probably most of what you need to know. The harder part is finding cards that are helpful (as Magic has over 20,000 cards that have been printed). This is the best card search I know about: https://scryfall.com/advanced. Here are some examples of helpful searches:

# Answer
> 10 votes
# 6 cards, not yet legal

(The card Saw in Half will become Legacy legal with the upcoming release of Unfinity.)

*This solution is based on a solution by plopfill to a slightly different challenge (fixed in a later post), which exceeds Graham's number in 9 cards in 1 turn without free mana: Black Lotus, Show and Tell, Omniscience, Doubling Season, Temur Ascendancy, Astral Dragon, Mystic Sanctuary, Saw in Half, Dromoka, the Eternal.*

**Doubling Season, Temur Ascendancy, Astral Dragon, Mystic Sanctuary, Saw in Half, Dungeoneer's Pack**

Start by playing Mystic Sanctuary and casting Doubling Season and Temur Ascendancy.

Next, cast Astral Dragon. When it enters the battlefield, it triggers Temur Ascendancy's ability and its own ability. Have Astral Dragon's ability resolve first and produce four copies of Doubling Season (because of Doubling Season).

In response to the "draw a card" ability still on the stack, cast Saw in Half, targeting Astral Dragon. The two tokens this produces are doubled five times to make 64 token copies of Astral Dragon.

The first 62 to resolve of the new Astral Dragons' triggered abilities should target Doubling Season. Each one increases the number of Doubling Seasons from \\$n\\$ to more than \\$2^n\\$, and the initial number is \\$5 \> 4 = 2\uparrow\uparrow2\\$, so the number of Doubling Seasons after those 62 abilities resolve is more than \\$2\uparrow\uparrow64\\$ (Knuth's up-arrow notation).

The last two Astral Dragon abilities should target Mystic Sanctuary. The first of those produces more than \\$2\uparrow\uparrow65\\$ tapped copies of Mystic Sanctuary, and the second produces the same number of copies, but now untapped. Use one of their abilities to put Saw in Half on top of the library, and then the Temur Ascendancy ability draws it.

Cast Dungeoneer's Pack, and then cast Saw in Half on an Astral Dragon again. Target Doubling Season with all but two of the copies' abilities, increasing the number of Doubling Seasons to more than \\$2\uparrow\uparrow(2\uparrow\uparrow65)\\$. Use the last two abilities to target Mystic Sanctuary and Dungeoneer's Pack for more than \\$2\uparrow\uparrow(2\uparrow\uparrow65)\\$ copies of each, and again put Saw in Half on top of the library.

Proceed to the second turn, untapping the Dungeoneer's Packs and redrawing Saw in Half in the draw step.

Cast Saw in Half on an Astral Dragon again (although this time, it doesn't make a big difference to the final result). Similarly to before, increase the number of Doubling Seasons to \\$2\uparrow\uparrow(2\uparrow\uparrow(2\uparrow\uparrow65))\\$ and put Saw in Half back onto the library with a copy of Mystic Sanctuary.

Now start activating the copies of Dungeoneer's Pack. Each one draws a card, allowing another casting of Saw in Half, but the more important parts are the Treasure tokens and the initiative, which gives ventures into Undercity.

With every five ventures, take the path Secret Entrance → Forge → Arena → Archives → Throne of the Dead Three. The important one is Forge: Put two +1/+1 counters on target creature. Keep Saw in Half in hand and target an Astral Dragon with that, giving it more than \\$2^{2\uparrow\uparrow(2\uparrow\uparrow(2\uparrow\uparrow(2\uparrow\uparrow65)))}\\$ +1/+1 counters the first time.

With its power thereby increased, the copies produced by casting Saw in Half on it will also have high power, and therefore trigger Temur Ascendancy to draw cards, allowing for more castings of Saw in Half.

* One Astral Dragon with power ≥7 gives rise to many with power ≥4, which give card draws and recastings of Saw in Half, each of which gives a tetration; thus the whole thing gives a pentation.
* One Astral Dragon with power ≥13 gives rise to many with power ≥7, for many pentations, thus a hexation.
* One Astral Dragon with power ≥25 gives rise to many with power ≥13, for many hexations, thus a heptation.
* In general, an Astral Dragon with power \\$\ge 2^{n}\times6+1\\$ gives the \\$n+5\\$th hyperoperation.

(Also, whenever the black mana is running out, target a Treasure token with an Astral Dragon's ability to make more Treasure tokens, which are usable because Temur Ascendancy gives them haste.)

Forge is reached again with every five ventures, feeding the Doubling Season count into the hyperoperation index each time. The number produced at the end is more than \\$2\rightarrow 3\rightarrow (2\uparrow\uparrow(2\uparrow\uparrow65)) \rightarrow2\\$ (Conway chained arrow notation), which exceeds Graham's number.

Finally, there are several options for making exactly Graham's number \\$G\\$ (it's not entirely clear to me what counts):

* Tap \\$G\\$ copies of Mystic Sanctuary for \\$G\\$ blue mana.
* Target a Treasure token with the last Astral Dragon ability to have more than \\$G\\$ Treasure tokens, then sacrifice all but \\$G\\$ of them.
* Attack with \\$G/3\\$ 3/3 copies of Doubling Season to deal \\$G\\$ damage to the opponent.
* Attack with \\$G/3\\$ 3/3 copies of Doubling Season and twenty 1/1 copies of Astral Dragon to deal \\$G+20\\$ damage to the opponent and make the opponent's life total \\$-G\\$.

---
Tags: game, atomic-code-golf
---


title: Fibonacci Exponents

text:
# Question
Title: Fibonacci Exponents
For this challenge, you are to output the result of the sum of some numbers. What are these numbers? Well, you are given input, (`a`, `b`), which are integers (positive, negative, or zero) , `a != b`, and `a < b` , and each integer within `a` and `b` (including them) will have exponents according to the Fibonacci numbers. That's confusing so here's an example:

```
Input: (-2, 2)
Output: -2**1 + (-1**1) + 0**2 + 1**3 + 2**5 =
          -2  +    -1   +   0  +   1  +   32 = 30

```

Given that the first Fibonacci number is represented by `f(0)`, the formula is:

```
a**f(0) + ... + b**f(b-a+1)

```

**Input, Processing, Output**

To clarify the above, here are some test cases, the processing of the input, and the expected outputs:

```
Input: (1, 2)
Processing: 1**1 + 2**1
Output: 3

Input: (4, 8)
Processing: 4**1 + 5**1 + 6**2 + 7**3 + 8**5
Output: 33156

Input: (-1, 2)
Processing: -1**1 + 0**1 + 1**2 + 2**3
Output: 8

Input: (-4, -1)
Processing: -4**1 + -3**1 + -2**2 + -1**3
Output: -4

```

**Rules**

* No standard loopholes allowed
* Exponents must be in order according to Fibonacci series
* Code must work for above test cases
* Only the output needs to be returned

**Winning Criteria**

Shortest code wins!

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
ŸDg!ÅFsmO

```

Try it online!

```
Ÿ         # Push [a, ..., b].
 Dg!      # Calculate ([a..b].length())! because factorial grows faster than fibbonacci...
    ÅF    # Get Fibonacci numbers up to FACTORIAL([a..b].length()).
      s   # Swap the arguments because the fibb numbers will be longer.
       m  # Vectorized exponentiation, dropping extra numbers of Fibonacci sequence.
        O # Sum.

```

Doesn't work on TIO for large discrepancies between `a` and `b` (E.G. `[a..b].length() > 25`).

But it does seem to work for bigger numbers than the average answer here.

Inefficient, because it calculates the fibonacci sequence up to `n!`, which is more than is needed to compute the answer, where `n` is the length of the sequence of `a..b`.

# Answer
> 5 votes
# Python, 49 bytes

A recursive lambda which takes `a` and `b` as separate arguments (you can also set the first two numbers of fibonacci, `x` and `y`, to whatever you want - not intentional, but a nice feature):

```
f=lambda a,b,x=1,y=1:a<=b and a**x+f(a+1,b,y,x+y)

```

**Try it online!** (includes test suite)

Golfing suggestions welcome.

# Answer
> 5 votes
## Mathematica, 38 bytes 37 bytes 31 bytes

```
Sum[x^Fibonacci[x-#+1],{x,##}]&

```

This is just rahnema1's answer ported to Mathematica. Below is my original solution:

```
Tr[Range@##^Fibonacci@Range[#2-#+1]]&

```

Explanation:

`##` represents the sequence of all the arguments, `#` represents the first argument, `#2` represents the second argument. When called with two arguments `a` and `b`, `Range[##]` will give the list `{a, a+1, ..., b}` and `Range[#2-#+1]` will give the list of the same length `{1, 2, ..., b-a+1}`. Since `Fibonacci` is `Listable`, `Fibonacci@Range[#2-#+1]` will give list of the first `b-a+1` Fibonacci numbers. Since `Power` is `Listable`, calling it on two lists of equal length will thread it over the lists. Then `Tr` takes the sum.

Edit: Saved 1 byte thanks to Martin Ender.

# Answer
> 4 votes
# Perl 6, ~~32~~ 30 bytes

```
{sum $^a..$^b Z**(1,&[+]...*)}

```

`$^a` and `$^b` are the two arguments to the function; `$^a..$^b` is the range of numbers from `$^a` to `$^b`, which is zipped with exponentiation by `Z**` with the Fibonacci sequence, `1, &[+] ... *`.

Thanks to Brad Gilbert for shaving off two bytes.

# Answer
> 3 votes
# Maxima , 32 bytes

```
f(a,b):=sum(x^fib(x-a+1),x,a,b);

```

# Answer
> 3 votes
## Pyke, 11 bytes

```
h1:Foh.b^)s

```

Try it here!

```
h1:         -   range(low, high+1)
   F     )  -  for i in ^:
    oh      -     (o++)+1
      .b    -    nth_fib(^)
        ^   -   i ** ^
          s - sum(^)

```

# Answer
> 3 votes
## Haskell, 35 bytes

```
f=scanl(+)1(0:f);(?)=sum.zipWith(^)

```

Usage:

```
$ ghc fibexps.hs -e '[4..8]?f'
33156

```

# Answer
> 3 votes
## JavaScript (ES7), 42 bytes

```
f=(a,b,x=1,y=1)=>a<=b&&a**x+f(a+1,b,y,x+y)

```

Straightforward port of @FlipTack's excellent Python answer.

# Answer
> 2 votes
# MATL, 23 bytes

```
&:ll&Gw-XJq:"yy+]JQ$h^s

```

Try it online! Or verify all test cases.

```
&:      % Binary range between the two implicit inputs: [a a+1 ... b]
ll      % Push 1, 1. These are the first two Fibonacci numbers
&G      % Push a, b again
w-      % Swap, subtract: gives b-a
XJ      % Copy to cilipboard J
q:      % Array [1 2 ... b-a-1]
"       % For each (repeat b-a-1 times)
  yy    %    Duplicate the top two numbers in the stack
  +     %    Add
]       % End
J       % Push b-a
Q       % Add 1: gives b-a+1
$       % Specify that the next function takes b-a+1 inputs
h       % Concatenate that many elements (Fibonacci numbers) into a row vector
^       % Power, element-wise: each entry in [a a+1 ... b] is raised to the
        % corresponding Fibonacci number
s       % Sum of array. Implicitly display

```

# Answer
> 2 votes
# Husk, 6 bytes

```
Σz^İf…

```

Try it online!

## Explanation

```
Σz^İf…
     … rangify the input
 z^    zip using the power function
   İf  using the fibonacci numbers
Σ      sum the result

```

# Answer
> 2 votes
# Vyxal `s`, 6 bytes

```
ṡ:ẏ∆fe

```

Try it online, or see a seven byte flagless solution. Takes input with b first, then a.

Explanation:

```
ṡ       # Range from a to b
 :      # Duplicate
  ẏ     # Range from 0 to length
   ∆f   # Nth Fibonacci number
     e  # To the power of
        # Sum with the s flag

```

# Answer
> 1 votes
# R, 51 bytes

An anonymous function.

```
function(a,b)sum((a:b)^numbers::fibonacci(b-a+1,T))

```

# Answer
> 1 votes
# Jelly, 13 bytes

```
ạµ1+⁸Ð¡0
r*çS

```

Try it online!

# Answer
> 1 votes
# Whispers v3, 87 bytes

```
> Input
> Input
> fₙ
>> 1…2
>> #4
>> 3ᶠ5
>> L*R
>> Each 7 4 6
>> ∑8
>> Output 9

```

Unfortunately, Whispers v3 isn't on TryItOnline!, so there isn't an online interpreter to test this, aside from downloading the repository and running it locally.

# Answer
> 1 votes
# Jelly, ~~9~~ 8 bytes

```
rJÆḞ*@rS

```

Try it online!

-1 byte thanks to ZippyMagician

## How it works

```
rJÆḞ*@rS - Main link. Takes a on the left and b on the right
r        - Range from a to b
 J       - Length range of that
  ÆḞ     - n'th Fibonacci number of each
      r  - Range from a to b
    *@   - Raise each to the power of the Fib numbers
       S - Sum

```

# Answer
> 1 votes
# Arn `-x`, ~~11~~ 8 bytes

```
gŸ▀<Çúì═

```

Try it!

# Explained

Unpacked: `.=z^[1 1{+`

```
   .=       Rangify input (inclusive)
z^          Zipped with exponentiation to
   [1 1{+   The fibonacci sequence, closing }] implied
          Then take the sum

```

# Answer
> 0 votes
## Ruby, 46 bytes

```
->a,b{n=s=0;m=1;a.upto(b){|x|s+=x**n=m+m=n};s}

```

Nothing particularly clever or original to see here. Sorry.

# Answer
> 0 votes
# Java 7, 96 bytes

Golfed:

```
int n(int a, int b){int x=1,y=1,z=0,s=0;while(a<=b){s+=Math.pow(a++,x);z=x+y;x=y;y=z;}return s;}

```

Ungolfed:

```
int n(int a, int b)
{
    int x = 1, y = 1, z = 0, s = 0;
    while (a <= b)
    {
        s += Math.pow(a++, x);
        z = x + y;
        x = y;
        y = z;
    }

    return s;
}

```

# Answer
> 0 votes
# R, 57 bytes

```
x=scan();sum((x[1]:x[2])^numbers::fibonacci(diff(x)+1,T))

```

Pretty straightforward. `gmp::fibnum` is a shorter built-in, but it doesn't support returning the entire sequence up to `n`, which `numbers::fibonacci` does by adding the argument `T`.

First I had a more tricky solution with `gmp::fibnum` which ended up 2 bytes longer than this solution.

```
x=scan();for(i in x[1]:x[2])F=F+i^gmp::fibnum((T<-T+1)-1);F

```

# Answer
> 0 votes
# dc, 56 bytes

```
?sf?sa0dsbsg1sc[lblcdlfrdsb^lg+sg+sclf1+dsfla!<d]dsdxlgp

```

Finishes for input `[1,30]` in 51 seconds. Takes the two inputs on two separate lines once executed and negative numbers with a leading *underscore* (`_`) instead of a dash (i.e `-4` would be input as `_4`).

# Answer
> 0 votes
# PHP, ~~77~~ 75 bytes

```
for($b=$argv[$$x=1];$b<=$argv[2];${$x=!$x}=${""}+${1})$s+=$b++**$$x;echo$s;

```

takes boundaries from command line arguments. Run with `-nr`.
showcasing PHP´s variable variables again (and what I´ve found out about them.

**breakdown**

```
for($b=$argv[$$x=0}=1]; # $"" to 1st Fibonacci and base to 1st argument
    $b<=$argv[2];           # loop $b up to argument2 inclusive
    ${$x=!$x}                   # 5. toggle $x,             6. store to $1/$""
        =${""}+${1}             # 4. compute next Fibonacci number
)
    $s+=$b++**                  # 2. add exponential to sum,    3. post-increment base
        $$x;                    # 1. take current Fibonacci from $""/$1 as exponent
echo$s;                     # print result

```

FlipTack´s answer ported to PHP has 70 bytes:

```
function f($a,$b,$x=1,$y=1){return$a>$b?0:$a**$x+f($a+1,$b,$y,$x+$y);}

```

# Answer
> 0 votes
# Axiom, 65 bytes

```
f(a,b)==reduce(+,[i^fibonacci(j)for i in a..b for j in 1..b-a+1])

```

test code and results

```
(74) -> f(1,2)
   (74)  3
                                                   Type: Fraction Integer
(75) -> f(4,8)
   (75)  33156
                                                   Type: Fraction Integer
(76) -> f(-1,2)
   (76)  8
                                                   Type: Fraction Integer
(77) -> f(-4,-1)
   (77)  - 4
                                                   Type: Fraction Integer
(78) -> f(3,1)
   >> Error detected within library code:
   reducing over an empty list needs the 3 argument form
    protected-symbol-warn called with (NIL)

```

# Answer
> 0 votes
# PowerShell, 67 bytes

```
$e=1;$args[0]..$args[1]|%{$s+=("$_*"*$e+1|iex);$e,$f=($e+$f),$e};$s

```

Try it online!

Found a slightly better way to do the sequence, but powershell doesn't compare to other languages for this one :)

# Answer
> 0 votes
# Japt `-x`, 9 bytes

```
òV ËpMgEÄ

```

Try it

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
ŸvyN>Åfm}O

```

Try it online! Takes two lines of input, the first line being `b` and the second line being `a`.

```
 v          # for y in...
Ÿ           # [a, ..., b] (implicit input)
       m    # push...
  y         # current item in list
       m    # to the power of...
     Åf     # the...
   N>       # current index in list...
     Åf     # th Fibonacci number
        }   # end loop
         O  # push sum(stack)
            # implicit output

```

---
Tags: code-golf, math, fibonacci
---


# Question
Title: Smallest subset of characters required for Turing Completeness
In Fewest (distinct) characters for Turing Completeness, the goal is to find the minimum number of characters which make a language Turing Complete...in other words, allow it to do any computation possible with any other language. In this challenge, we'll be doing somewhat of the opposite, and finding the minimum number of characters, without which Turing Completeness is impossible.

**Example:**

In JavaScript, it is well known that the characters `+!()[]` are all that's needed to write any JS program. We could try using just one of these characters, `+`, as a solution. However, I can get around this with something like: `eval("1\x2b2")`. So, I might add `"`, `'`, and `\` to the list. This would keep going until I find a small list of characters with which it is difficult or impossible to write any program with.

**Rules:**

* **You must be able to write a valid program without using any characters in your chosen set.** It doesn't need to do anything useful, it just can't error (this is to prevent a character set which includes a single character needed in any valid program)
* Actual "Turing Completeness" isn't necessarily required, since languages like C impose things like maximum sizes for pointers which would rule out many languages. I won't set any specific requirements for "how" Turing Complete the threshold is, but be reasonable, and answers which use a clearly Turing Incomplete language or similar tricks should be downvoted
* Like , competition is purely within a language, not between different ones

**How this post works:**

This is a sort-of-CnR. Since determining whether a subset of characters is required for TC-ness or not is itself a fun challenge, Robbers will have the task of trying to "crack" submissions by finding a way to achieve TC-ness without the chosen subset of characters (or proving such a task is impossible). Thus, Cops can fall into two categories:

1. Cop-cops: Submissions which are specifically designed to have a trick that still allows TC-ness, as a challenge to Robbers
2. Sort-of-cops: Submissions which do not have an intended crack, where the possible-TC-ness is either unknown or can be proven (it's recommended to say how certain you are that it's not crackable, to prevent Robbers from wasting their time on a likely impossible sort-of-cop)

Here is an example of each:

> # Cop-cop: JavaScript, 4 characters
>
> ```
> +"'\
> ```
>
> This is a known-crackable cop. The solution isn't super hard to find, but I hope you have fun with it!

And a non-cop-cop:

> # Sort-of-cop: JavaScript, 6 characters
>
> ```
> +S("'\
> ```
>
> I'm 99% certain this is valid.

And a proven-non-cop-cop:

> # Sort-of-cop: JavaScript, 1114112 characters
>
> ```
> [all of unicode]
> ```
>
> Proof: Kinda obvious

**Scoring:**

The winner of the cops' challenge, per language, is the smallest subset of characters required for Turing Completeness, which is not cracked within two weeks (at which point it becomes "safe").

**Robbers post:** Robbers: Smallest subset of characters required for Turing Completeness

**Chat room:** https://chat.stackexchange.com/rooms/136437/smallest-subset-of-characters-required-for-turing-completeness

# Answer
# Sort-of cop, Common Lisp, one character

```
(

```

I am almost certain that no Turing Complete CL program can be written without an open paren: the language can easily be extended/modified such that, in the extended language, one can, but I don't think you can bootstrap such an extension without `(`.

Programs can still be written, such as `1` or `nil`.

This is characters, not octets in a file.
> 8 votes

# Answer
# Cop-cop: , 3 bytes, cracked by Cong Chen

```
(=<

```

Try it online!

I imagine this won't take long for one of the  afficionados to crack...
But, as a bonus, it looks like a grumpy face. (=\<
> 7 votes

# Answer
# Sort-of-cop: Desmos, 1 character

```
=

```

Took out variable/function declaration, which is essential in doing anything useful in Desmos. Would love to be proved wrong though. I have a more restrictive version if this happens to be cracked.
> 6 votes

# Answer
Round 2!

# Actual Cop: Python, 4 characters, cracked

```
:[ef
```

CPython 3.10.2 on Linux. This blocks all control flow and obvious workarounds.

No file encoding workarounds, please. (If you want, I can invent a language called *Pythom* which doesn't have the encoding syntax feature. Hopefully, though, this is a clear enough rule.)
> 5 votes

# Answer
# Sort-of-cop: Ada, 5 bytes

`:wWlL`

Ada is case insensitive, so letters count twice. `:` prevents defining constants, variables or arguments to functions, `wW` prevents "with"ing any packages that might have variables, and `lL` prevents any sort of loop variables. (There's still a `goto` statement, but without variables it's not enough.)
> 4 votes

# Answer
# Cop-cop, Haskell, 22 characters, cracked by ais523

```
({$                 　`

```

Although this is more restrictive than my original maybe-cop, forbidding block comments and all non-line-break Unicode whitespace (that hyphen-looking one is `U+1680 OGHAM SPACE MARK`), I have worked through the possible crack I initially foresaw.

ais's crack is a bit simpler than what I initially had in mind, but it works on the same principle of using lists for everything, and I realized something like it would work just about the moment I finished writing this possibly faulty Bitwise Cyclic Tag interpreter:

```
[]#_=[]
dataString#program|[[head]<*>[program]]==["0"],[programTail]<-[tail]<*>[program],[dataTail]<-[tail]<*>[dataString]=dataTail:dataTail#programTail
dataString#program|[[head]<*>[dataString]]==["1"],[programTail]<-[tail]<*>[program],programNext<-[head]<*>[programTail],newData<-dataString++programNext=newData:newData#programTail
dataString#program|[programTail]<-[tail]<*>[program]=dataString#programTail
main=do[input]<-sequence[getLine];[[[dataString,program]]]<-pure[[read]<*>[input]];[[cycledProgram]]<-pure[[cycle]<*>[program]];print[dataString#cycledProgram]

```

Try it online!
> 4 votes

# Answer
## Sort-of-cop: C (tcc), 6, 5 4 bytes (cracked by **ais523**)

```
{(?%

```

-1 byte thanks to @RadvylfPrograms

-2 byte thanks to @EngineerGaming

To the best of my knowledge, C is not Turing complete with these restrictions. No control flow, as `if`, `while`, `for`, `switch`, function calls, etc. are ruled out by this subset. I am merely somewhat sure of this answer. There is probably a crack; I just do not know it. The `{` character is in this subset as there are hacky machine-code tricks that can be used to create a function definition without using `(`, but there are none that I know of that are do not use `{` or `(`.

The `?` and `%` are to prevent (tri|di)graph tricks.
> 3 votes

# Answer
## Cop-cop: Applesoft BASIC, 1 byte

```
=

```

Prevents variable assignment, should be pretty easy to figure out.
> 3 votes

# Answer
# Almost certainly not a cop - Vyxal, 15 bytes, cracked by me

```
{(ƛ⁽‡≬λ@∆Ė†E'µøÞ

```

This was a pain.

`†E` provide access to python. `'ƛµ` allow iterating over infinite lists. `{(` are loops. `@⁽‡≬λ` stop the definition of functions.  deals with a certain ACE vulnerability that hasn't been patched yet. `ø` deals with `øV` which is replace until no change. And of course `Ė` (eval as vyxal) is necessary so there are no workarounds.

Just to be on the safe side, I'm banning `Þ`, the delimiter for list digraphs which can be infinite.

I'm pretty sure this blocks all infinite loops.
> 3 votes

# Answer
# Actual Cop: Python, 3 characters, cracked

```
:ef
```

CPython 3.10.2 on Linux. This blocks all control flow and obvious workarounds.

No file encoding workarounds, please. (If you want, I can invent a language called *Pythom* which doesn't have the encoding syntax feature. Hopefully, though, this is a clear enough rule.)
> 3 votes

# Answer
# almost-certainly-not-cop, tinylisp, 1 character, cracked by ais523

```
i

```

Without `i` in tinylisp, you cannot perform if statements, load the library, or construct a string from codepoints (which would give you access to `i` through `eval`ing code), which prevents any control flow from being possible.
> 3 votes

# Answer
# Maybe-cop, Haskell, 4 characters, cracked by pxeger

```
($ `

```

Defining functions is possible, but writing a program is challenging. Nevertheless, this doesn't feel airtight, as only the most straightforward infix opportunities are closed off.
> 3 votes

# Answer
# Sort-of-cop: Headass, 1 byte; cracked by m90

```
E

```

`E` allows you to access stored variables other than the four main registers, access other code blocks, and also halt the program on a dime by trying to reach out of bounds with it (though you can still halt without it)

I'm not sure whether it is TC without it, because you can still loop / enter and exit loops with `{}:;)`, but I feel like the lang may be too constrained to allow you to do enough. Just a gut feeling not sure.

# Sort-of-cop: Headass, 1 byte

```
}

```

On the opposite side of the coin, without matching loop brackets, there's no looping *within* each code block. This means you aren't able to loop through input or all of your stored variables, which makes me 90% sure that it isn't TC, since you can't store arbitrarily many variables. Looping is still possible with `E`, but the main registers are cleared. Additionally, variables have no upper limit, but encoding/decoding data would be hard probably.

# Not a cop: Headass, 2 bytes

```
E}

```

If all else fails, remove all loops :)
> 3 votes

# Answer
## Sort-of-cop: Nim, 1 byte (cracked by the default)

```
:

```

Nim needs `:` to do to any control flow. Thus, as best I can tell, this is a valid if uninteresting answer to this question. I would love to be proven wrong.
> 2 votes

# Answer
## Sort-of-cop: Brainfuck, 1 byte

```
[

```

Well, brainfuck needs this character to loop. This answer is quite boring.
> 2 votes

# Answer
## Sort-of-cop: Brainflak, 1 byte

```
{

```

In effect, a translation of my Brainfuck answer. Without it, there is no looping.
> 2 votes

# Answer
# Sort-of-cop: Charcoal, 3 characters

```
ＦＵＷ

```

and  prevent indefinite loops while  prevents access to Python.
> 2 votes

# Answer
# Sort-of-cop: Retina 0.8.2, 1 character

```
`

```

Without this character you can't configure a stage, which means you can't add an indefinite loop.
> 2 votes

# Answer
# Cop-cop: Batch, 2 characters, cracked

```
iI

```

Without these to form `if` (case-insensitive), you can't use conditional looping.

This was originally a sort-of-cop but ended up becoming a cop-cop. For a sort-of-cop, `%!` should work to prevent accessing variables.
> 2 votes

# Answer
# Sort-of-cop: PARI/GP, 1 character

```
(

```

You can't call a function without `(`, which includes control flow functions like `if`, `while`, `for`. The only remaining control flow is list comprehension, but it can only loop over a list, whose size is known and finite. So every program terminates.
> 2 votes

# Answer
# Sort-of-cop: Python, 2 bytes

`(`

Probably impossible, no spaces and parentheses completely breaks Python, not even allowing imports.
> 2 votes

# Answer
## Sort-of-cop: LOLCODE, 1 byte (cracked by ais523)

```
S

```

This prevents variable declaration, i.e. "I HAS VAR".
> 1 votes

# Answer
## Sort-of-cop: Racket, 2 bytes

```
([

```

To the best of my knowledge, this prevents Racket from being Turing complete by preventing the creation of any control flow, any function declaration, any arithmetic, etc. I might be wrong, as I am quite inexperienced with Racket.
> 1 votes

# Answer
# Sort-of-cop: BitCycle, 3 characters

```
~+=

```

I just took out all ways (I *think*) to do infinite looping and conditionals. Might be proved wrong by someone more experienced in BitCycle than me.
> 1 votes

# Answer
# Sort-of-cop: C#, 3 characters

```
.=;

```

No .Equals() for you!

# Answers cracked by the default:

# Sort-of-cop, 1 byte

```
;

```

# Sort-of-cop

```
=

```

No variables and no conditionals.

There are a lot of these in C#.
> 1 votes

# Answer
## Sort-of-cop: Headass, 4 bytes

```
^+-]

```

Posting this even though it's longer because it uses a different approach; Now you only have access to values 1 and 0 :P (and input i guess but that doesnt count)

I think this is possible but I can't confirm it

For fun, while I'm here,

## Sort-of-cop: Headass, 10 bytes

```
DR^+-[]<>(

```

I have no idea if this is possible. It'd be a computational model I am unfamiliar with. My main idea is something to do with using how many values are on the array somehow. You can technically still use value 0 but it might be tricky, since the only char that explicitly gives 0 here is `)`, which is used for control flow/conditionals, so that might get messy.
> 1 votes

# Answer
# Sort-of-cop: C#, 1 byte

```
(

```

No calling main or other methods, functions, if or loops. Maybe this doesn't count, but you can still write library code.

```
using System;

namespace Code;

public class A {

    public string Greeting { get; set; } = "Hello ";

    public Func<string,string> GreetPerson =>  name => Test + name;

    public Func<int,int> Square => a => a*a;
}

```
> 1 votes

# Answer
## Cop-cop: Elixir, 2 characters

```
d-

```

Without these characters you cannot create any function… maybe.
> 1 votes

# Answer
# Sort-of-cop: Knight, 3 characters

```
E=`

```

Takes out `EVAL`, variable assignment, and ``` (run shell command). Taking out variables should prevent Knight from being Turing complete. `E` is there to prevent the `EVAL` and `ASCII` strategy for running any Knight code (which would allow variable assignment), and ``` is there to prevent running Shell, which is Turing complete.
> 1 votes

# Answer
# Probably-a-Cop: Go, 1 byte

```
(

```

Functions can be anonymous in Go, but they must use a pair of parens to declare and call them. This prevents declaring `main()` as an entry point into a full program, as well as declaring/calling any new functions since Go doesn't have special lambda syntax.
> 1 votes

# Answer
# Sort-of-Cop: Clojure, 3 bytes

```
atf

```

This takes out 6 of the 9 fundamental functions: `atom`, `first`, `rest`, `quote`, `fn`, and `def`. Also blocks `map` and `apply`. Some possible pointers could be `=`, `cond`, `reduce`, `cons`, `eval`, or `conj`.
> 1 votes

---
Tags: restricted-source, cops-and-robbers
---


# Question
Title: Solving an easy Sudoku in increasing digit order
## Introduction:

I'm old-fashioned and still read a physical newspaper in the morning while eating my breakfast. Although I don't like Sudoku that much, I do solve the Light-complexity ones, which are extremely easy. With these, I always try to solve all the numbers using only the Hidden Single technique†, in increasing order from 1 to 9. If I can fill in the current digit in all nine of it cells, I write it down at the top.

Thus far, I've only been able to complete the entire Sudoku in increasing order once††. Usually, a digit has two paired cells where they can go in either combination, so I'll skip them, and fill them in at the end.

† Naked Single and Hidden Single solving techniques are the basic Sudoku solving strategies that won't require any hint numbers to be used. When I solve the Light-complexity Sudoku in my newspaper, and therefore also in this challenge, I only use the Hidden Single solving technique. Here the relevant quote from my Puzzling SE post:

> **2. Hidden Single**
>
> Again, a pretty easy one that everyone knows: When there is only one place in a particular row, column or block for a specific number to go, we can just fill it in. For example:
>
> Here there is only one place for the 2 to go in the center 3x3 box, and that is the marked cell.

## Challenge:

Given a Sudoku, output the set of digits which you were able to fill in all nine occurrences of while solving the Sudoku with only Hidden Single techniques, when going in increasing order from 1 to 9.

**Example:**

Input:

```
[[3,7,0,  0,0,0,  1,0,4],
 [0,1,8,  2,4,0,  0,0,3],
 [0,0,0,  1,7,0,  8,0,0],

 [0,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,0,0,  0,6,1],
 [0,0,0,  0,1,9,  0,0,0],

 [8,0,4,  0,0,2,  0,0,0],
 [0,0,0,  0,8,0,  2,0,9],
 [0,3,1,  0,9,6,  5,4,0]]

```

We first try to fill in all the 1s using Hidden Single techniques:

```
[[3,7,0,  0,0,0,  1,0,4],
 [0,1,8,  2,4,0,  0,0,3],
 [0,0,0,  1,7,0,  8,0,0],

 [1,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,0,0,  0,6,1],
 [0,0,0,  0,1,9,  0,0,0],

 [8,0,4,  0,0,2,  0,1,0],
 [0,0,0,  0,8,1,  2,0,9],
 [0,3,1,  0,9,6,  5,4,0]]

```

Since we were able to fill in all 1s, we add the `1` to the result-set.
Next up are the 2s:

```
[[3,7,0,  0,0,0,  1,2,4],
 [0,1,8,  2,4,0,  0,0,3],
 [0,2,0,  1,7,0,  8,0,0],

 [1,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,2,0,  0,6,1],
 [0,0,0,  0,1,9,  0,0,2],

 [8,0,4,  0,0,2,  0,1,0],
 [0,0,0,  0,8,1,  2,0,9],
 [2,3,1,  0,9,6,  5,4,0]]

```

We were again able to fill in all digits, so we add the `2` to the result-set.
Next up are the 3s:

```
[[3,7,0,  0,0,0,  1,2,4],
 [0,1,8,  2,4,0,  0,0,3],
 [0,2,0,  1,7,3,  8,0,0],

 [1,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,2,0,  0,6,1],
 [0,0,3,  0,1,9,  0,0,2],

 [8,0,4,  0,0,2,  0,1,0],
 [0,0,0,  0,8,1,  2,0,9],
 [2,3,1,  0,9,6,  5,4,0]]

```

We were only able to fill in two 3s, with four 3s still left to fill in. So we won't add it to the result-set, and continue with the 4s:

```
[[3,7,0,  0,0,0,  1,2,4],
 [0,1,8,  2,4,0,  0,0,3],
 [4,2,0,  1,7,3,  8,0,0],

 [1,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,2,4,  0,6,1],
 [0,4,3,  0,1,9,  0,0,2],

 [8,0,4,  0,0,2,  0,1,0],
 [0,0,0,  4,8,1,  2,0,9],
 [2,3,1,  0,9,6,  5,4,0]]

```

These we were able to fill all in, so `4` will be added to the result-set.
Next up are the 5s:

```
[[3,7,0,  0,0,0,  1,2,4],
 [0,1,8,  2,4,0,  0,0,3],
 [4,2,0,  1,7,3,  8,0,0],

 [1,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,2,4,  0,6,1],
 [5,4,3,  0,1,9,  0,0,2],

 [8,0,4,  0,5,2,  0,1,0],
 [0,0,0,  4,8,1,  2,0,9],
 [2,3,1,  0,9,6,  5,4,0]]

```

We were able to fill in two 5s, with four 5s still left to fill in. So we won't add it to the result-set, and continue again.
Etc. for 6s (not added); 7s (not added); 8s (added); and 9s (added). The Sudoku after all the digits looks like this:

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

 [1,6,2,  8,0,7,  4,9,5],
 [9,8,7,  5,2,4,  0,6,1],
 [5,4,3,  6,1,9,  0,8,2],

 [8,9,4,  0,5,2,  0,1,0],
 [7,0,0,  4,8,1,  2,0,9],
 [2,3,1,  0,9,6,  5,4,8]]

```

You don't have to solve the Sudoku any further. You can simply output the final result-set, which is `[1,2,4,8,9]` for this Sudoku.

## Challenge Rules:

* Although we solve the Sudoku from 1 to 9, the result-set doesn't necessarily have to be ordered.
* The input-Sudoku can be in any reasonable format. Can be a matrix of integers with `0` or `-1` for empty cells; a flattened list of integers; a string with spaces for empty cells; or even an image file for all I care. Please specify your input-format in your answer.
* Likewise, the output can be in any reasonable format as well. Can be a list of digits; a string of digits; printed on separated lines to STDOUT; a 1-based indexed binary-list of size 9 for which digits were truthy; etc.

## General Rules:

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

## Test Cases:

(Using a matrix input and list output.)

```
Input:
[[3,7,0,  0,0,0,  1,0,4],
 [0,1,8,  2,4,0,  0,0,3],
 [0,0,0,  1,7,0,  8,0,0],

 [0,6,2,  0,0,7,  4,0,5],
 [9,0,7,  5,0,0,  0,6,1],
 [0,0,0,  0,1,9,  0,0,0],

 [8,0,4,  0,0,2,  0,0,0],
 [0,0,0,  0,8,0,  2,0,9],
 [0,3,1,  0,9,6,  5,4,0]]
Output:
[1,2,4,8,9]

††Input:
[[0,0,0,  0,6,0,  0,7,0],
 [4,8,0,  7,0,0,  0,0,6],
 [2,7,0,  4,5,0,  1,0,3],

 [8,0,0,  1,0,0,  6,3,0],
 [0,0,2,  0,0,5,  9,1,0],
 [0,6,9,  0,8,2,  0,0,0],

 [7,0,0,  0,0,0,  0,2,1],
 [0,0,4,  9,0,8,  0,5,0],
 [0,3,1,  0,4,7,  8,0,0]]
Output:
[1,2,3,4,5,6,7,8,9]

Input:
[[0,0,9,  4,0,0,  7,1,0],
 [0,1,2,  0,7,0,  0,0,9],
 [0,4,0,  2,1,0,  5,0,0],

 [0,2,6,  0,0,0,  0,5,4],
 [0,0,0,  1,8,0,  6,0,7],
 [7,0,8,  6,5,0,  0,0,0],

 [9,0,0,  0,0,3,  0,6,0],
 [6,0,4,  0,2,8,  1,0,0],
 [0,8,0,  7,0,0,  0,9,5]]
Output:
[1,4,6,7,8,9]

Input (actually a High-complexity Sudoku from my newspaper):
[[0,0,0,  2,4,0,  5,0,0],
 [9,0,0,  0,0,8,  0,0,0],
 [0,0,0,  0,0,0,  0,0,8],

 [0,0,0,  0,2,0,  7,0,4],
 [0,0,7,  0,0,0,  3,0,0],
 [0,4,9,  5,0,0,  1,6,0],

 [3,9,0,  0,8,5,  0,2,0],
 [1,0,8,  0,3,0,  4,0,0],
 [0,0,0,  1,0,0,  0,0,0]]
Output:
[]

```

# Answer
# JavaScript (ES6), 239 bytes

Returns a string of digits, or *undefined* if no set at all was completed.

```
m=>(i=1,g=o=>i>9?o:g([u=M=0,1,2,n=9].map(N=p=>m.map((r,y)=>r.map((v,x)=>(A=[x,y+9,b=x/3-~(y/3+5)*3|0],k=v==i,q=1<<x|1<<y+9|1<<b,M|=k*q,v|=M&q,p^9?p^2?p*v&&A.map(j=>N[j]=-~N[j]):v|A.every(j=>N[j]^8)?0:r[x]=u=i:n-=k))))|n|u?o:[o]+i,i+=!u))()

```

Try it online!

### How?

We use a recursive function \\$g\\$ starting with \\$i=1\\$ and making its way to \\$i=10\\$, at which point it immediately stops. The value of \\$i\\$ is the digit that we're currently processing in the grid.

Each iteration is divided into 4 passes. During each pass, we walk through each cell of value \\$v\\$ at position \\$(x,y)\\$.

The following variables are always computed, no matter which pass is processed:

```
k = v == i                        // is the current cell set to i?
b = x / 3 - ~(y / 3 + 5) * 3 | 0  // box number in [18 .. 26]
A = [x, y + 9, b]                 // [ column, row, box ]
q = 1 << x | 1 << y + 9 | 1 << b  // column/row/box bit mask

```
1. We set up a 27-bit mask \\$M\\$ telling in which columns, rows and boxes \\$i\\$ appears.

```
M |= k * q

```
2. For each column, row and box, we figure out the number of cells \\$N\[j\],\\:j\in\\{x,y+9,b\\}\\$ where \\$i\\$ can't possibly appear.

```
v |= M & q
v && A.map(j => N[j] = -~N[j])

```
3. If a column, row or box has exactly 8 cells where \\$i\\$ cannot appear, we set the remaining cell to \\$i\\$ and set the flag \\$u\\$. This is the actual implementation of the *hidden single* rule.

```
v | A.every(j => N[j] ^ 8) ? 0 : r[x] = u = i

```
4. During the last pass, we decrement \\$n\\$ (which is initialized to 9) whenever a cell of value \\$i\\$ is found in the updated grid.

```
n -= k

```

If \\$u\\$ was set, it means that the grid was updated and we do a recursive call with \\$i\\$ unchanged. Otherwise, we do a recursive call with \\$i+1\\$ and append \\$i\\$ to the final output string if \\$n=0\\$.

```
g(n | u ? o : [o] + i, i += !u)

```
> 5 votes

# Answer
# Python3, 677 bytes:

```
R=range
E=enumerate
r=R(0,9,3)
K=lambda b:[(B:=[[(x,y)for y,k in E(j)]for x,j in E(b)]),[*zip(*B)],[[t for X in B[x:x+3]for t in X[y:y+3]]for x in r for y in r]]
S=lambda x:type(x)==int
Q=R(1,10)
def U(b,I):
 b=eval(str(b))
 for x,j in E(b):
  for y,k in E(j):
   if k==0:b[x][y]={*Q}-{b[X][Y]for i in K(b)for T in i for X,Y in T if((x,y)in T)&S(b[X][Y])}
 for x,j in E(b):
  for y,k in E(j):
   if 1-S(k)and{I}==k-{L for X,Y in{*[i for i in K(b)[-1]if(x,y)in i][0]}-{(x,y)}for L in[b[X][Y],[]][S(b[X][Y])]}:b[x][y]=I
 return[[[0,i][S(i)]for i in J]for J in b]
def f(b):
 for i in Q:
  while b!=(b:=U(b,i)):1
  if all(any(i==b[x][y]for x,y in T)for O in K(b)for T in O):yield i

```

Try it online!
> 4 votes

---
Tags: code-golf, number, grid, puzzle-solver, sudoku
---


title: Is it a properly tiered list?

text:
# Question
Title: Is it a properly tiered list?
A ragged list is a (finite depth) list where each element is either a positive integer or a ragged list.

A ragged list is *properly tiered* if it contains either all positive integers or all properly tiered ragged lists.

For example `[1,2,3,6]` is properly tiered because it is a list of only positive integers. `[[1,2],[[1]],[[6],[[]]]]` is also properly tiered, because it has 3 elements which are all properly tiered lists themselves. Note that all the lists don't have to be the same depth.

The list `[[1,2],[[6],4]]` is *not* properly tiered because one of it's elements is a ragged list which contains a mixture of lists and positive integers.

## Task

Take a ragged list via any natural format and determine if it is a properly tiered list. You should output one of two consistent values, the first if the input is a properly tiered list and the second if it is not.

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

## Test cases

```
[] -> Yes
[1,2,3,6] -> Yes
[[1,2],[[1]],[[6],[[]]]] -> Yes
[[]] -> Yes
[1,[2]] -> No
[[1,2],[[6],4]] -> No
[[1,[2]],[[3],4]] -> No
[1,[]] -> No

```

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

*-1 thanks to @emanresuA*

Returns *false* for valid, *true* for invalid.

```
a=>/\d,\[|],\d/.test(JSON.stringify(a))
```

Attempt This Online!

Or **23 bytes** if we simply take a string as input:

```
a=>/\d,\[|],\d/.test(a)
```

Attempt This Online!

---

# JavaScript (Node.js), 41 bytes

Returns *false* for valid, *true* for invalid.

```
f=(a,q)=>a.some(b=>q-(q=!b.at)||!q&&f(b))
```

Attempt This Online!

Or:

```
f=(a,q)=>a.some(b=>q-(q=!b.at)|f(q?[]:b))
```

Attempt This Online!
> 10 votes

# Answer
# Python, ~~61~~ ~~40~~ ~~39~~ ~~35~~ 32 bytes

```
f=lambda l:l*-1or[l.sort(key=f)]

```

Attempt This Online!

Errors if the list is not properly tiered, otherwise returns `[]`.

---

-1 byte from @Mukundan314
-5 bytes from @loopy walt for various cleverness
-3 bytes from @Mukundan314
> 10 votes

# Answer
# BQN, ~~17~~ 15 bytesSBCS

Thanks to DLosc for -2 bytes!

```
{1<≡?∧´¨;≡}

```

Run online!

gives the nesting depth of a list:

`1<≡?` If the depth is larger than 1 ( contains at least one list):
`∧´¨` Are all the elements in the list properly tiered?
Else, if is either an integer or a list of integers:
Return the depth (1 for a list, 0 for an integer)
> 8 votes

# Answer
# Brachylog, ~~8~~ 7 bytes

```
ℕᵐ|ċᵐ↰ᵐ

```

Try it online!

### Explanation

```
ℕᵐ        The input is a list of only integers
  |       Or
   ċᵐ     The input is a list of only lists
     ↰ᵐ   Recursive call on each sub-list

```
> 7 votes

# Answer
# Typescript, 19 bytes

```
type A=number[]|A[]

```

Try it online!

Type system shows an error whenever the typed variable doesn't conform to the requirements.
> 7 votes

# Answer
# 05AB1E, 19 (or 2..) bytes

```
d"Ð1åi˜Që®δ.V"©.Vß_

```

Outputs `0` for truthy and `1` for falsey.

Try it online or verify all test cases.

If the challenge would have used the default truthy/falsey definition instead of overwriting the meta, it could have been **2 bytes** instead by erroring:

```
¸P

```

Gives an error† as falsey value, or not as truthy value.

Try it online or verify all test cases (somewhat.. the falsey test cases contain rubbish output and lack trailing newline. Not sure how to properly try-catch the inner Elixir errors in 05AB1E.)

**Explanation:**

```
d            # Convert each value in the (implicit) input-list to a 1
             # (with a >=0 check)
 "..."       # Push the recursive string defined below
      ©      # Store it in variable `®` (without popping)
       .V    # Evaluate and execute it as 05AB1E code
         ß   # Pop and push the flattened minimum
             # (0 for falsey; 1 or "" for truthy)
          _  # Check that this value is equal to 0 (1 if 0; 0 otherwise)
             # (after which the result is output implicitly)
Ð            #  Triplicate the current list
 1åi         #  If it contains a 1 as item:
    ˜Q       #   Check if the list is unchanged when flattened (thus all are 1s,
             #   without inner lists)
   ë         #  Else:
     δ       #   Map over each inner list:
    ® .V     #    And do a recursive call to `®`

¸            # Wrap the (implicit) input-list into a list
 P           # Take the product of each inner-most list,
             # which will error if an inner list contains both integers and lists
             # (implicitly output the result if it didn't error)

```

† The (Elixir) error is either an `ArithmeticError: bad argument in arithmetic expression` or an `UndefinedError: protocol Enumerable not implemented for int.` depending on how deep the integer causing the error is.
> 6 votes

# Answer
# Vyxal, 11 bytes

```
λÞjṅ[Þj|vxA

```

Try it Online!
> 5 votes

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

```
*/^9 56?4/'6!3':`j@^:

```

Try it online!

Uses a similar idea to Arnauld and Neil's regex approach, but without regex.

```
*/^9 56?4/'6!3':`j@^:   Input: a ragged list
                   ^:   change all numbers to zeros
                `j@     JSON stringify (which contains only `[]0,`)
             3':        get all length-3 contiguous substrings
           6!    each charcode mod 6 (`[]0,` -> 1 3 0 2)
        4/'      base 4 each
  ^9 56?         test if each number is not one of 9 or 56 (which can only appear if
                 the substring "0,[" or "],0" appear in the string respectively)
*/               1 if all true (or empty), 0 otherwise

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~28~~ ~~24~~ 19 bytes

```
Min[0#/.{0...}->1]&

```

Try it online!

Returns `1` if the list is properly tiered, or `0` otherwise.

Checks that integers are only present in non-nested lists.

```
    0#              zero integers
      /.{0...}->1   turn lists of 0s into 1
Min[             ]  0s remaining?

```
> 4 votes

# Answer
# Jelly, 9 bytes

```
ß€ŒḊ⁺Ḋ$?P

```

Try it online!

Port of ovs's BQN solution.

```
  ŒḊ         The depth of the argument (0 if integer)
       ?     unless
    ⁺        the depth of the argument
     Ḋ       is greater than 1 (range [2 .. depth] is nonempty)
ß            in which case recur
 €           on each element
        P    and take the product of the results.

```
> 4 votes

# Answer
# Python, 54 bytes

```
f=lambda x:x*0==0 or all((y*0==x[0]*0)&f(y)for y in x)
```

Attempt This Online!

We can get it a little shorter with Whython, because iterating through a number is an error:

# Whython, 46 bytes

```
f=lambda x:all((y*0==x[0]*0)&f(y)for y in x)?1
```

Attempt This Online!
> 4 votes

# Answer
# , 56 bytes

```
f=\(x)`if`(all(y<-Map(is.list,x)),all(Map(f,x)),!any(y))
```

Attempt This Online!

Checks whether all elements are lists. If so, recurses, otherwise none of the elements may be a list.

Utilises the fact that `all` and `any` work on depth-1 lists so we may use `Map` over `sapply`.
> 4 votes

# Answer
# Rust, ~~147~~ ~~131~~ 123 bytes

-18 bytes thanks to @alephaalpha for reminding me `matches!` exists

-8 bytes thanks to @bubbler for reminding me `Vec` impelments `Deref<Target=[T]>` and @alephaalpha for reminding me you can use `if` in `matches!`.

```
enum E{a(u8),b(Vec<E>)}fn f(e:&[E])->bool{e.iter().all(|m|matches!(m,E::a(_)))|e.iter().all(|m|matches!(m,E::b(k)if f(k)))}

```

Playground Link
> 4 votes

# Answer
# Ruby, ~~21~~ 16 bytes

```
p !/\],\d|\d,\[/

```

Try it online!

* Thanks to @Dom Hastings for saving 6.
* Fixed output to be of two consistent values.

Using Regexp.

Takes a string array literal and return *true* if list is tiered, *false* otherwise.

**Or 50 bytes**

Checking recursively.

```
f=->l{l.all?{|e|e*0==0}||l.all?{|e|e*0==[]&&f[e]}}

```

Try it online!
> 4 votes

# Answer
# Factor \+ `json`,  ~~58 38~~  37 bytes

```
[ >json R/ ],\d|\d,\[/ re-contains? ]

```

`>json` postdates the Factor builds on TIO and ATO, so have a picture of running this in Factor's REPL:

If we're allowed to take input as a string, `>json` can be removed for -6 bytes.
> 3 votes

# Answer
# JavaScript, 36 bytes

```
f=a=>a.some?.(v=>v.at!=a[0].at|f(v))

```

Return `false` for valid, `true` for invalid.

```
f=a=>a.some?.(v=>v.at!=a[0].at|f(v))

update = () => { try { output.value = input.value.trim().split('\n').map(x => [JSON.parse(x.split('->')[0]), x.split('->')[1].trim() !== 'Yes']).map(([i, e]) => f(i) + ' ' + e).join('\n'); } catch {} }

update();
input.oninput = update;
```

```
<div style="display: flex">
<textarea id=input style="flex: 0 0 50%; font: inherit; padding: 10px;">[] -> Yes
[1,2,3,6] -> Yes
[[1,2],[[1]],[[6],[[]]]] -> Yes
[[]] -> Yes
[1,[2]] -> No
[[1,2],[[6],4]] -> No
[[1,[2]],[[3],4]] -> No
[1,[]] -> No</textarea>
<output id=output style="flex: 1 1 0; white-space: pre; padding: 15px;"></output>
</div>
```
> 3 votes

# Answer
# jq, 35 bytes

```
[..|map(type)?|unique|length]|max<2

```

Try it online!

Below, "E" indicates where `map(type)` produces an error. This is supressed with `?`.

```
input:        [1,[2,3]]
[..]:         [[1,[2,3]],          1, [2,3],                2, 3]
[|map(type)]: [["number","array"], E, ["number", "number"], E, E]
[|unique]:    [["number","array"],    ["number"]]
[|length]:    [2,                     1]
|max<2:       false

```
> 3 votes

# Answer
# Retina 0.8.2, 12 bytes

```
1`\d,\[|],\d

```

Try it online! Link includes test cases. Outputs `0` for a properly tiered list. Explanation: Same approach as @Arnauld, just check for an integer next to a list. Would cost 3 bytes to output `1` for a properly tiered list.
> 2 votes

# Answer
# Charcoal, 27 bytes

```
⊞υθＦυＦι⊞υ⁺⟦⟧κ⬤υΦ²⬤ι⁼μ⁼ν⁺⟦⟧ν

```

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

```
⊞υθＦυＦι⊞υ⁺⟦⟧κ

```

Enumerate the ragged list and all of its elements but replacing integers with empty lists (which are always properly tiered).

```
⬤υΦ²⬤ι⁼μ⁼ν⁺⟦⟧ν

```

Check that all lists contain either only integers or only sublists (or both, in the case of empty lists).
> 2 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
FreeQ[a_/;!SameQ@@Head/@a]

```

Try it online!

Checks if the input contains any list whose elements do not have the same head (`List` or `Integer`).
> 2 votes

# Answer
# Ruby, ~~40 36~~ 29 bytes

```
f=->l{l*0!=0&&!l.uniq(&f)[1]}

```

Try it online!

### Why?

First check if l is a list (`l*0!=0`)

Then map f on l and check that the result is the same for all elements. By applying `uniq` directly on the list, instead of `l.map(&f).uniq` we can just check if there is a second element (`uniq` returns elements of the list instead of `true` or `false`). If we map the function first, we must check that the size is 2, because if we check the second element, it could be `false`, which is not what we want.
> 2 votes

# Answer
# PARI/GP, 38 bytes

```
f(a)=(#a>#b=[f(x)|x<-a,#x'==#x])*#b||b
```

Attempt This Online!

Returns `0` for valid, `1` for invalid.

---

# PARI/GP, 40 bytes

```
f(a)=[#x'==#x|x<-a]&&[x'===0||f(x)|x<-a]
```

Attempt This Online!

Returns `0` for valid, `1` for invalid.
> 1 votes

# Answer
# Pyth, 13 bytes

```
:w"\d,\[|],\d

```

Try it online!

Outputs `False` if list is properly tiered and `True` otherwise
> 1 votes

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

```
f=v=>v.every?.(u=>!u.at)|v.every?.(f)

```

Attempt This Online!

Outputs `1` for properly tiered list, `0` for lists that is not properly tiered, or integers (only used for recursive case)
> 1 votes

# Answer
# Whython, 36 bytes

```
f=lambda l:sum(l)>=0?all(map(f,l))?0

```

Attempt This Online!

*Test harness stolen from the one Mukundan314 contributed to Adam's Python answer*

### Explanation

```
f=                                    # f is
  lambda l:                           # a function that takes one argument l:
           sum(l)                     # Sum the list (errors unless all items are numbers)
                 >=0                  # If that worked, return True
                    ?                 # If that errored,
                         map(f,l)     # Recurse on each item (errors if l is not a list)
                     all(        )    # If that worked, return True if every item returned True
                                  ?   # If that errored (l is not a list),
                                   0  # Return 0 (falsey)

```

The only time the function returns `0` is when it is called on an integer. If it is called on a list, it will always return either `True` or `False`.
> 1 votes

---
Tags: code-golf, decision-problem, ragged-list
---


title: Multiply numbers by their depth

text:
# Question
Title: Multiply numbers by their depth
Given a ragged list, we can define an element's depth as the number of arrays above it, or the amount that it is nested.

For example, with the list `[[1, 2], [3, [4, 5]]]` the depth of the `2` is 2, as it is nested within two lists: The base list, and the list `[1, 2]`. The depth of the `4` is 3 as it is nested within three lists.

Your challenge is to, given a ragged list of positive integers, multiply them by their depths.

For example, given the list `[[1, 2], [3, [4, 5]], 6]`:

* The depth of 1 is 2, so double it -\> 2
* The depth of 2 is also 2, so double it -\> 4
* The depth of 3 is 2, so double it -\> 6
* The depth of 4 is 3, so triple it -\> 12
* The depth of 5 is 3, so triple it -\> 15
* The depth of 6 is 1, so leave it alone -\> 6

So, the result is `[[2, 4], [6, [12, 15]], 6]`.

Another way of viewing it:

```
[[1, 2], [3, [4, 5 ]], 6]  - Original list
[[2, 2], [2, [3, 3 ]], 1]  - Depth map
[[2, 4], [6, [12,15]], 6]  - Vectorising product

```

You can assume the list won't contain empty lists.

This is , shortest wins!

## Testcases

```
[[1, 2], [3, [4, 5]], 6] => [[2, 4], [6, [12, 15]], 6]
[[3, [2, 4]]] => [[6, [6, 12]]]
[[9, [[39], [4, [59]]]], 20] => [[18, [[156], [16, [295]]]], 20]
[2, [29]] => [2, [58]]
[[[[[[[[9]]]]]]]] => [[[[[[[[72]]]]]]]]

```

# Answer
> 17 votes
# Vyxal, 4 bytes

```
⁽L€*

```

Try it Online!

```
⁽L€*
⁽ €  # At each value in the input, all the way down, run the following on the multi-dimensional index of the current value:
 L   # Length. This gets the current depth
   * # Vectorizically (is that a word?) multiply by the input

```

# Answer
> 10 votes
# Wolfram Language (Mathematica), 12 bytes

```
#0/@#-#&@-#&

```

Try it online!

```
         -# negate
#0/@#  &@   at each level:
     -#       subtract original value(s)
            (atoms: #0/@#-# = #-# = 0)

```

# Answer
> 6 votes
# Python, ~~51~~ ~~49~~ ~~44~~ 43 bytes

```
f=lambda l,d=0:l*d*-1or[f(s,d-1)for s in l]

```

Attempt This Online!

This is a really fun abuse of the overloading of the `*` operator:

* If `l` is a positive integer, then `l*d*-1` equals `l*-d`, which is always truthy (because the integers are always positive, so non-zero), so it returns `l*-d`, where `d` is the negation of the depth.
* If `l` is an array, then `l*d` produces `d` copies of the list joined together, which is actually interpreted as 0 copies of the list joined together (because `d` is negative), i.e. `[]`. So `l*d*-1` equals equals `[]*-1` equals `[]`, which is falsy, so the second part of the conditional is run.

---

-1 bytes from @loopywalt by flipping the sign of `d`.

# Answer
> 6 votes
# K (ngn/k), 17 bytes

```
{$[x~*x;0;x+o'x]}

```

Try it online!

# Answer
> 5 votes
# Jelly, 5 bytes

```
ŒJẈṁ×

```

Try it online!

```
ŒJ       All multidimensional indices, in flat order.
  Ẉ      Get the length of each index (= depth of value at index).
   ṁ     Mold to the structure of the input,
    ×    and multiply corresponding elements.

```

# Answer
> 5 votes
# BQN, 9 bytes

```
{+⟜⍟=¨}

```

Try it here!

-5 bytes thanks to @att!

## Explanation

* `{...¨}` for each element *n* over input...
    + `...⍟=` if rank of *n* \> 0 (i.e. *n* is a list)...
        - `+⟜` *n* \+ F(*n*)

# Answer
> 4 votes
# JavaScript, 32 bytes

```
(g=k=>a=>a.map?.(g(-~k))??a*k)()

```

```
f =

(g=k=>a=>a.map?.(g(-~k))??a*k)()

testcases = `
[[1, 2], [3, [4, 5]], 6] => [[2, 4], [6, [12, 15]], 6]
[[3, [2, 4]]] => [[6, [6, 12]]]
[[9, [[39], [4, [59]]]], 20] => [[18, [[156], [16, [295]]]], 20]
[2, [29]] => [2, [58]]
[[[[[[[[9]]]]]]]] => [[[[[[[[72]]]]]]]]
`.trim().split('\n').map(l => l.split(' => ').map(t => JSON.parse(t)));
testcases.forEach(([i, e]) => {
  console.log(JSON.stringify(f(i)) === JSON.stringify(e), JSON.stringify(f(i)));
});
```

The submitted function is partial invoked currying function. Maybe the first time I try to use this pattern in a code-golf.

However, the `a.map?.(…)??…` pattern is quite common for .

# Answer
> 3 votes
# Retina 0.8.2, 51 bytes

```
\d+
$*
1(?=((\[)|(?<-2>])|(])|[^][])+)
$#3$*
1+
$.&

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
1(?=((\[)|(?<-2>])|(])|[^][])+)
$#3$*

```

Replace each `1` with the number of unmatched `]`s in the input's suffix, which equals its depth, thereby multiplying each number by its depth.

```
1+
$.&

```

Convert to decimal.

Just creating the depth map can be readily achieved with the following code:

```
\d+(?=((\[)|(?<-2>])|(])|[^][])+)
$#3

```

Retina 1 can perform multiplication as part of a substitution, solving the original problem as follows:

```
\d+(?=((\[)|(?<-2>])|(])|[^][])+)
$.($#3**

```

Try it online! Link includes test cases. Explanation: The `**` causes the capture result (the depth) to be implicitly multiplied by the matched integer, converted to unary, and the `$.(` then converts back to decimal.

# Answer
> 3 votes
# PARI/GP, 25 bytes

```
f(a)=if(#a',a+apply(f,a))
```

Attempt This Online!

# Answer
> 3 votes
# Racket, ~~88~~ 63 bytes

```
(define(m l[d 0])(if(list? l)(map(λ(n)(m n(+ 1 d)))l)(* l d)))

```

Try it online!

-25 from removing whitespace, ty @emanresu A!

# Answer
> 2 votes
# lin, 26 bytes

```
"deps1> (.+ \@ ' + ) e&".'

```

Try it here! Uses stack as nested list.

For testing purposes (use `-i` flag when running locally):

```
[[1 2] [3 [4 5]] 6] \; '
"deps1> (.+ \@ ' + ) e&".'

```

## Explanation

Prettified:

```
( deps 1> (.+ \@ ' + ) e& ).'

```
* `(...).'` map...
    + `deps 1> (...) e&` if depth \> 1 (i.e. is list)...
    + `.+ \@ ' +` recurse and vector-add to current element

# Answer
> 2 votes
# 05AB1E, ~~23~~ ~~16~~ 15 bytes

```
.γd}DžuSδ¢ÆηO*J

```

Try it online!

-2 thanks to @Kevin Cruijssen

Takes the input list as a string, using `(` and `)`.

If `a` and `b` are valid list boundaries, then it's -1 for replacing `žu` with `A`. Try it online!

# Answer
> 2 votes
# 05AB1E, 16 bytes

```
_"Ddië®δ.V>"©.V*

```

Try it online or verify all test cases.

**Explanation:**

First step of this 05AB1E answer of mine.

```
_            # Transform each integer in the (implicit) input to 0
 "..."       # Push the recursive string explained below
      ©      # Store it in variable `®` (without popping)
       .V    # Evaluate and execute it as 05AB1E code
             # (we now have the depth of each item in the ragged input-list)
         *   # Multiply each by the value in the (implicit) input-list at the same
             # positions
             # (after which the result is output implicitly)

  D          # Duplicate the current list
   dië       # If it's not an integer (so it's a list):
       δ     #  Map over each item:
      ® .V   #   Do a recursive call
          >  #  Then increase each integer in this list by 1

```

# Answer
> 2 votes
# Perl 5 `-p`, 33 bytes

```
s/\d+/$&*($`=~y|[||-$`=~y|]||)/ge

```

Try it online!

For each number, depth is determined by counting the number of `[` and subtracting the number of `]` that come before it in the string.

# Answer
> 2 votes
# Ruby, 38 bytes

```
f=->a,d=0{a*0==0?a*d:a.map{f[_1,d+1]}}
```

Attempt This Online!

# Answer
> 2 votes
# Ruby, 38 bytes

```
f=->a,i=1{a.map{f[_1,i+1]rescue _1*i}}
```

Attempt This Online!

An alternative to Razetime's answer for the same byte count.

# Answer
> 2 votes
# Knight, ~~124~~ 118 bytes

```
;=p++=o""=i=d 0P;W<=i+1iLp;=n=cGp i 1I>c"9";=d-d-1*2<c"]"=o+o cI<"/"c;W&<=tGp+1i 1"["<"/"t;=i+1i=n+n t=o+o*d n=o+o cOo

```

Try it online!

Nice, big ole fat Knight program. Parses it as a string lol

Ungolfed and commented:

```
; = p + + = o "" = i = d 0 PROMPT                # p = (o = "") + (i = d = 0) + input()
; W < = i + 1 i LENGTH p                         # while (i = i + 1) < len(p):
  ; = n = c GET p i 1                            #   n = c = p[i]
  : IF > c "9"                                   #   if c > "9":
    ; = d - d - 1 * 2 < c "]"                    #     d = d - (1 - 2 * (c < "["))
    : = o + o c                                  #     o = o + c
  # ELSE                                         #   else:
    : IF < "/" c                                 #     if "/" < c:
      ; WHILE & < = t GET p + 1 i 1 "[" < "/" t  #       while ((t = p[i + 1]) < "[") and ("/" < t):
        ; = i + 1 i                              #         i = i + 1
        : = n + n t                              #         n = n + t
      : = o + o * d n                            #       o = o + d * n
    # ELSE                                       #     else:
      : = o + o c                                #       o = o + c
: OUTPUT o                                       # print(o)

```

-6 bytes thanks to Adam.

# Answer
> 1 votes
# Charcoal, 35 bytes

```
⊞υ⟦¹θ⟧ＦυＵＭ⊟ι⎇⁺⟦⟧κ∧⊞Ｏυ⟦⊕Σικ⟧κ×Σικ⭆¹θ

```

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

```
⊞υ⟦¹θ⟧

```

Start by considering the input list at depth `1`.

```
Ｆυ

```

Loop through the list and its sublists.

```
ＵＭ⊟ι

```

Loop through the elements of the current list.

```
⎇⁺⟦⟧κ

```

If this is a sublist, then...

```
∧⊞Ｏυ⟦⊕Σικ⟧κ

```

... push it with the incremented depth to the list of sublists, but don't actually change the list itself yet, otherwise...

```
×Σικ

```

... multiply the element by the current depth.

```
⭆¹θ

```

Pretty-print the result, since Charcoal's default formatting is not designed for ragged lists.

# Answer
> 1 votes
# , 12 bytes

Takes input as a boxed array.

```
*L:0#L:1@{::
```

Attempt This Online!

`{::` Map; replaces each leaf by its multidimensional index.
`#L:1` At level 1 (for each index vector), take the length.
`*L:0` multiply with input at level 0 (leafs).

# Answer
> 1 votes
# jq, 31 bytes

```
def f(n):map(f(n+1))?//.*n;f(0)

```

Try it online!

The key to the base case: If `map()` fails (since we try to map over a number instead of an array), `?` suppresses the error, `//` substitutes the alternate value of `.*n`

# Answer
> 1 votes
brev, 46 bytes

```
(c(fn(if(list? y)(map(c f(+ x 1))y)(* y x)))0)

```

Classic lispy depth first tree walking: map if not atom

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


# Question
Title: An Array of Challenges #2: Separate a Nested Array
*Note: This is #2 in a series of challenges. For the previous challenge, click here.*

# Separating Nested Lists

> To separate values in a nested list, flatten it, and then wrap each value so it is at the same nested depth as before.

That is to say, this list:

```
[1, [2, 3], [4, 4, [5, 2], 1]]

```

Would become:

```
[1, [2], [3], [4], [4], [[5]], [[2]], [1]]

```

---

# The Challenge

Your task is to write a program which takes any nested list of positive integers (within your language's limits) and performs this separation operation.

You may submit a function which takes the list as an argument, or a full program which performs I/O.

As this is , the shortest submission (in bytes) wins!\*

\*Standard golfing loopholes are banned. You know the drill.

---

# Test Cases

Input lists will only ever contain integers in your language's standard integer size. To avoid languages' constraints preventing them from competing, values will not be nested at depths of more than 10.

You may assume that input will not have empty sub-lists: for example - `[[5, []]]` will not be given. However, the main list could be empty.

```
[]            ->  []

[[1, 2]]      ->  [[1], [2]]
[3, [4, 5]]   ->  [3, [4], [5]]
[3, [3, [3]]] ->  [3, [3], [[3]]]
[[6, [[7]]]]  ->  [[6], [[[7]]]]
[[5, 10], 11] ->  [[5], [10], 11]

```

Don't hesitate to leave a comment if I've missed out a corner case.

# Example

I threw together a quick (ungolfed) Python 3 solution as an example - you can **test it on repl.it**.

# Answer
> 5 votes
# Brachylog v1, 16 bytes

```
:{##:0&:ga|g}ac|

```

Try it online!

### Explanation

```
Example input: [1:[2:3]]

:{          }a     Apply the predicate below to each element of the list: [[1]:[[2]:[3]]]
              c    Concatenate: Output = [1:[2]:[3]]
               |   Or: Input = Output = []

  ##                 Input is a list: e.g. Input = [2:3]
    :0&              Call recursively the main predicate with this input: [2:3]
       :ga           Group each element in a list: Output = [[2]:[3]]
          |          Or (not a list): e.g. Input = 1
           g         Group into a list: Output = [1]

```

# Answer
> 19 votes
## Mathematica, ~~24~~ 21 bytes

```
##&@@List/@#0/@#&/@#&

```

or one of these:

```
##&@@List/@#&/@#0/@#&
##&@@List@*#0/@#&/@#&
##&@@List/@#&@*#0/@#&

```

### Explanation

The reason this is so short is that it's basically a recursion that doesn't require an explicit base case.

There's a lot of syntactic sugar here, so let's start by ungolfing this. `&` denotes an unnamed function left of it, whose argument is written as `#`. Inside this function `#0` refers to the function itself, which allows one to write unnamed recursive functions. But let's start by giving the inner function a name and pulling it out:

```
f[x_] := ##& @@ List /@ f /@ x
f /@ # &

```

The other important syntactic sugar is `f/@x` which is short for `Map[f, x]` i.e. it calls `f` on every element of `x`. The reason `f[x_] := ... f /@ x` doesn't lead to infinite recursion is that mapping something over an atom leaves the atom unchanged without actually calling the function. Hence, we don't need to check for the base case (current element is an integer) explicitly.

So the function `f` first recurses down to the deepest list inside `x`, at which point `f/@` becomes a no-op. Then we call use `##& @@ List /@` on that. Mapping `List` over the list simply wraps each element in a separate list, so `{1, 2, 3}` becomes `{{1}, {2}, {3}}`. Then we *apply* `##&` to it, which means the head (i.e. the outer list) gets replaced by `##&`, so this turns into `##&[{1}, {2}, {3}]`. But `##&` simply returns it's arguments as a `Sequence` (which you can think of as an unwrapped list, or a sort of "splat" operator in other languages).

So `##& @@ List /@` turns a list `{1, 2, 3}` into `{1}, {2}, {3}` (kind of, that last thing is actually wrapped in the head `Sequence`, but that vanishes as soon as we use the value anywhere).

That leaves the question why `f` itself isn't already the solution to the challenge. The problem is that the outermost list should be treated differently. If we have input `{{1, 2}, {3, 4}}` we want `{{1}, {2}, {3}, {4}}` and *not* `{{1}}, {{2}}, {{3}}, {{4}}`. My original solution fixed this by passing the final result as a list of arguments to `Join` which would restore the outer level of lists, but this one just skips the outer level by using `f` *itself* in a map on the output. Hence `f` is only applied to the individual elements of the outermost list and never gets to touch that list.

As for the other three solutions, the first one simply applies the recursion outside of `f` which works just as well. The other two solutions avoid a repeated `Map` operation by first composing two functions and then mapping the result only once.

# Answer
> 8 votes
# , ~~19~~ 18 bytes

```
(<@]/@,~>)S:0 1{::

```

This is an anonymous verb that takes and returns boxed arrays, which are J's (rather cumbersome) version of nested arrays. See it pass all test cases.

## Explanation

This uses the somewhat exotic operations `{::` (map) and `S:` (spread), which operate on boxed arrays. `{::` replaces each leaf with the boxed path to that leaf. `S:` applies a given verb to a given nesting depth, then splats the results into an array.

```
(<@]/@,~>)S:0 1{::  Input is y.
(        )          Let's look at this verb first.
        >           Open the right argument,
      ,~            append the left argument to it,
    /               then reduce by
 <@]                boxing. This puts the left argument into as many nested boxes
                    as the right argument is long.
                    This verb is applied to y
               {::  and its map
            0 1     at levels 0 and 1.
                    This means that each leaf of y is paired with its path,
                    whose length happens to be the nesting depth of y,
                    and the auxiliary verb is applied to them.
          S:        The results are spread into an array.

```

# Answer
> 3 votes
# R, 199 bytes

```
function(l){y=unlist(l);f=function(x,d=0){lapply(x,function(y){if(class(y)=='list'){f(y,d=d+1)}else{d}})};d=unlist(f(l));lapply(1:length(d),function(w){q=y[w];if(d[w]){for(i in 1:d[w])q=list(q)};q})}

```

This question was HARD. R's lists are a bit weird and it is absolutely not straightforward to loop over all the elements of sublists. It is also not straightforward to then determining the depth of that list. Then the challenge becomes to recreate the list with all the elements separated, so we also need a way to adaptively create a list of a certain depth.

The solution consists of two big parts. A recursive function that loops over all the lists and records the depth:

```
  f=function(x,d=0){
    lapply(x,function(y){
      if(class(y)=='list'){
        f(y,d=d+1)
      } else {
        d
      }})
  }

```

When we have the depths of every entry of the vector `unlist(l)`, stored in `d`, we implicitly create a list through `lapply`, and fill it with the following function:

```
  lapply(1:length(d),function(w){
    q=y[w]
    if(d[w]){
      for(i in 1:d[w]){
        q=list(q)
      }
    }
    q
  })

```

In this apply call, we create an object `q` with the value of the entry in the list, check its depth and see if it is nonzero. If it is zero, we can just leave it as a numeric value. If it is non-zero, we need to nest it in that amount of lists. So we call a for-loop `d` times and repeatedly call `q=list(q)`.

`lapply` then puts all these values of `q` in a list, creating the desired output.

### Complete program with proper spacing and such:

```
function(our.list){
  values <- unlist(our.list)
  f <- function(part.list, depth = 0){
    lapply(part.list, function(y){
      if(class(y)=='list'){
        f(y, depth <- depth + 1)
      } else {
        return(depth)
      }})
  }
  depths <- unlist(f(our.list))
  new.list <- lapply(1:length(depths), function(w){
    q <- values[w]
    if(depths[w] != 0){
      for(i in 1:depths[w]){
        q <- list(q)
      }
    }
    return(q)
  })
  return(new.list)
}

```

# Answer
> 3 votes
## Retina, 34 bytes

```
+`(.(?>()\[|(?<-2>)]|.)+)\2,
$1],[

```

Try it online!

# Answer
> 2 votes
## JavaScript (Firefox 30-57), 53 bytes

```
f=a=>[for(e of a)for(d of e.map?f(e):[e])e.map?[d]:d]

```

Best ES6 answer I have so far is 76 bytes:

```
f=(a,r=[],d=0)=>a.map(e=>e.map?f(e,r,d+1):r.push((n=d=>d?[n(d-1)]:e)(d)))&&r

```

# Answer
> 2 votes
# Python 2, ~~122~~ 106 bytes

Pretty terrible score, just a straightforward implementation.

Thanks to @Zachary T for helping save 16 bytes!

```
def x(l,a=[],d=0):
 n=lambda b:b and[n(b-1)]or l
 if'['in`l`:[x(e,a,d+1)for e in l];return a
 else:a+=n(d)

```

Call `x` with one argument to run. For some reason it can only be run once.

# Answer
> 2 votes
# PHP, ~~101~~ 94 bytes

saved 1 byte thanks to @Christoph, saved another 6 inspired by that.

```
function s($a){foreach($a as$b)if($b[0])foreach(s($b)as$c)$r[]=[$c];else$r[]=$b;return$r?:[];}

```

recursive function, pretty straight forward

**breakdown**

```
function s($a)
{
    foreach($a as$b)                // loop through array
        if($b[0])                       // if element is array
            foreach(s($b)as$c)$r[]=[$c];    // append separated elements to result
        else$r[]=$b;                    // else append element to result
    return$r?:[];                   // return result, empty array for empty input
}

```

# Answer
> 2 votes
# C (gcc), 147 bytes

```
d=0,l,i;
P(n,c){for(;n--;)putchar(c);}
main(c){for(;~(c=getchar());l=i)i=isdigit(c),P((l<i)*d,91),P(i,c),P((l>i)*d,93),P(l>i,32),d+=(92-c)*(c>90);}

```

Example input:

```
1 [23 3] [40 4 [5 2] 1]

```

Example output:

```
1 [23] [3] [40] [4] [[5]] [[2]] [1]

```

# Answer
> 2 votes
# stacked, noncompeting, 25 bytes

```
{e d:e$wrap d 1-*}cellmap

```

This is a function in that it modifies the top member of the stack. If you want a bonafide function, just add `[` and `]` to the beginning and end. Try it here!

Here's a readable version:

```
{ arr :
  arr { ele depth :
    ele   $wrap depth 1- * (* execute wrap n times, according to the depth *)
  } cellmap (* apply to each cell, then collect the results in an array *)
} @:a2
(1 (2 3) (4 4 (5 2) 1)) a2 out

```

Test case:

```
(1 (2 3) (4 4 (5 2) 1))    (* arg on TOS *)
{e d:e$wrap d 1-*}cellmap
out                        (* display TOS *)

```

Output without newlines:

```
(1 (2) (3) (4) (4) ((5)) ((2)) (1))

```

# Answer
> 1 votes
# Pyth - 29 bytes

```
.b]FYt-F/LN`[)PsM._:`Q"\d"3.n

```

Test Suite.

# Answer
> 1 votes
# Perl 6, ~~60~~ 47 bytes

```
sub f{[$_~~List??|([$_] for .&f)!!$_ for |$^a]}

```

(Try it online.)

### Explanation:

1. `[... for |$^a]`: Iterate over the input array, and construct a new array from it.
2. `$_ ~~ List ?? ... !! ...`: For each element, check if it is itself an array.
3. `|([$_] for .&f)`: If the element is an array, recursively apply the function to it, iterate over the elements of the new array returned from that recursive call, wrap each element in an array of its own, and slip them into the outer list.
4. `$_`: If the element is not an array, pass it on as-is.

# Answer
> 1 votes
## Haskell, 71 bytes

```
data L=N Int|C[L]
d#C l=((C .pure.d)#)=<<l
d#n=[d n]
f(C l)=C$(id#)=<<l

```

Again I have to define my own list type, because Haskell's natives lists can't be arbitrarily nested. This new type `L` can be returned from a function but not be printed by default, so in order to see a result I define a `show` instance for `L`:

```
instance Show L where
  show (N n)=show n
  show (C l)=show l

```

Now we can do some test in the REPL:

```
*Main> f $ C[N 1, C[N 2, N 3], C[N 4, N 4, C[N 5, N 2], N 1]]
[1,[2],[3],[4],[4],[[5]],[[2]],[1]]

*Main> f $ C[C[N 6, C[C[N 7]]]]
[[6],[[[7]]]]

```

How it works: a simple recursion which passes the nesting level as a function of `C` constructors. We start with the identity function `id` and whenever there's a list (-\> pattern match `d#C l=`) we add a further layer of `C` (-\> `C .pure.d`) to the recursive call of `#` to all elements of the list. If we encounter a number, we simply apply the nesting-level-function `d` to the number.

# Answer
> 1 votes
# APL (Dyalog), 44 bytes\*

Anonymous tacit prefix function. Takes nested APL list as argument and returns a nested APL array.

```
∊{⊃⊂⍣⍵,⍺}¨{⊃¨(j∊⎕D)⊆+\-⌿'[]'∘.=j←⎕JSON⍵}

```

Try it online!

`{``}` apply the following explicit function where the argument is represented by :

`⎕JSON⍵` convert the argument to JSON

`j←` store in `j`

`'[]'∘.=` table where `j` equals open (top row) and close (bottom row) brackets

`-⌿` top row minus bottom row (vertical difference reduction)

`+\` cumulative sum (this gives the nesting level for each character)

`(``)⊆` partition, beginning a new partition whenever a 1 is not preceded by a 1 in…

`j∊⎕D` where each character of `j` is a member of the set of **D**igits

`⊃¨` pick the first of each (this gives nesting level per multi-digit number)

`∊{` apply the following function to each nesting level (), using the corresponding element from the **ϵ**nlisted (flattened) argument as left argument ():

`,⍺` ravel (listify) the number (because scalars cannot be enclosed)

`⊂⍣⍵` enclose  times

disclose (because the innermost list is itself an enclosure)

---

* Using Dyalog Classic with `⎕ML←3` (default on many systems), substituting  for  and  for . Tio!

# Answer
> 1 votes
# Jelly, ~~12~~ 10 bytes

```
FWṛ¡"ŒJẈ’Ɗ

```

Try it online!

## How it works

```
FWṛ¡"ŒJẈ’Ɗ - Main link. Takes a list l on the left
F          - Flatten l
         Ɗ - Group the three previous commands over l:
     ŒJ    -   Multidimensional indices of l
       Ẉ   -   Get the length of each
        ’  -   Decrement
           - This gets the depth of each element in l
    "      - Zip together l and the depths, d
   ¡       - Do the following...
  ṛ        -   d times:
 W         -     Wrap the element of l

```

# Answer
> 1 votes
# , 23 bytes

```
([:;^:(1<L.)<"+L:0)^:L.

```

Try it online!

Since J requires boxing for ragged arrays, we use boxing level for array nesting level. Thus for example:

```
Original:
┌─────┐
│┌───┐│
││1 2││
│└───┘│
└─────┘
Transformed:
┌───┬───┐
│┌─┐│┌─┐│
││1│││2││
│└─┘│└─┘│
└───┴───┘

Original:
┌─┬───────┐
│3│┌─┬───┐│
│ ││3│┌─┐││
│ ││ ││3│││
│ ││ │└─┘││
│ │└─┴───┘│
└─┴───────┘
Transformed:
┌─┬───┬─────┐
│3│┌─┐│┌───┐│
│ ││3│││┌─┐││
│ │└─┘│││3│││
│ │   ││└─┘││
│ │   │└───┘│
└─┴───┴─────┘

```

# Answer
> 1 votes
# Vyxal, 11 bytes

```
f?⁽L€f‹¨£(w

```

Try it Online!

```
       ¨£   # Zip
f           # Input flattened
  ⁽L€       # Replace elements with depths
 ?          # in input
     f‹     # Flatten and decrement
       ¨£   # Zipwith...
         (w # Repeatedly wrap

```

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


title: Play a dumb coinflip game

text:
# Question
Title: Play a dumb coinflip game
Write an interactive program or function which allows the user to play The Coinflip Game! The object of the game is to repeatedly flip a coin until you get the same result \\$n\\$ times in a row.

Specific behavior of the program/function is as follows:

* At the start of the game, the user inputs a positive integer \\$n\>1\\$
* The program should then "flip a coin" (i.e. choose between two values randomly), and show the result to the user. Possible outcomes can be any two distinct outputs (e.g. 1 or 0) and must be chosen non deterministically such that each result always has a nonzero chance of appearing.
* Next, the following loop occurs
    1. Prompt the user to input whether they wish to continue trying or quit. This prompt must include the two input options the player has, one corresponding to continuing, and one corresponding to quitting, clearly delimited. If they choose to quit, take no further input and exit the program.
    2. If they choose to continue, perform another "coinflip", and show the user the outcome (same rules as before).
    3. If the "coinflip" has had the same outcome \\$n\\$ times in a row (meaning this outcome and the previous \\$n-1\\$ outcomes are all equal), print a congratulatory message (any message that is not one of the coinflip values or continue/quit prompts) and exit, taking no more input.
    4. If the "coinflip" has not had the same outcome \\$n\\$ times in a row yet, return to step 1 of the loop.

This is , so shortest implementation in bytes wins.

## More rule clarifications:

* Steps must occur in the order shown, so you can't prompt the user to continue before showing them their first coinflip result for example.
* All six values listed below must be distinct from one another:
    + Coinflip outcome 1
    + Coinflip outcome 2
    + Continue/Quit prompt
    + Continue playing input
    + Quit game input
    + Congratulatory message
* The coinflip only needs to be nondeterministic; You don't need the randomness to be uniform per flip.
* There can only be two possible outcomes for each coinflip. A random float between 0 and 1 is not a coinflip.
* Player input can be taken in any reasonable fashion.
* You can assume the player will never give invalid input.

# Answer
> 7 votes
# Python 3.8 (pre-release), 101 bytes

```
from random import*
p=m=n=int(input())
while'0'<input((m:=[n,m,print(r:=random()>.5)][r==p]-1)/m):p=r

```

Try it online!

* Coin flip outcome 1: `True`
* Coin flip outcome 2: `False`
* Continue/Quit prompt: `1.0`
* Continue playing input: `1`
* Quit game input: `0`
* Congratulatory message: `ZeroDivisionError: division by zero`

# Answer
> 3 votes
# Pyth, 31 bytes

```
KUJ"C/Q"We,aK
O2t{>QKJIqweJB.?N

```

Try it online!

Coinflip outcomes are "0" or "1"
Continue/Quit prompt is "C/Q"
Continue playing input is "C"
Quit playing input is "Q"
If you win, you receive a congratulatory "

# Answer
> 3 votes
# Bash, 82 75 bytes

```
read n
while read;do
echo $[x=RANDOM%2,t*=x==l,l=x]
let n==++t&&exit 2
done

```

Try it online!

* prompts for `n`
* prompts to continue or quit: "enter" continues and "ctrl-D" quits with exit code 1
* prints 0 or 1 randomly if you continued
* quits with exit code 2 if you won. continues loop otherwise.
    + Works by resetting the total count `t` every time there is a switch in direction.

# Answer
> 3 votes
# Python, ~~129~~ ~~131~~ ~~127~~ 106 bytes

```
i,p,a=input,print,1
p(v:=id(n:=int(i()))%3%2)
while"3">i(2.3):p(c:=id(dict())%3%2);a,v=c^v or-~a,c;1/(n>a)

```

Attempt This Online!

The coin flips are `0` and `1`, continue with `2` and quit with `3`, and the success message is an error message.

---

+2 bytes from @Steffan
-11 bytes from @Jonathan Allan*

# Answer
> 3 votes
# 05AB1E, ~~23~~ ~~22~~ ~~19~~ 17 bytes

```
[₂Ω=ˆ1z¯γθg¹Q+=Ê#

```

-4 bytes thanks to *@CommandMaster*.

* Coin flip outcomes: `2` and `6`
* Continue/Quit prompt: `1.0`
* Continue playing input: `1`
* Quit game input: `0`
* Congratulations message: `2.0`

Try it online.

**Explanation:**

```
[            # Start an infinite loop:
 ₂           #  Push 26
  Ω          #  Pop and push a random digit from it
   =         #  Output it with trailing newline (without popping)
    ˆ        #  Pop and add it to the global_array
 1z          #  Push 1.0 (push 1; calculate 1/value)
 ¯           #  Push the global_array
  γ          #  Group it to equal adjacent values
   θ         #  Pop and leave just the last group
    g        #  Pop and get the length of this last group
     ¹Q      #  Check if it's equal to the first input `n` (1 if truthy; 0 if falsey)
       +     #  Add that to the 1.0
        =    #  Output it with trailing newline (without popping)
 Ê           #  If it's NOT equal to the next (implicit) input-integer:
  #          #   Stop the infinite loop

```

Regarding the `Ê#`:

* If we haven't got \\$n\\$ the same values in a row yet, the value we output is still `1.0`. The `Ê` will be falsey if the prompt input is to continue (`1`), and will be truthy if the prompt input is to quit (`0`).
* If we have reached \\$n\\$ the same values in a row, the value we output is the congratulations message `2.0`. The `Ê` will now be truthy, regardless of whether the prompt input is to continue (`1`) or quit (`0`).

# Answer
> 2 votes
## (Browser) JavaScript, 122 bytes

```
a=prompt,k=0,s=0;for(g=+a();;k++){c=!Math.random();a(c);if(c!=s){s^=1;k=0}else if(g-1==k){a`!`;break}if(a`q|g`=="q")break}
```

If you're wondering why `if(Math.random())` works, yes: it can return 0 (but *not often*).

Hey, there *is* a nonzero chance of 0 popping up...

# Answer
> 1 votes
# Python, 141 bytes

```
from random import*
n=int(input());a=[.5]
while 1:
 print(f:=random()>.5);a+=f,
 if 0==sum(a[-n:])%n:print(2);break
 if'C'<input('C/Q'):break
```

Attempt This Online!

Coinflip outcomes are `False` and `True`, prompt is `C/Q`, where `C` = continue and `Q` = quit.

-14 bytes thanks to CursorCoercer

# Answer
> 1 votes
## Batch, 107 bytes

```
@set/al=c=0
:c
@set/af=%random%%%2,c=1+c*!(l-f),l=f
@echo %f%
@if %c%==%1 goto w
@set/pi=cq
@goto %i%

```

Takes `n` as a command-line parameter. Outputs `0` or `1` for the coin. Prompt is `cq`, input is `c` to continue, `q` to quit. Stops with the message `The system cannot find the batch label specified - w` if you win. Explanation: `c` is the count of consecutive equal flips, `l` is the last flip, `f` is the current flip, `i` is the user input (note that outside `set/a` variables have to be enclosed in `%`s and even inside `set/a` in the case of `%random%`).

# Answer
> 1 votes
# simply, ~~260~~ ~~254~~ 244 bytes

Yeah, the code is a big fat boy.
It is also *far* from the intended way to use the language.

---

## Values

The program has the following values:

* Coinflip outcome 1: `0`
* Coinflip outcome 2: `1`
* Continue/Quit prompt: `window.confirm`
* Continue playing input: `true`
* Quit game input: `false`
* Congratulatory message: `'W'`

---

## The code

Thanks to Steffan for saving 3 bytes.

```
$F=run$argv->map->constructor("return self")$W=run$F()$T=&int(run$W->prompt)$L=&rand(0,1)$C=1for$i in0..9999{$R=run$W->confirm($L)unless$R;break$F=&rand(0,1)if run&compare($L$F){$L=$F$C=1}else{$C=&add(1$C)unless run&compare($C$T){out'W'break}}}

```

Unfortunately, my language doesn't have infinite loops, yet...
However, this loops 10000 times, which should be enough to get the user to stop or give you a win.

It is possible to emulate this with `setTimeout`, but the program flow will be extremely weird, and cost a ton of bytes.

Additionally, the result of the last coin flip is shown in the message requesting to continue or stop, to save bytes.

### Ungolfed and readable

```
$func = call $argv["map"]["constructor"]("return self");
%window = call $func();

%times = &int(call %window->prompt("How many equals"));
%last_flip = &rand(0, 1);
%count = 1;

for $i in 0..9999 {
    $result = call %window->confirm(&str_concat("Rolled ", %last_flip, ' ', %count, " time(s). Continue?"));

    unless $result {
        break;
    }

    $flip = &rand(0, 1);
    if call &compare(%last_flip, $flip) {
        %last_flip = $flip;
        %count = 1;
    } else {
        %count = &add(1, %count);

        unless call &compare(%count, %times) {
            echo "You're Winner!";
            break;
        }
    }
}

```

### Ungolfed to Plain English

```
Set $func to the result of calling $argv["map"]["constructor"]("return self").
Set %window to the result of calling $func().

Set %times to the result of calling &int(
    Call the function %window->prompt("How many equals")
).

Set %last_flip to the result of calling &rand(0, 1).
Set %count to 1.

Loop from 0 to 9999 as $i
Begin
    Set $result to the result of calling %window->confirm(
        Call the function &str_concat("Rolled ", %last_flip, ' ', %count, " time(s). Continue?")
    ).

    Unless $result then
        Break.

    Set $flip to the result of calling &rand(0, 1).

    If Call &compare(%last_flip, $flip)
    Begin
        Set %last_flip to $flip.
        Set %count to 1.
    End
    Else
    Begin
        Set %count to the result of calling &add(1, %count);

        Unless Call &compare(%count, %times)
        Begin
            Show the value "You're Winner!".
            Break.
        End
    End
End

```

All versions work exactly the same, but the output is kinda different, just to be more user friendly.

## Explanation

The variable `$argv` is an array with arguments passed to the `.execute()` method of the compiler.
This can be used to run `[]["filter"]["constructor"]("return this")()`, which returns the `window` object (Source in http://www.jsfuck.com/).
But since the compiler changes the `this` value, I had to use `self`, which is the same as `window.self` which is just the window object.
Since `[]["filter"]...` is invalid syntax, I get around it by using `$argv->filer ...` (`$argv["filter"]...` is valid as well).

The keyword `run` (or `call`) is required to say "I am absolutely sure this variable is a function, now run it".
Due to bugs, the `if` and `unless` requires that the functions are executed with `run`, otherwise it assumes it is checking if the function exist.

The syntax `$T=&int(run$W->prompt)` is valid, because you don't need to have parenthesis when there's no arguments.

You will find a few cases where the syntax makes no sense, like `$C=1for$i in0..9999` or `$C=&add(1$C)unless`.
As long as the tokens are distinguishable from each other, there's no problem.
`$C=1for$i in0..9999` will be parsed as the following tokens: `$c`, `=`, `1`, `for`, `$i`, `in`, `0`, `..`, `9999`.

Since, currently, there's no boolean operators, I use the `unless` block.
It is basically an `if(!(condition))`.
Since I need to check if values are false-y, for example: `unless$R;break`, I use this block.

The function `&compare` checks if the first argument is lower, higher or equal to the second argument.
If it is lower, returns -1.
If it is higher, returns 1.
Otherwise, returns 0 (a false-y value).

`$W->prompt` (`window.prompt`) shows a message requesting a value.
`$W->confirm` (`window.confirm`) shows a message and requests the user to click "OK" or "Cancel".

```
console.log(window.prompt("Write any value", "any value"));

console.log(window.confirm("Want to show 'true'?"));
```

# Answer
> 0 votes
# JavaScript (browser), 105 bytes

```
p=prompt,r=()=>Math.random()<.5,t=p();c=b=1;for(u=r();b;b=c==t?p(3):+p`1.0`){n=r();p(n);n==u?c++:c=1,u=n}
```
* Coin flip outcome 1: `true`
* Coin flip outcome 2: `false`
* Continue/Quit prompt: `1.0`
* Continue playing input: `1`
* Quit game input: `0`
* Congratulatory message: `3`

---
Tags: code-golf, interactive
---


# Question
Title: Need some feedback with PHP+C polyglot code and class/struct properties
If you consider the following PHP+C polyglot snippet, there is a problem regarding class property access in the printf call:

```
#include <stdio.h>
#include <stdlib.h>
#define class struct
#define function

class Point {
#define public int
    public $x;
    public $y;
};

int
function main()
{
    struct Point*
    $p = alloca(sizeof(struct Point));
    printf("%d", $p->x);  // PHP expects $p->x, but C expects $p->$x
    return 0;
}

```

My question is, how to resolve this in a neat manner? Possible solutions:

1. Remove all `$` via sed before compiling with gcc
2. Define `public $x` as `int x` using `#if __PHP__`
3. Edit: Use getters, maybe? (works in C by passing self as first argument with function pointers)

Trying to define dollar sign as empty space does not work:

```
#define $

```

Any other ideas? I am also considering using m4 in the C Makefile. Thank you. :)

# Answer
> 5 votes
You can add `#define x $x` with the other `#define`s at the top. Now `$p->x` should also work in C.

---
Tags: tips, polyglot, c, php
---