title: Cat, Quine, Hello World

text:
# Question
Title: Cat, Quine, Hello World
Write a cat program, a quine, and a Hello World in the same language such that when two specific programs of the three are concatenated in a certain order, you get the third program. It does not matter which program is the first, second, and third are as long as all three types are represented once each.

e.g. if \\$A\\$ is a cat and \\$B\\$ is a quine then \\$AB\\$ is Hello World. Alternatively, if \\$A\\$ is Hello World and \\$B\\$ is a cat then \\$AB\\$ is a quine. You only need to make *one permutation* of the possible 6 work.

For completeness of explanation:

* A cat program outputs the input exactly
* A quine is a program that outputs its own source code
* A hello world program outputs the string "Hello World!"

## Rules, Scoring, Formatting

* Shortest code wins. Scoring goes by the length of the concatenated program, i.e. the longest of the three.
* Standard rules and loopholes apply.
* The hello world program and quine might possibly receive input. You must output the appropriate text regardless of what is given as input.
* Programs may output a trailing newline.
* You can treat all three programs as if they are surrounded by your language's function closure (please specify the name of your implicit argument in this case) or `main` function boilerplate if that is required for your solution to work. Use the same convention for all three programs. The quine should not contain the boilerplate in this case.

Format the header of your answer like this:

> \<first type\> + \<second type\> = \<third type\>, \<language\>, \<score\>

or

> \<language\>, \<first type\> + \<second type\> = \<third type\>, \<score\>

# Answer
# Python 3, Hello World + Quine = Cat, 129 bytes

### Hello World:

```
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
 p(input())
 os._exit(0)

```

### Quine:

```
s='s=%r;print(s%%s)';print(s%s)

```

### Cat:

```
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
 p(input())
 os._exit(0)
s='s=%r;print(s%%s)';print(s%s)

```

`atexit` lets you define cleanup steps that will run when your program exits "normally". In this case, I register the `print` function (renamed `p`) with the argument `"Hello World!"`, so it will print that string when the program ends.

I then redefine `print` to become a `cat` function. Normally, this would cause the program to print its input *and* "Hello World!", but `os._exit()` is an "abnormal" exit that bypasses the cleanup steps.

Now that `print` has been redefined, the Quine simply calls this `cat` function and the program abruptly exits. If the Quine doesn't exist, then the program exits normally, printing "Hello World!" in the process.

The final program doesn't work on TIO, but it works for me running Python 3.7.3 on MacOS.
> 23 votes

# Answer
# Bash, Quine + Cat = Hello World, 110 bytes

## Quine

```
q='eval printf "$s" "$s"';s='q=\47eval printf "$s" "$s"\47;s=\47%s\47;$q';$q

```

## Cat

```
true false&&cat||echo Hello World!

```

## Hello World

```
q='eval printf "$s" "$s"';s='q=\47eval printf "$s" "$s"\47;s=\47%s\47;$q';$qtrue false&&cat||echo Hello World!

```

This takes advantage of the fact that undefined variables expand to the empty string and that `true` is a command that can take arguments.

You can trivially swap the cat and the hello world by swapping `true` and `false`
> 12 votes

# Answer
# , Quine + hello, world = cat; ~~48 + 49~~ ... 43 + 44 = 87 bytes

Or **75 bytes** as internal code of functions and not including `function(){}` wrappers.

*Edit: -14 bytes thanks to Robin Ryder!*

Nontrivial quine:

```
'->T;cat(sQuote(T),T)' ->T;cat(sQuote(T),T)

```

Try it online!

Hello,world:

```
~F->y;cat(`if`(T>0,"Hello world!",scan(,T)))

```

Try it online!

Cat:

```
'->T;cat(sQuote(T),T)' ->T;cat(sQuote(T),T)~F->y;cat(`if`(T>0,"Hello world!",scan(,T)))

```

Try it online!

A 'trivial quine' version could be Quine = `~1`, and Hello, world = `+F->y;cat(`if`(y<0,scan(,''),'Hello world!'))`, for **2+45=47 bytes**.

**How? (nontrivial & trivial versions)**

The default behaviour of  is to output any unassigned values (such as variables or expressions). So, to print a quine, we simply need to generate an expression containing the program code, and it is output by default (this applies both to the nontrivial quine, which is contructed using `cat` to join the various text elements together, as well as the trivial quine `~1` consisting simply of a formula which is outputted)

If a value is assigned to a variable, it is not output. So to stop the quines from printing, we incorporate them into an expression and assign this to the variable `y`.

To do this, we need to use a binary operator, but since this operator will also appear at the start of the 'Hello, world' program, it must also function as a unary operator. Both the `~` (formula) and `+` (positive/sum) operators have this property.

Conveniently,  also includes a (little used outside coding challenges) left-to-right assignment operator, `->`, which - together with a unary/binary operator - lets us package the quine into the variable `y` & forget about it. Then all we need to do is to determine whether this has happened or not, and use this to switch between 'Hello, world' and 'cat' behaviour.
> 11 votes

# Answer
# Quine + Cat = Hello World, Jelly, 25 bytes

*-2 bytes thanks to @Jonathan Allan*

### Quine (12 bytes)

```

“Ṿṭ⁷;⁾v`”v`

```

(starts with a newline)

Try it online!

### Cat (13 bytes)

```
Ṇ
“,ḷṅḳȦ»³ÑƑ?

```

Try it online! (argument quoted to avoid casting to a Python object from string as per @Jonathan Allan's suggestion)

### Hello World (25 bytes)

```

“Ṿṭ⁷;⁾v`”v`Ṇ
“,ḷṅḳȦ»³ÑƑ?

```

(starts with a newline)

Try it online!

## How it Works

In Jelly, the last link (last line) is always executed as the main link. The Cat and Hello World have the same last link, so they are differentiated by the value of the first link (blank (identity) or  (logical not)).

```
“,ḷṅḳȦ»³ÑƑ?
          ?  # If
        ÑƑ   # The first link is the identity
“,ḷṅḳȦ»        # Return "Hello World!" (String Compressor: https://codegolf.stackexchange.com/a/151721/68261)
             # Else
       ³       # Return the input

```

The quine is slightly difficult because it needs to prepend a blank line.

```
“Ṿṭ⁷;⁾v`”v`
“Ṿṭ⁷;⁾v`”     # Set the string "Ṿṭ⁷;⁾v`"
         v`   # Eval it on itself:
 Ṿṭ⁷;⁾v`
 Ṿ              # Uneval: "“Ṿṭ⁷;⁾v`”"
  ṭ⁷            # Prepend a newline "¶“Ṿṭ⁷;⁾v`”"
    ;⁾v`        # Concatenate "v`" to get "¶“Ṿṭ⁷;⁾v`”v`"

```
> 8 votes

# Answer
# Wolfram Language (Mathematica), Quine + Cat = Hello World, ~~15+28=43~~ 15 + 22 = 37 bytes

3 functions.

### Quine

```
ToString[#0] &

```

Try it online!

### Cat

```
#/.#_:>"Hello World!"&

```

Try it online!

### Hello World

```
ToString[#0] & #/.#_:>"Hello World!"&

```

Try it online!

---

### ~~HW+Q=C,46+58=104 Q+C=HW,43+48=91~~ Cat + Quine = Hello World, 49 + 37 = 86 bytes

**Cat**

```
Print[#/._@_->"Hello World!"]&@$ScriptInputString

```

Try it online!

**Quine**

```
Print[ToString[#0, InputForm][]] & []

```

Try it online!

**Hello World**

```
Print[#/._@_->"Hello World!"]&@$ScriptInputStringPrint[ToString[#0, InputForm][]] & []

```

Try it online!
> 8 votes

# Answer
# Rust, Quine + Cat = Hello, world! (106 + 2 = 108 bytes)

### Quine (~~108~~ 106 bytes):

-2 bytes: removed ',' from "Hello world!"

```
let s=format!("Hello world!");format!("{},{0:?})","let s=format!(\"Hello world!\");format!(\"{},{0:?})\"")

```

`.into()` instead of `format!` saves a few bytes but is context-dependent.

### Cat (2 bytes):

```
;s

```

### Quine + Cat = Hello, world! (~~110~~ 108 bytes):

```
let s=format!("Hello world!");format!("{},{0:?})","let s=format!(\"Hello world!\");format!(\"{},{0:?})\"");s

```

Try it!

Updated to not use `include_str!`. Hopefully this doesn't break any rules anymore.

This relies on it being in a closure/function that implements `Fn(String) -> String` with argument `s`.

---

Old answer, uses `include_str!`:

### Quine (67 bytes):

```
match include_str!("f"){p@_ if p.len()==67=>p,_=>"Hello, world!"}//

```

(Not very creative, unfortunately)

### Cat (1 byte):

```
s

```

### Quine + Cat = Hello, world! (68 bytes):

```
match include_str!("f"){p@_ if p.len()==67=>p,_=>"Hello, world!"}//s

```

~~Try it! (Repl.it link due to multiple files)~~

This depends on the code being in its own file named "f" and being `include!`'d into main.rs before being executed. The Repl.it link has the programs in separate files with different names, which means that the quine and hello world programs are different by one character so that they include the correct string.

~~This challenge was especially difficult in Rust (without using a comment at the end of one of the programs) because of the syntax of the language. Functions and multi-statement closures have braces surrounding them, so you can't just concat two closures to get a third, unfortunately.~~
> 7 votes

# Answer
# Python 2, Hello World + Cat = Quine, 200 198 189 bytes

## Hello World

```
id=0;a="Hello World!";a0='id=0;a="%s";a0=%r;print a0%%((a,a0)if id<1else 1)\nimport sys\nif id:print sys.stdin.read()';print a

```

## Cat

```
0%((a,a0)if id<1else 1)
import sys
if id:print sys.stdin.read()

```

My previous answer was actually wrong. `raw_input` only reads one line. This reads the entire input.

## Quine

```
id=0;a="Hello World!";a0='id=0;a="%s";a0=%r;print a0%%((a,a0)if id<1else 1)\nimport sys\nif id:print sys.stdin.read()';print a0%((a,a0)if id<1else 1)
import sys
if id:print sys.stdin.read()

```

Try it online!

---

*2020-08-05: -42 bytes thanks to Jonathan Allen, +33 to fix a bug*
> 7 votes

# Answer
# Keg, Hello World + Quine = Cat, 26 bytes

```
«H%c¡|,!«``:[④|᠀,]`:[④|᠀,]

```

Try it online!

## How it Works

### Hello World

```
«H%c¡|,!«`

```

Try it online!

This is my answer to the HW challenge with some additional string closing syntax. Why? Because a) the main string needs closing to be concatenated and b) the end \`\`\` is needed to "ignore" the quine part

### Quine (non-trivial)

```
`:[④|᠀,]`:[④|᠀,]

```

Try it online!

```
`:[④|᠀,]`

```

Push the string `:[④|᠀,]` to the stack

```
:[④|᠀,]

```

Duplicate the string and start an if-block. The if block uses the truthiness of the t.o.s to determine which branch is to be executed. In this case, the string is truthy, so the  is executed (printing the string raw). Implicit output then prints the string nicely.

### Concatenation

```
«H%c¡|,!«``

```

Push the string `Hello, World!` followed by an empty string onto the stack.

```
:[④|᠀,]

```

Duplicate the top of the stack (an empty string) and start the if block. Empty strings are considered falsey, so the `᠀,` branch is executed. This takes input and prints it.

```
`:[④|᠀,]

```

Push the string `:[④|᠀,]` and don't do anything with it.
> 7 votes

# Answer
# Python 3.8, Cat + Quine = Hello, ~~101 91~~ 89 bytes

## Cat (32 bytes)

```
a=id=""
while 1:a=input(a)+"\n";

```

Try it online!

## Quine (57 bytes)

```
exec(s:='+input(id and"exec(s:=%r)"%s or"Hello World!")')

```

Try it online!

## Hello World (89 bytes)

```
a=id=""
while 1:a=input(a)+"\n";exec(s:='+input(id and"exec(s:=%r)"%s or"Hello World!")')

```

Try it online!

## How it works:

For the cat program:

* `a=id=0` we assign `a` and `id` to the empty string. `id` is now evaluated as `False` (remember it for later)
* At the first loop of `while 1`: `a=input(a)+"\n"` will display `a` without a new line (so the empty string) and store in `a` the first line of the input plus a newline
* Then we loop again, displaying the input of the previous iteration until the program has written all the lines of the input and crash (`EOFError`)

For the quine program:

* The main structure of the quine is `exec(s:='print("exec(s:=%r)"%s)')`, a well known quine in python.
* We uses `input()` instead of `print()` to avoid the trailing new line
* the `+` at the start is here to make the program crash as soon as it finished printing to make sure the program ends.
* `id` is a python built-in. Because of that it is evaluated as `True` so `id and <code 1> or <code2>` will be equal to `<code 1>` (which contains the code for our quine to work).

For the hello world program:

* remember the cat program where we assigned `id` to the empty string?
* `id and <code 1> or <code2>` will now execute `<code2>` since `id` is now evaluated as `False`, resulting the printing of `Hello World!`
* The `+` crashes the program avoiding looping in the cat code again

## Old solution: cat (37) + quine (64) = hello (101 bytes)

Here is my old solution using triple quoted string and comments to "squeeze" the quine part and directly printing `"Hello World!"`. It uses some cool tricks with comments:

```
while p:=print:id or p(input());id=""									# cat (37 bytes)
                                     "";exec(s:='input(\'"";exec(s:=%r)\'%s)#"""-p("Hello World!")#')	# quine (64 bytes)
while p:=print:id or p(input());id="""";exec(s:='input(\'"";exec(s:=%r)\'%s)#"""-p("Hello World!")#')	# hello (101 bytes)

```

Try it online!

Who said that comments were not usefull in codegolfing?
> 6 votes

# Answer
# , Quine (~~74~~ 51 bytes) + Cat (~~77~~ 74 bytes) = Hello world ~~151~~ 125 bytes

# , Hello world (~~173~~ 174 bytes) + Cat (~~77~~ 74 bytes) = Quine ~~250~~ 248 bytes

# , Quine (~~74~~ 51 bytes) + Hello world (~~173~~ 174 bytes) = Cat ~~247~~ 225 bytes

**A set of Quine, Cat & Hello world from which any 2 can be combined to form the third.**

Not the shortest answer, but pleasingly symmetric.

**Quine (~~74~~ 51 bytes)**

```
'->F;T=0;cat(sQuote(F),F)' ->F;T=0;cat(sQuote(F),F)

```

Try it online!

**Cat (~~77~~ 74 bytes)**

```
~1->y;cat(`if`(T>1,sprintf(T,sQuote(T)),`if`(T,scan(,""),"Hello world!")))

```

Try it online!

**Hello world (~~173~~ 174 bytes)**

```
~1->y;T='~1->y;T=%s;cat(`if`(F<0,scan(,""),"Hello world!"))~1->y;cat(`if`(T>1,sprintf(T,sQuote(T)),`if`(T,scan(,""),"Hello world!")))';cat(`if`(F<0,scan(,""),"Hello world!"))

```

Try it online!
> 5 votes

# Answer
# Aceto, quine (67) + cat (33) = Hello World (100 bytes\*)

(\*I counted one file including a final newline so that catting them together works as expected)

### quine (made it for this challenge):

```
£"24«cs%55«3+cp24«2+cdpsdpsppn"24«cs%55«3+cp24«2+cdpsdpsppn

```

### cat:

```
X

n
p el
r"HlX
^^ oldnp
 ^Wor!"

```

---

The quine itself was the hardest part, due to the nature of having code on a Hilbert curve (The "Hello World", and cat programs are trivial compared to it). The solution of having the concatenated program do something else than the parts is simple in Aceto: Because the (longer-line) quine enforces a square size of an even power of two (64 = 2^6), and the cat program has, on its own, a square of size 8x8 (8 = 2^3, an odd power of two), the instruction pointer starts moving in a different direction.
> 4 votes

# Answer
# Alice, Cat + Quine = Hello World, 51 bytes

**Cat:** (With trailing newline)

```
\ >  "!dlroW olleH"d&O@
  ^/ v
  # < i

```

Try it online.

Uses # to skip the redirect west and instead hit the redirect south into the i, which pushes the input as a string to the top of the stack. The instruction pointer then reflects off the top and bottom boundaries of the grid, hitting the o and @ from the Hello World program, causing it to output the top of the stack as a string and then terminate. The code requires a trailing newline, which I couldn't get to display here in the code block.

**Quine:**

```
"!<@O&9h.

```

Try it online.

Just a standard Alice quine.

**Hello World:**

```
\ >  "!dlroW olleH"d&O@
  ^/ v
  # < i
"!<@O&9h.

```

Try it online.

The # is now used to skip the @ from the quine program, causing the instruction pointer to instead hit the redirect west, which passes through a mirror and hits two more redirects to hit a standard Alice Hello World program.
> 4 votes

# Answer
# Hello World + Quine = Cat, C (GCC), 149 (81 + 68)

### Hello World

```
a;main(s){a?read(0,&s,1)&&main(putchar(s)):puts("Hello World!");}
#define main m

```

Try it online!

### Quine

```
a=1;main(s){printf(s="a=1;main(s){printf(s=%c%s%1$c,34,s);}",34,s);}

```

Try it online!

### Cat (Hello World + Quine)

```
a;main(s){a?read(0,&s,1)&&main(putchar(s)):puts("Hello World!");}
#define main m
a=1;main(s){printf(s="a=1;main(s){printf(s=%c%s%1$c,34,s);}",34,s);}

```

Try it online!
> 4 votes

# Answer
# \>\<\>, Quine + Cat = Hello World!, 48 bytes

**Quine**

`"r00gol?!;40.`

The classic \>\<\> quine

**Cat**

```
"]v"i:0(?;o
>l?!;o
^"Hello World!"<

```

A simple cat program, loaded with some other code that isn't being run.

**Hello World!**

```
"r00gol?!;40."]v"i:0(?;o
>l?!;o
^"Hello World!"<

```

The quine part makes the instruction pointer stop interpreting "\]v" as text, instead clearing the stack and moving down to the "Hello World!" printer.

---

Equivalently, the program can be written as

```
'rd3*ol?!;40.']v'i:0(?;o
>l?!;o
^"Hello World!"<

```

Which, as Jo King points out, avoids using the `g` code reflection instruction, arguably making the quine more genuine.
> 4 votes

# Answer
# 05AB1E, Quine + Hello World = Cat, 23 bytes

**Quine:**

```
2096239D20BJ

```

Try it online (with input) or try it online (without input).

**Hello World:**

```
I.gi”Ÿ™‚ï!

```

Try it online (with input) or try it online (without input).

**Cat:**

```
2096239D20BJI.gi”Ÿ™‚ï!

```

Try it online (with input) or try it online (without input).

(All three output with trailing newline.)

**Explanation:**

```
2096239       # Push integer 2096239
       D      # Duplicate it
        20B   # Convert it to base-20 as list: "D20BJ"
           J  # Join stack together: "2096239D20BJ"
              # (after which it is output implicitly as result)

I             # Push the input (or an empty string if none is given)
 .g           # Get the amount of items on the stack (which will be 1)
   i          # If this amount is 1 (which it always is):
    ”Ÿ™‚ï!    #  Push dictionary string "Hello World!"
              #  (after which it is output implicitly as result)

2096239D20BJ  # Same as above
I             # Push the input (or an empty string if none is given)
 .g           # Get the amount of items on the stack: 2
   i          # If this amount is 1 (which it isn't):
    ”Ÿ™‚ï!    #  Push dictionary string "Hello World!"
              # (implicit else:)
              #  (implicitly output the input we pushed earlier as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”Ÿ™‚ï!` is `"Hello World!"`.
Credit of the quine goes to *@Grimmy*'s answer here.
> 3 votes

# Answer
# Jelly, Quine + Cat = Hello World! 17 bytes

Note that using a formatted input has been deemed valid and this entry takes input as a command-line argument formatted as a Python string. To have a pure-Cat program we'd need to use STDIN in Jelly, since it first attempts to evaluate any command-line argument as Python. This is achievable in 21 bytes with `”ṘṘ` \+ `”1$0¡ƈȮ¤L¿“,ḷṅḳȦ»Ṇ?` TIO.

```
”ṘṘ

```

**Quine**

```
1$0¡³“,ḷṅḳȦ»⁼?

```

**Cat**

```
”ṘṘ1$0¡³“,ḷṅḳȦ»⁼?0

```

**Hello World!**

### How?

The shortest proper quine in Jelly is:

```
”ṘṘ - Main Link: any arguments
”Ṙ  - an 'Ṙ' character
  Ṙ - print Jelly representation of x (i.e. ”Ṙ) and yield x ('Ṙ')
    - implicit print (i.e. Ṙ)

```

To use it we need to not let the  execute in the largest program.

One way to not execute a link is to follow it with  \- repeat zero times, but `¡` needs a link to repeat, like `X0¡`, so we make `X` equal `1$`.

`$` composes the preceding two links into a single monadic link and (slightly surprisingly) `1$` can start a full program, as a monad which yields \\$1\\$ but when repeated zero times it just yields whatever its left argument is.

As such starting a program which has one command-line argument with `1$0¡` applies `1$` zero times to that argument, i.e. is a no-op, giving the rest of the program that same left argument.

But when `1$0¡` is prefixed with `”ṘṘ` we have the `X` (described earlier) equal to `Ṙ1` which when applied zero times to `”Ṙ` yields the character `'Ṙ'`.

Since the character, `'Ṙ'`, is not equal to the right argument of the Main Link (which, when given a single command-line argument is that argument) since that is a *list* of characters, we can use equality, , to test, `?`, (effectively) whether the prefix `”ṘṘ` is present and either...

...Cat\* (if not):

```
³ - yield the programs 1st command-line argument

```

...or Hello World!:

```
“,ḷṅḳȦ» - compressed string = "Hello World!"

```

---

* The Cat code for the 21 byte STDIN version is:

```
ƈȮ¤L¿ - niladic link (no arguments)
    ¿ - do...
  ¤   - ...instruction: nilad followed by link(s) as a nilad
ƈ     -   read a character from STDIN
 Ȯ    -   print & yield
   L  - ...while?: length (0 at EOF)

```

and we use the monad logical-NOT, , as our test since we get an implicit left argument of `0` with no command-line arguments and by this point  gets an argument of `0` (`0Ṇ` = \\$1\\$ -\> Cat) or `'Ṙ'` (`”ṘṆ` = \\$0\\$ -\> Hello World!).
> 3 votes

# Answer
# Ruby, Cat + Quine = *Hello World!*, ~~100~~ ~~97~~ 96 bytes

Reading the source code is prohibited for quines but there is no such rule for *Hello World!* programs. We exploit this fact using Ruby's `DATA`/`__END__` mechanism. If `__END__` appears alone on any line in the code, execution terminates there. However, any further code is accessible via the constant `DATA`, which is initialised to a `File` object containing all of this non-executable 'data'.

### Cat

```
$><<(DATA||=$<).read;a

```

Try it online!

The idiomatic `||=` operator sets the value of the variable `DATA` only if it is not already defined. In this case, `DATA` is not defined because the program does not contain `__END__`. In effect, the first part of the code therefore reduces to `$><<$<.read`, where `$<` and `$>` point to STDIN and STDOUT, respectively. For later use, the final `a` (which is an undefined variable) throws an error, which is inconsequential here.

### Quine

```
eval$s=%q($><<"eval$s=%q(#$s)
__END__
Hello World!")
__END__
Hello World!

```

Try it online! or verify quine.

All of the real work is done in the first line, which is a basic Ruby quine template. With `__END__` now making an appearance, it shouldn't be too hard to see where this is going.

### *Hello World!*

```
$><<(DATA||=$<).read;a
eval$s=%q($><<"eval$s=%q(#$s)
__END__
Hello World!")
__END__
Hello World!

```

Try it online!

Finally we have `DATA` and `__END__` together. Unlike in the *cat* program, `DATA` is defined this time: it's a `File` object containing `Hello World!`. Once this has been printed, there is no further output because of the error thrown by the final `a` (undefined) in the first line.
> 3 votes

# Answer
# Python 3, Cat + Quine = Hello World, 121 bytes

* -2 bytes thanks to @Jo King

**Cat**:

Actual `cat` part is taken from the top comment of this SO answer.

If the file is long enough, switch to a Hello World program.

```
len(open(__file__).read())<99or~print('Hello World!')
import sys
print(sys.stdin.read())

```

The `~print` exits the program after printing: `print` returns `None` and `~None` throws. (Crashing to exit was allowed by OP in a comment.)

**Quine**:

Pretty standard. Originally wanted to use Python 3.8 `:=` to do `print((s:='print((s:=%r)%%s)')%s)`, but that was longer. Stole the use of `;` instead of `\n` from one of the other Python answers.

```
s='s=%r;print(s%%s)';print(s%s)

```

**Combined**:

```
len(open(__file__).read())<99or~print('Hello World!')
import sys
print(sys.stdin.read())
s='s=%r;print(s%%s)';print(s%s)

```
> 2 votes

# Answer
# Haskell, Cat + Quine = Hello World, 127 bytes

## Cat, 27 bytes

```
o=interact id
main=o where

```

Try it online!

## Quine, 100 bytes

```
o=putStr"Hello, world!";main=putStr$(++)<*>show$"o=putStr\"Hello, world!\";main=putStr$(++)<*>show$"

```

Try it online!

## Hello World

```
o=interact id
main=o where o=putStr"Hello, world!";main=putStr$(++)<*>show$"o=putStr\"Hello, world!\";main=putStr$(++)<*>show$"

```

Try it online!

## Explanation

The main trick in this answer is scoping. In the cat we have a simple program. We have a `main` which is just defined to be `o`, which is a cat program. At the end of the program there is a `where` which opens a new scope. This will make our entire quine program attached to the scope of the main program. Two things are solved by doing this.

* Since the quine program's `main` is not defined in the global scope we avoid the duplicate main declaration error.
* We can declare a version of `o` that overrides the one in the global scope. Our quine program declares `o` to be a hello world program.

The overall technique is very similar to Silvio Mayolo's answer, however improves upon it in two ways.

* Silvio Mayolo's answer declares a variable `c=1`, which is never used (I am not sure why this is done. Removing it doesn't break anything). This does not have this.
* I used a shorter quine technique. I took a glance at Silvio Mayolo's quine and I don't know how it works, but it is longer than mine.
> 2 votes

# Answer
# Python 2, Quine + Cat = Hello World, 86 bytes

### Quine (35 bytes)

```
id='id=%r;print id%%id';print id%id

```

### Cat (51 bytes)

```
+0*''and'Hello World!'
while''>id:print raw_input()

```

### Hello World (86 bytes)

```
id='id=%r;print id%%id';print id%id+0*''and'Hello World!'
while''>id:print raw_input()

```
> 2 votes

# Answer
# Pxem (esolang-box notation), Hello World: 48 bytes + Quine: 110 bytes = Cat: 158 bytes.

Unprintables are escaped.

## Hello World

```
.f!.zHello World.p.d.a.w.c.z.w.o.i.c\001.+.a.d.a.a

```

## Quine

```
!Be!?BzBc!!B+BzXXFBaBcFBzBsXXFBBaBsBtBvBmBvBcAcB-BaBsBp".e!?.z.c!!.+.zXXF.a.cF.z.sXXF..a.s.t.v.m.v.cAc.-.a.s.p

```

## Cat

```
.f!.zHello World.p.d.a.w.c.z.w.o.i.c\001.+.a.d.a.a
!Be!?BzBc!!B+BzXXFBaBcFBzBsXXFBBaBsBtBvBmBvBcAcB-BaBsBp".e!?.z.c!!.+.zXXF.a.cF.z.sXXF..a.s.t.v.m.v.cAc.-.a.s.p

```

## Try it online!

Use variable `mode` to switch programs.

## How it works

The Hello World program consists of several parts, as in:

```
# branch if content begins with '!' or not
.f!.z
  # Hello World program
  # Note that '!' is recycled here
  Hello World.p.d
.a
.w.c.z
  # Cat program
  # Note that content of stack is cleared before entrying here
  .w.o.i.c\001.+.a.d
.a.a\n

```

Quine is recycled from here.

Cat program uses this specification:

> The first line is the file name of the pxem code.
>
> The rest is the content of the pxem code.
> 2 votes

# Answer
# AWK, Cat + HW = Quine, 156 bytes

```
BEGIN{k=1}1;BEGIN{if(k){printf a="BEGIN{k=1}1;BEGIN{if(k){printf a=%c%s%c,34,a,34,34,34;exit}print%cHello World!%c}",34,a,34,34,34;exit}print"Hello World!"}

```

Try it online!

This is the overall algorithm:

```
BEGIN{k=1}1;
BEGIN{if(k){
    print"Quine";exit
    }
print"Hello, World!"
}

```

## Cat

```
BEGIN{k=1}1;

```

## Hello World

```
BEGIN{if(k){printf a="BEGIN{k=1}1;BEGIN{if(k){printf a=%c%s%c,34,a,34,34,34;exit}print%cHello World!%c}",34,a,34,34,34;exit}print"Hello World!"}

```
> 2 votes

# Answer
# V (vim), Quine + Hello World = Cat, 32 bytes

## Quine

```
dG2idG2i

```

Explanation:

* `dG`: Delete the buffer (saving it to the unnamed register)
* `2idG2i`: Insert `dG2i` twice.

## Hello World

```
"_dG4iHello World!
␛pH3D

```

With trailing newline. TryItOnline also shows a trailing space after that, but this appears to be an artifact of it's V runner.

Explanation:

* `"_dG`: Delete the buffer (without saving it to a register)
* `4iHello World!␊␛`: Write "Hello World!" 4 times
* `p`: Paste from the (empty) unnamed register
* `H3D`: Delete the first 3 lines of the buffer

## Cat

```
dG2idG2i"_dG4iHello World!
␛pH3D

```

Since all no-ops in V are automatically cat programs, the trick here is to make the combined program cancel out itself.

Explanation:

* `dG`: Delete the buffer (saving it to the unnamed register)
* `2idG2i"_dG4iHello World!␊␛`: Write `dG2i"_dG4iHello World!` twice (trailing newline)
* `p`: Paste from the unnamed register.
    + Since the motion used to delete was `G`, this pastes it onto the following line.
    + Therefore, the first two lines of the buffer are that crazy string, the third is an empty line, and the rest is the original buffer
* `H3D`: Delete the first 3 lines of the buffer

Try it online!
> 1 votes

# Answer
# Haskell, Cat + Quine = Hello World, 140 bytes

## Cat

```
b=interact id
main=b where c=1;

```

## Quine

```
main=putStr a>>print a;b=putStrLn "Hello world!";a="main=putStrLn a>>print a;b=putStrLn \"Hello world!\";a="

```

## Hello World!

```
b=interact id
main=b where c=1;main=putStr a>>print a;b=putStrLn "Hello world!";a="main=putStrLn a>>print a;b=putStrLn \"Hello world!\";a="

```

We exploit the rules of variable shadowing. The cat program simply calls the global `b`, defined as `interact id` (a standard cat in Haskell). We declare a variable `c` that's never used, simply so we can concatenate later. The quine is pretty standard; we define a variable `b` that we never use, but otherwise it simply prints its payload and exits.

Here's a version of "Hello world" with better spacing.

```
b = interact id
main = b
  where c=1
        main=putStr a>>print a
        b=putStrLn "Hello world!"
        a="main=putStrLn a>>print a;b=putStrLn \"Hello world!\";a="

```

`main` simply calls `b`, but this time is calls the locally-declared `b`, which prints "Hello world!". All of the other variables are unused.
> 1 votes

# Answer
# PHP, Hello World + Quine = Cat, 117 bytes

Because of the input method this only works using the command line.

## Hello world

the double die is because the php code has to get interupted earlier in order to prevent errors being printed (missing function a)

```
<?php if(!function_exists('a')){die('Hello world!');}die(a($argv));

```

## Quine

without opening tag, php just outputs whatever it contains

```
function a($b){unset($b[0]);echo implode(' ',$b);}

```

## Cat

Because function declations are passed first, the die() isn't called yet and therefor a() exists, and is called in order to print its arguments. The unset avoids the scriptname from being printed (which is not an input)

```
<?php if(!function_exists('a')){die('Hello world!');}die(a($argv));function a($b){unset($b[0]);echo implode(' ',$b);}

```

If only the first argument has to be printed, a shortcut can be used (101 bytes):

```
<?php if(!function_exists('a')){die('Hello world!');}die(a($argv));function a($b){unset($b[0]);echo implode(' ',$b);}

```

This however is not the full input and i consider this invalid
> 1 votes

# Answer
# Java 10+, Cat + Quine = Hello World, 384 (135 + 249) bytes

## Cat, 135 bytes

```
interface C{static void main(String[]a){System.out.println(Boolean.TRUE?new java.util.Scanner(System.in).nextLine():"Hello World");}}//

```

## Quine, 249 bytes

(note: TIO doesn't let me run the code unless I rename my interface from `Q` to `Main`, but just know that it's supposed to be named the former)

```
interface Q{static void main(String[]a){var s="interface Q{static void main(String[]a){var s=%c%s%c;System.out.printf(s,34,s,34,10);}}%cinterface Boolean{boolean TRUE=false;}";System.out.printf(s,34,s,34,10);}}
interface Boolean{boolean TRUE=false;}

```

## Hello World, 384 bytes

```
interface C{static void main(String[]a){System.out.println(Boolean.TRUE?new java.util.Scanner(System.in).nextLine():"Hello World");}}//interface Q{static void main(String[]a){var s="interface Q{static void main(String[]a){var s=%c%s%c;System.out.printf(s,34,s,34,10);}}%cinterface Boolean{boolean TRUE=false;}";System.out.printf(s,34,s,34,10);}}
interface Boolean{boolean TRUE=false;}

```

Again, the TIO link contains an interface called `Main`, but it's actually `C`, the cat program.

It redefines `Boolean.TRUE` to be `false` when the quine is concatenated to the cat.
> 1 votes

# Answer
# Klein 001, Quine + Cat = Hello World, 28 bytes

## Quine, 11 bytes

*This is Martin Ender's quine from here*

```
:?\:2+@> "

```

Try it online!

## Cat, 17 bytes

```
@ >"Hello world!"

```

Try it online!

## Hello World, 28 bytes

```
:?\:2+@> "
@ >"Hello world!"

```

Try it online!
> 1 votes

# Answer
# Japt, Quine + Cat = Hello World, 43 bytes

All of the complexity is jammed into making a quine that includes a variable that holds `Hello World!`. Cat simply outputs the default input and the Hello World merger reuses the variable from the quine.

## Quine, 41 bytes

```
"Hello World!"             // U = "Hello World!"
"iQ ²iRiQiUiQ"iQ ²iRiQiUiQ // A bunch of messy string manipulations to make this a quine

```

## Cat, 2 bytes

```

U // Output the default first input

```

## Hello World, 43 bytes

```
"Hello World!"             // U = "Hello World!"
"iQ ²iRiQiUiQ"iQ ²iRiQiUiQ // Throwaway line
U                          // Output U

```
> 1 votes

# Answer
# Vyxal, Cat + Quine = Hello, 16 bytes

## Hello world, 13 bytes

```
kh\!+□⁋`I^`I^

```

Try it Online!

## Cat, 7 bytes

```
kh\!+□⁋

```

Try it Online!qwhYOKWoeKBiyIsIiIsImFcbmJcbmNcbmRcbiJd)

## Quine, 6 bytes

```
`I^`I^

```

Try it Online!

## Explanation :

```
## Cat (10)

kh       # push 'Hello World' onto the stack
  \!+    # add '!' to the string
     □   # push the list of the inputs onto the stack
      ⁋  # join the element on top of the stack, with '\n' as separator
         # implicit output

## Quine (6)

`I^`     # push 'I^' on the stack
    I    # string -> `string`string
     ^   # reverse the stack
         # implicit output

## Hello (16)

kh\!+          # push `Hello World!` onto the stack
     □         #  | do
      ⁋        #  | many
       `I^`    #  | useless
           I   #  | things
             ^ # reverse the stack
               # implicit output

```
> 1 votes

---
Tags: code-golf, quine, source-layout, hello-world, multiple-holes
---


# Question
Title: Find the maximum length in a ragged list
Given a ragged list of positive integers find the size of the largest list contained somewhere in it.

For example:

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

```

Here the answer is 6 because one of the lists has 6 elements and all other lists have fewer.

```
[1,[1,[8,2,[1,2],5,4,9]],2,[],3]
       ^ ^ ^     ^ ^ ^

```

The length doesn't care in any way about the *value* of the elements, so a list can be longer than the list that contains it.

## Task

Given a ragged list of positive integers output the size of the largest list contained somewhere in it. You may take input in any reasonable format.

This is so answers will be scored in bytes with the goal being to minimize the size of your source-code.

## Testcases

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

```

# Answer
# Python 2, 40 bytes

```
f=lambda a:a>[]and max(len(a),*map(f,a))
```

Attempt This Online!

Uses Python 2's global ordering: lists are all considered greater than ints. We can also use `>` instead of `>=`, because `[]>[]` is `False` which is the same as `0`, which would be the result anyway from the `max(len(a),*map(f,a))`.

This also uses the var-args version of `max` which is shorter than constructing a list. Normally we wouldn't be able to do this, because the var-args form of `max` only works with 2 or more arguments, but if we know `a>[]` then `a` is non-empty, so `*map(f,a)` always adds at least one more argument to the call.

# Whython, 34 bytes

```
f=lambda a:max(len(a),*map(f,a))?0
```

Attempt This Online!

When a member is an integer, the `len` call fails; we just catch this and replace the result with `0`. When `a` is an empty list, this also fails because `max` gets only one argument, but catching and returning `0` conveniently fixes this too.
> 11 votes

# Answer
# , 58 bytes

```
f=function(x)max(l<-length(x),if(l&is.list(x))sapply(x,f))

```

Try it online!
> 6 votes

# Answer
# Haskell \+ free, ~~40~~ 37 bytes

*3 bytes saved by Lynn*

Haskell doesn't have a built in ragged list type so we need to build one out of free monads from the free package.

```
iter(maximum.((:)=<<length)).fmap(*0)

```

Try it online!

## Explanation

First we replace every number with `0` because that is their length, or at least it's the length they should be to make the math work out.

Then from there we make a function `maximum.((:)=<<length`. This looks complicated, but really all it does is take the length of a list of integers, put it on the front of the list and take the maximum of that. So it gives the max of the list or the length of the list whichever is larger.

With this we use `iter` to "tear down" the list. `iter` will start first with the lists containing only integers and run this on them then replace them with their results, and then it will do that again, and again until we've reduced the entire structure down to a single element.

We can visualize the entire process as:

```
[1,[1,[8,2,[1,2],5,4,9]],2,[],3]
[0,[0,[0,0,[0,0],0,0,0]],0,[],0] -- Replace everything with 0
[0,[0,[0,0,2,0,0,0]],0,0,0]
[0,[0,6],0,0,0]
[0,6,0,0,0]
6

```
> 6 votes

# Answer
# BQN, ~~15~~ 13 bytesSBCS

-2 bytes thanks to Razetime!

```
{(≠⌈´⍟=¨)×}

```

Run online!

```
{(≠⌈´⍟=¨)×}   # Anonymous function taking the list as right argument
          ×    # Sign of each number, converts all numbers to 1
 =     ¨       # For each value in the list
     ⍟=        #   do a recursive call if it is a list (rank 1)
                #   and return integers unchanged (rank 0)
     ≠⌈´        # Maximum reduction of the results starting with the length of

```

or questionable 12 bytes:

```
{(≠⌈´⎊0¨)}

```

Run online!

This relies on exceeding the maximum call stack size, which means this only works if such a limit exists and is larger than the maximum depth of the ragged list.
> 5 votes

# Answer
# Python 3, 41 bytes

```
f=lambda x:x*-1or max([len(x),*map(f,x)])

```

Try it online!

-10 bytes thanks to loopy walt with a better way of typechecking
> 4 votes

# Answer
# 05AB1E, 14 bytes

```
ΔDgˆʒ˜gĀ}€`}¯à

```

Try it online or verify all test cases.

**Explanation:**

```
Δ             # Loop until the result no longer changes:
 D            #  Duplicate the current list
  g           #  Pop and push its length
   ˆ          #  Pop and add this to the global array
    ʒ         #  Filter the items within the list:
     ˜        #   Flatten it
      g       #   Pop and push the length
       Ā      #   Check that this is not 0
    }         #  After the filter:
     €`       #  Flatten the list one level down
}             # After the loop:
 ¯            # Push the global array with lengths
  à           # Pop and push its maximum
              # (which is output implicitly as result)

```

Bug-abuses the fact that `˜` gives an error on integers, causing them to be removed after the filter. Most errors in 05AB1E are simply ignored, which would be incorrect in this case, since the  would result in a truthy result.

---

Could have been **13 bytes** in the legacy version of 05AB1E if all integers were guaranteed to contain less digits than the intended result:

```
˜g'ε×æ'g«€.VZ

```

Try it online or verify all test cases.

```
˜             # Flatten the (implicit) input-list
 g            # Pop and push its length
  'ε×        '# Push a string of that many "ε"
     æ        # Pop and push the powerset of this string
              # (the prefixes would be enough, but that builtin doesn't include
              # an empty string which the powerset builtin does)
      'g«    '# Append a trailing "g" to each
         €    # Map over each string
          .V  #  Execute it as 05AB1E code with the (implicit) input-list
              #  (where `ε` is a map, and `g` pushes the length)
            Z # Push the flattened maximum of this list
              # (which is output implicitly as result)

```

This unfortunately doesn't work if the integers are too big, because the `εg` would include the lengths of each inner integer in the resulting list of lists, which could potentially be larger than the intended result.
See that it fails if an input-number contains too many digits.

Minor note: Luckily the `'ε×` isn't a dictionary word. If we would use  instead of `ε` it wouldn't work, because `'€×` is the dictionary word for `"view"`.
> 4 votes

# Answer
# Japt, ~~14~~ ~~13~~ 11 bytes

```
Ë¶Ô©ßDÃrwUl

```

Try it (includes all test cases)

```
Ë¶Ô©ßDÃrwUl     :Implicit input of array U
Ë               :Map each D
 ¶              :  Test for strict equality with
  Ô             :    Max with nothing if an integer (which, for some reason, returns an object)
  Ô             :    Itself reversed if an array (which works because reversing mutates the array)
   ©            :  Logical AND with
    ßD          :   Recursive call with argument D
      Ã         :End map
       r        :Reduce by
        w       :  Maximum
         Ul     :  With initial value of length of U

```
> 4 votes

# Answer
# Factor, 41 bytes

```
[ [ array? ] deep-filter longest length ]

```

Try it online!

Get a list of every list (no matter the depth), then find the length of the longest one. `deep-filter` is like `filter` except instead of traversing elements in a linear fashion, it traverses nested sequences using a depth-first search algorithm. (`deep-reduce` is also an approach that works, but it offers atoms and so it's verbose to check for and ignore them.)

```
                        ! { 1 { 1 { 8 2 { 1 2 } 5 4 9 } } 2 { } 3 }
[ array? ] deep-filter  ! {
                        !     { 1 { 1 { 8 2 { 1 2 } 5 4 9 } } 2 { } 3 }
                        !     { 1 { 8 2 { 1 2 } 5 4 9 } }
                        !     { 8 2 { 1 2 } 5 4 9 }
                        !     { 1 2 }
                        !     { }
                        ! }
longest                 ! { 8 2 { 1 2 } 5 4 9 }
length                  ! 6

```
> 4 votes

# Answer
# , ~~66~~ 64 bytes

```
f=function(x)"if"(is.list(x)&(l=length(x)),max(l,sapply(x,f)),0)

```

Try it online!

Currently being out-golfed by Dominic van Essen.
> 3 votes

# Answer
# JavaScript, 40 bytes

```
f=a=>a/a||Math.max(a.length,...a.map(f))

```

Try it online!

# JavaScript, 43 bytes

```
f=a=>Math.max(~~a.length,...a.map?.(f)??[])

```

```
f=a=>Math.max(~~a.length,...a.map?.(f)??[])

console.log(f([]))
console.log(f([1,2,3]))
console.log(f([[1,2,3]]))
console.log(f([1,2,[],1]))
console.log(f([1,[1,[8,2,[1,2],5,4,9]],2,[],3]))
```
> 3 votes

# Answer
# Vyxal, 9 bytes

```
-λ[vxnLJG

```

Try it Online!

```
-         # Subtract from self to generate a list with the same shape but only zeroes
 λ        # A recursive lambda, which automatically gets called with ^
  [       # If it's truthy (a list)
   vx     # Do a recursive call on each item
     nLJ  # Append the length of the list
        G # Get the maximum

```
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~28~~ 25 bytes

Full program.

```
l←⍬
{1<|≡l,∘≢←⍵:∇¨⍵}⎕
⌈/l

```

Try it online!

`l←⍬` initiate `l` to an empty list

get evaluated console input
`{``}` apply the following anonymous lambda to that; the argument is :  the length of the argument
`l,∘≢←⍵` append `l` with the argument length, giving the argument as pass-through value
the depth (nesting level — negative if ragged) of the argument
`|` absolute value of that
`1<``:` if that is greater than 1:
`∇¨` recurse on each element of the argument

`⌈/l` \[implicitly print\] the largest value of `l` (lit. max-reduce)
> 2 votes

# Answer
# Wolfram Language (Mathematica), 23 bytes

```
Max[Length@#,#0/@(0#)]&

```

Try it online!
> 2 votes

# Answer
# BQN, 13 bytes

```
{⌈´≠⊸∾¨⍟=×}

```

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

Found independently of ovs's solution, but takes advantage of a 1-byte savings proposed in a comment on that solution by Razetime.

### Explanation

```
{⌈´≠⊸∾¨⍟=×}
               Start with the argument, which is either a list or an integer
           ×    Get its sign (applies itemwise over lists): converts all integers to 1
         ⍟=    Apply this function 0 times to an integer or 1 time to a list:
       ¨         Map a recursive call over each element
   ≠⊸∾         Prepend the length of the list (or 1 if it's an integer)
 ⌈´            Take the maximum

```
> 2 votes

# Answer
# Charcoal, 23 bytes

```
⊞υＡＦυＦιＦ⁼κ⁺κ⟦⟧⊞υκＩ⌈ＥυＬι

```

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

```
⊞υＡ

```

Collect the input list into the list of lists.

```
Ｆυ

```

Loop over each list.

```
Ｆι

```

Loop over each element.

```
Ｆ⁼κ⁺κ⟦⟧

```

If adding the empty list to the element results in a copy of the element, ...

```
⊞υκ

```

...then push the element to the list of lists. (Adding the empty list to a scalar results in an empty list, not the scalar.)

```
Ｉ⌈ＥυＬι

```

Output the maximum of all the lengths of the lists.
> 2 votes

# Answer
# Brachylog, 10 bytes

```
{ċl|ċ∋↰}ᶠ⌉

```

Try it online!

### Explanation

```
{      }ᶠ     Find all possible outputs of the following predicate:
 ċ                The input is a list
  l               Output its length
   |            OR
    ċ             The input is a list
     ∋            Take an element of that list (creates choice points for each element)
      ↰            Recursively call this predicate
         ⌉    Final output is the maximum value of the resulting list of possible outputs

```
> 2 votes

# Answer
# Jelly,  ~~7~~  6 bytes

```
¬ß€»LṀ

```

**Try it online!**

A monadic Link accepting a list containing any strictly positive integers or nested, similar, lists that yields the maximal length list.

### How?

```
¬ß€»LṀ - Link, call this "f": list, A
¬      - logical NOT (vectorises) - convert all positive integers to zeros so that
                                    we wont implicitly treat them as ranges
  €    - for each element, E, in A (...if the current A isn't now a zero):
 ß     -   call this Link (i.e. f(A=E))
    L  - length of A - Note that zero has length one.
   »   - maximum (vectorises)
     Ṁ - maximum (of the resulting list)

```
> 2 votes

# Answer
# Perl 5, 34 bytes

```
sub f{max@_+0,map ref?f(@$_):0,@_}

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~44~~ 39 bytes

```
f=->d{d*0==0?0:[d.size,*d.map(&f)].max}

```

Try it online!
> 1 votes

# Answer
# C (gcc) with `-m32` and `-lm`, ~~94~~ ~~88~~ 87 bytes

* -6 thanks to ceilingcat

32-bit mode used to make bit-twiddling of pointers easier.

As C doesn't have any list primitive, I implemented a tagged value list (lists stored as an item have the least significant bit set.) The function simply gets the total length of the current list and checks to see if any sublist has a longer length.

```
f(l,m,i)int*l,*m;{for(m=l,i=0;l;l=l[1])i++;for(;m;m=m[1])*m&1?i=fmax(f(*m^1),i):0;l=i;}

```

Try it online!

Ungolfed:

```
f(l,m,i)int*l,*m;{
  for(m=l,i=0;l;l=l[1]) i++; // Get length of current list
  for(;m;m=m[1])
    *m&1? // Is this a sublist?
      i=fmax(f(*m^1),i): // Is the sublist longer?
    0;
  l=i;
}

```
> 1 votes

# Answer
# tinylisp, ~~65~~ 56 bytes

```
(load library
(d M(q((x)(i(v x)1(max(c(length x)(map M x

```

Try it online!

-9 bytes thanks to DLosc's suggestion for type abuse.
> 1 votes

# Answer
# Julia 1.0, ~~39~~ 34 bytes

```
~a::Int=1
~a=max(length(a),.~a...)

```

Try it online!

Pretty easy to get a general idea of how this works. The `.~(a)` is way of recursively mapping our function (which we've called `~`) on the elements of a.

(-5 bytes thanks to @MarcMush - making use of dispatch instead of the `isa` check.)
> 1 votes

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


title: Build a list from a depth map

text:
# Question
Title: Build a list from a depth map
You will be given as input a non-empty list of positive integers. For example:

```
[1,2,2,2,1]

```

You want to produce a ragged list as output which has this as its "depth map". This list should have the same elements in the same order but each element `n` should be at the depth equal to its value.

```
[1,[2,2,2],1]

```

This is a list where the `1`s are at the first level, the `2`s are nested in there, the threes would be nested in that etc.

There are multiple outputs that fit this description:

```
[1,[2],[2],[2],1]
[1,[],[2,[],2,2],1]
[1,[2,2,2],1,[[[]]]]

```

We want the simplest one, that is the one with the fewest lists total. So in this case

```
[1,[2,2,2],1]

```

only has 2 lists whereas all the other examples had more.

## Task

Take a depth map and produce the simplest ragged list that it could represent as outlined above.

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

## Test cases

```
[1] -> [1]
[2] -> [[2]]
[3] -> [[[3]]]
[10] -> [[[[[[[[[[10]]]]]]]]]]
[1,2] -> [1,[2]]
[2,2] -> [[2,2]]
[2,1,2] -> [[2],1,[2]]
[1,2,3,2] -> [1,[2,[3],2]]
[1,2,3,3,3,2,1] -> [1,[2,[3,3,3],2],1]
[1,2,1,2,1,3,3,1] -> [1,[2],1,[2],1,[[3,3]],1]

```

# Answer
# Retina, ~~23~~ 21 bytes

Input are comma-separated integers, output is in the same format as the test cases.

```
\d+
*[$&$&*]
+`],\[
,

```

Try it online!

Wraps each number on its own, then repeatedly replaces `],[` with `,`.
> 9 votes

# Answer
# JavaScript (ES6),  ~~80 79~~  74 bytes

*Saved 5 bytes thanks to @tsh*

This builds a weird and dirty string internally but eventually returns a clean ragged list.

```
a=>eval('_='+[...a,'_'].map(g=v=>d^v?d++<v?"["+g(v):"],"+g(v,d-=2):v,d=0))

```

Try it online!

### How?

Starting with \\$d=0\\$, for each entry \\$v\\$ in the original array followed by an extra `"_"`:

* if the current depth \\$d\\$ is less than \\$v\\$: we append the string `"["` repeated \\$v-d\\$ times before \\$v\\$ and update \\$d\\$ to \\$v\\$
* if \\$d\\$ is greater than \\$v\\$: we append the string `"],"` repeated \\$d-v\\$ times before \\$v\\$ and update \\$d\\$ to \\$v\\$. (NB: The trailing `"_"` triggers this case and closes all pending brackets.)
* if \\$d=v\\$: we just leave \\$v\\$ unchanged

We then prepend `"_="`, which implicitly joins everything with commas, and we evaluate the resulting string.

For instance, `[1,2,3,3,3,2,1]` is turned into:

```
"_=[1,[2,[3,3,3,],2,],1,],_"

```

which is evaluated to:

```
[1,[2,[3,3,3],2],1]

```
> 7 votes

# Answer
# Python 3, 75 bytes

```
f=lambda x,l=0:x and"],"*(l-x[0])+"["*(x[0]-l)+"%s,"%x+f(x[1:],x[0])or"]"*l

```

Try it online!

Python's `%` formatter coming in clutch.

Output is a list in string format that can be evaluated by Python to the correct answer.

Simple recursive function that walks down the input list. `l` just stores the value of the last element.

# Python 3.8 (pre-release), 71 bytes

```
lambda x,i=0:",".join((j-i)*"["+(i-(i:=j))*"],"+str(j)for j in x)+i*"]"

```

Try it online!

Using the walrus operator removes the need for recursion, and the trailing comma can be added by `str.join`. Suggested by @loopywalt.
> 6 votes

# Answer
# BQN, 28 bytesSBCS

```
{⟨0⟩:0;1+¨{⊐+`»⊸∨¬×}⊸⊔-1}

```

Run online!

A single recursive function that builds the output as a nested list.

`⟨0⟩:0` Base case: If the argument is a list containing a single 0, return 0 as a scalar value.

`-1` Decrement each value.
`{⊐+`»⊸∨¬×}⊸⊔` Group adjacent positive integers, and put each 0 in its own group.
`¨` recursively call the function on each group.
`1+` Add 1 to each number.
> 6 votes

# Answer
# , 63 59 37 bytes

```
<:<@([:>:L:0$:^:(0<{.));.1~1,2~:/\=&1

```

Try it online!

-22 thanks to approach suggested by ovs! It's similar or the same as his BQN answer's.

## , original approach 63 59 bytes

```
g=.((,$:/@,&.>/@]^:[~[:(1=*+.1<<.)/,&L.){.),}.@]
[:g/<^:]"+

```

Try it online!

This is *ridiculous*. Someone please find a better approach that still uses boxes and let me know what it is...

The basic approach is:

* Individually wrap each element to its depth.
* Recursively meld together neighboring elements using a fold.
> 5 votes

# Answer
# Charcoal, 29 bytes

```
≔⁰ηＦＡ«Ｆ⁻ηι]→Ｆ⁻ιη[Ｉι≔ιη»Ｆη]ＵＢ,

```

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

```
≔⁰η

```

Start with a depth of 0.

```
ＦＡ«

```

Loop through the depths.

```
Ｆ⁻ηι]

```

Add `]`s as necessary to reduce the depth to the current depth.

Leave a space between values.

```
Ｆ⁻ιη[

```

Add `]`s as necessary to increase the depth to the current depth.

```
Ｉι

```

Output the current depth.

```
≔ιη

```

Save the current depth as the previous depth.

```
»Ｆη]

```

Output the necessary closing `]`s at the end.

```
ＵＢ,

```

Replace all the interior spaces with commas. (The leading space simply gets skipped, since it wasn't actually printed.)

Actually creating the list in memory takes 44 bytes:

```
⊞υ⟦⟧ＦＡ«Ｗ‹Ｌυι«≔⟦⟧θ⊞§υ±¹θ⊞υθ»≔…υιυ⊞§υ±¹ι»⭆¹§υ⁰

```

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

```
⊞υ⟦⟧

```

Start with an empty list.

```
ＦＡ«

```

Loop over the depths.

```
Ｗ‹Ｌυι«

```

While the next depth is larger than the current depth, ...

```
≔⟦⟧θ⊞§υ±¹θ⊞υθ

```

... nest a list.

```
»≔…υιυ

```

Truncate the current depth to the next depth.

```
⊞§υ±¹ι

```

Append the next depth value to its list.

```
»⭆¹§υ⁰

```

Pretty-print the final list.
> 4 votes

# Answer
# 05AB1E, 22 bytes

```
εDG…[ÿ]]',ý…[ÿ]…],[',:

```

Input as list, output as string. It kinda feels like cheating, but I saw multiple other answers do the same.. And I guess we could technically add an eval.

Try it online or verify all test cases.

A port of *@xigoi*'s Jelly answer is 22 bytes as well:

```
0.ø¥Ý€{.±…,[]sèJI.ιJ¦¨

```

Try it online or verify all test cases.

**Explanation:**

```
ε         # Map over each integer in the (implicit) input-list:
 D        #  Duplicate the integer
  G       #  Pop and loop the integer-1 amount of times:
   …[ÿ]   #   Wrap it in block-quotes as string
]         # Close both the inner loop and outer map
 ',ý     '# Join the strings with "," delimiter
    …[ÿ]  # Wrap the entire string into block-quotes as well
…],[',:  '# Replace all "],[" with ","
          # (after which the resulting string is output implicitly)

0.ø       # Surround the (implicit) input-list with leading/trailing 0
   ¥      # Get the deltas/forward-differences of this list
    Ý     # Transform each value to a list in the range [0,value]
     €{   # Sort each inner list
       .± # Convert each to its sign (-1 if <0; 0 if 0; 1 if >0)
…,[]sè    # Modular 0-based index each into ",[]"
      J   # Join each inner list of characters to a string
I.ι       # Interleave it with the input-list
   J      # Join it together again
    ¦¨    # Remove the leading/trailing ","
          # (after which the resulting string is output implicitly)

```
> 4 votes

# Answer
# Jelly, 20 bytes

```
Ø0jIr0Ṣ€Ṡị“[],”ż⁸FḊṖ

```

Try it online!

A string-based approach.

## Explanation

```
Ø0jIr0Ṣ€Ṡị“[],”ż⁸FḊṖ
Ø0j                  Surround with zeroes
   I                 Increments
    r0               Raplace each element x with the range x..0
      Ṣ€             Sort each range
        Ṡ            Replace each number with its sign
         ị“[],”      Perform the mapping: 1 -> "[", -1 -> "]", 0 -> ","
               ż⁸    Zip with the original input
                 F   Flatten
                  ḊṖ Remove the leading and trailing commas

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~59~~ ~~41~~ 40 bytes

```
f@{a:0..}=a
f@l_:=f/@SplitBy[l-1,Sign]+1

```

Try it online!
> 3 votes

# Answer
# Python3, 112 bytes:

```
from itertools import*
f=lambda x,n=1:[j for a,b in groupby(x,key=lambda x:x==n)for j in(b if a else[f(b,n+1)])]

```

Try it online!
> 2 votes

# Answer
# Ruby, 54 bytes

```
f=->a,d=1{a.chunk{_1>d}.flat_map{_1 ? [f[_2,d+1]]:_2}}
```

Attempt This Online!

-16 from AZTECCO.
> 2 votes

# Answer
# Perl 5 -p, 86 bytes

```
s/\d+,?|$/"]"x($d=$l-$&).","."["x-$d.($l=$&)/ge;s/(\[),|,(])|,(,)/$1$2$3/g;s/^.|..$//g

```

Try it online!
> 2 votes

# Answer
# , 84 bytes

Or **\>=4.1, 77 bytes** by replacing the word `function` with a `\`.

```
f=function(v,s=1)"if"(all(v<s),v,{y[]=cumsum(c(T,y<-v==s)|y);Map(f,split(v,y),s+1)})

```

Try it online!

Outputs the actual list structure.
> 2 votes

# Answer
# Vyxal 2.4.1 `D`, 20 bytes

```
Ġƛh‹(w);S`⟩|⟨`\|øVḢṪ

```

Try it Online!

A big mess. We're using v2.4.1 because v2.6+ prettyprint lists with spacing.

```
Ġ                    # Group consecutive identical elements
 ƛ     ;             # Map...
  h‹( )              # item-1 times...
     w               # wrap in a list
        S            # Stringify
         `⟩|⟨`\|øV   # Replace `⟩|⟨` with `|`
                  ḢṪ # Remove the first and last characters.

```
> 1 votes

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


title: Chris Pine's "Deaf Grandma"

text:
# Question
Title: Chris Pine's "Deaf Grandma"
I'm a mentor at RubyLearning and one of the exercises we give to our students is the "Deaf Grandma" exercise from Chris Pine's book "Learn to Program". Here's the description:

> Write a Deaf Grandma program. Whatever you say to grandma (whatever you type in), she should respond with: "Huh?! Speak up, sonny!", unless you shout it (type in all capitals). If you shout, she can hear you (or at least she thinks so) and yells back: "No, not since 1938!"
>
> To make your program really believable, have grandma shout a different year each time; maybe any year at random between 1930 and 1950. (This part is optional, and would be much easier if you read the section on Ruby's random number generator at the end of the methods chapter.) You can't stop talking to grandma until you shout "BYE".

After several course iterations I tried to see how small I can get this and now have it down to 112 characters:

```
puts (s||='').upcase==s ? "NO, NOT SINCE #{1930+rand(21)}!":"HUH?! SPEAK UP, SONNY!" until(s=gets.chomp)=="BYE"

```

I'm curious to see in how few characters this can be achieved in the language of your choice, because I think Ruby is already doing really well here.

**Edit:** The Perl solution posted below led to

```
ruby -nle 'puts($_=="BYE"?exit: $_.upcase!? "HUH?! SEPAK UP, SONNY!":"NO, NOT SINCE #{1930+rand(21)}!")'

```

which is 92 characters for the expression + 2 more for the `n` and `l` options.

# Answer
## Perl, 85 ~~91~~

Run with `perl -nE '<code goes there>'` (`n` counted in program size):

```
$==1930+rand 21;say/^BYE$/?last:uc eq$_?"
NO, NOT SINCE $=!":"HUH?! SPEAK UP, SONNY!"

```

~~That trailing exclamation mark is *very* expensive...~~

Edits suggested by IK:

* Using a regexp instead of a string match spares the `-l` global option as well as two program characters: -3.
* Using an actual variable to save a value and use it later for interpolation (Genius! Who'd have thought of using a variable for that?): 0.
* Making that variable `$=`, constrained to be an integer: -4.

(and it still doesn't add up and I'm too sleepy to find out why. Oh well, the final count is right at least)
> 13 votes

# Answer
## Python 120 Characters

```
r=raw_input
s=r()
while'BYE'!=s:
 print["HUH?! SPEAK UP, SONNY!","NO, NOT SINCE %d!"%(1930+id(s)%21)][s.isupper()];s=r()

```

Any hints to improve?
> 6 votes

# Answer
**131 characters in PowerShell:**

```
for(){$j=read-host;if($j-ceq"BYE"){break}if($j-ceq$j.ToUpper()){"No, not since 19$(10..90|random)!"}else{"Huh?! Speak up, sonny!"}}

```

W/ whitespace:

```
for(){
  $j = read-host;
  if ( $j -ceq "BYE" ) { break }
  if ( $j -ceq $j.ToUpper() ) { "No, not since 19$(10..90|random)!" }
  else { "Huh?! Speak up, sonny!" }
}

```

Squeezed 18 characters from Joey's suggestion.

BTW, 'Learn to Program' was the first programming book I ever read cover to cover.
> 4 votes

# Answer
**C# - 234 Chars**

```
using System;class P{static void Main(){for(;;){var s=Console.ReadLine();if(s!=s.ToUpper()){Console.WriteLine("Huh?! Speak up, sonny!");continue;}if(s=="BYE")break;Console.WriteLine("No, not since 19{0}!",new Random().Next(30,51));}}}

```

More readable:

```
using System;
class P
{
    static void Main()
    {
        for(;;)
        {
            var s=Console.ReadLine();
            if(s!=s.ToUpper())
            {
                Console.WriteLine("Huh?! Speak up, sonny!");
                continue;
            }
            if(s=="BYE")
                break;
            Console.WriteLine("No, not since 19{0}!",new Random().Next(30,51));
        }
    }
}

```
> 3 votes

# Answer
## Befunge - 27x6 = 162 characters

```
> ~:0`  #v _            vv<
         >:"a"`!#v  _:"z"`|
^                <       <
v"Huh?! Speak up, sonny!"0<
v"No, not since 1938!"0 <
>:# #, _@

```

EDIT: Completely missed the "BYE" part. New version coming soon.

EDIT 2: Actually, that makes it a bit too complex for my meager Befunge skills. I might try again later, but I can't think of any simple way to implement it at the moment.
> 3 votes

# Answer
**C# - 194 CHARS**

```
using System;class P{static void Main(){var s=Console.ReadLine();if(s!="BYE"){Console.Write((s==s.ToUpper()?"No, not since 19"+new Random().Next(30, 51):"Huh?! Speak up, sonny")+"!");Main();}}}

```

With whitespaces:

```
using System;
class P
{
    static void Main()
    {
        var s = Console.ReadLine();
        if (s != "BYE")
        {
            Console.Write((s == s.ToUpper() ? "No, not since 19" + new Random().Next(30, 51) : "Huh?! Speak up, sonny") + "!");
            Main();
        }
    }
}

```

With some inspiration from Nellius and fR0DDY.

Please let me know if it can be improved.
> 3 votes

# Answer
# D: 246 Characters

```
import std.random,std.stdio,std.string;void main(){auto r=rndGen();for(;;){auto t=strip(readln());if(t=="BYE")break;if(t.toupper()==t)writefln("No, not since %s!",{r.popFront();return r.front%20+1930;}());else writeln("Huh?! Speak up, sonny!");}}

```

More Legibly:

```
import std.random, std.stdio, std.string;

void main()
{
    auto r = rndGen();

    for(;;)
    {
        auto t = strip(readln());

        if(t == "BYE")
            break;

        if(t.toupper() == t)
            writefln("No, not since %s!", {r.popFront(); return r.front % 20 + 1930;}());
        else
            writeln("Huh?! Speak up, sonny!");
    }
}

```
> 3 votes

# Answer
javascript, 142 characters, 29 of them perform random year

```
n='a'; while((/[a-z]/.test(n)?r="HUH?! SPEAK UP, SONNY!":n=="BYE"?r='':r="NO, NOT SINCE "+Math.floor(Math.random()*21+1930))!=''){n=prompt(r)}

```
> 3 votes

# Answer
## Windows PowerShell, ~~121~~ 117

Due to the nature of the task this looks pretty much identical to Ty Auvil's solution, although it was written independently:

```
for(;($j=read-host)-cne'BYE'){if($j-cmatch'[a-z]'){'Huh?! Speak up, sonny!'}else{"No, not since 19$(30..50|random)"}}

```

Thanks to SpellingD for the suggestion,
> 3 votes

# Answer
# Awk: ~~97~~ 95 characters

Thanks to

```
/^BYE$/{exit}$0=toupper($0)==$0?"NO, NOT SINCE "int(rand()*21+1930)"!":"HUH?! SPEAK UP, SONNY!"

```

Try it online!
> 3 votes

# Answer
**Haskell (189)**

```
import Random
import Char
main=getLine>>=g
g"BYE"=return""
g s|s/=map toUpper s=putStrLn"HUH?! SPEAK UP SONNY!">>main|4>2=randomRIO(30,50::Int)>>=putStrLn.("NO, NOT SINCE 19"++).show>>main

```

The weird thing is, Haskell code is usually a lot shorter than comparable C code when writing a 'serious' program.
> 2 votes

# Answer
## APL (76)

```
 {'BYE'≢A←⍞:∇⎕←{∧/⍵∊⎕A:'No, not since ',⍕1938+?20⋄'Huh?! Speak up sonny!'}A}⍬

```
> 2 votes

# Answer
**C# - 345 Chars**

```
using System;class Program{static void Main(){for(;;){if(!t(Console.ReadLine()))break;}}static bool t(string s){bool b=false;if(s=="BYE")return b;int i=0;for(;i<s.Length;i++){b=(s[i]>65&&s[i]<90)?true:false;if(!b)break;}if(b) p("NO, NOT SINCE 1938!");else p("HUH?! SPEAK UP, SONNY!");return true;}static void p(string s){Console.WriteLine(s);}}

```

Damn verbose language ... :-)
> 1 votes

# Answer
### C# - 196 chars (but leaky)

`using System;class P{static void Main(){var s=Console.ReadLine();if(s!="BYE"){Console.Write((s==s.ToUpper()?"No, not since 19"+new Random().Next(30, 51):"Huh?! Speak up, sonny")+"!\n");Main();}}}`

That's @Richard's (leaky) answer with two parens (see below) and a \n added in there to get the EOL in both cases. Otherwise the `" + "` is just wasted space.

**Formatted**

```
using System;
class P
{
    static void Main() {
        var s = Console.ReadLine();
        if (s != "BYE") {
            Console.Write((
                s == s.ToUpper() ?
                "No, not since 19" + new Random().Next(30, 51) :
                "Huh?! Speak up, sonny"
                ) + "!\n");
            Main();
        }
    }
}

```

UPDATE: to clarify my comment about the parens being needed, here's what i get without the parens (i.e. with @Richard's original solution):

And with the parens:

Neither of these use my additional `\n` though.
> 1 votes

# Answer
# Bash: ~~136~~ 128 characters

```
while read s
do
[[ $s = BYE ]]&&break
[[ ${s^^} = $s ]]&&echo NO, NOT SINCE $[RANDOM%21+1930]!||echo HUH?! SPEAK UP, SONNY!
done

```

## Limited alternative: ~~132~~ 123 characters

```
f(){
read s
[[ $s = BYE ]]||{
[[ ${s^^} = $s ]]&&echo NO, NOT SINCE $[RANDOM%21+1930]!||echo HUH?! SPEAK UP, SONNY!
f
}
}
f

```

You can talk to a deaf infinitely, but the conversation with this later code is limited by the call stack. (In my test it gets terminated after 4989 calls.)
> 1 votes

# Answer
# Javascript - 133 131 130 128 127 121 chars

**golfed version of www0z0ks solution**

```
g='';while((i=prompt(g))!='BYE'){/[a-z]/.test(i)?g='Huh?! Speak up, sonny!':g='No, not since '+Math.floor(Math.random()*21+1930)+'!'}

```

```
g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.floor(Math.random()*21+1930)+'!'}

```

```
g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!'}

```

```
for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!');

```

```
for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+parseInt(Math.random()*21+1930)+'!');

```

```
for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+(Math.random()*21+1930|0)+'!');

```

**Edit:** Saved another six chars with this great tip
> 1 votes

# Answer
# Jelly, 54 bytes

```
21X+⁽¤Ḷ“Ð€ÑƊʂ!ṡxẈ»,K”!
ɠ¢“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ṄßƊḟ⁻?“BYE

```

Try it online!

# Jelly, 49 bytes

```
21X+⁽¤Ḷ“Ð€ÑƊʂ!ṡxẈ»,K”!µ“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ḟ⁻?“BYE

```

Try it online!

# Jelly, 51 bytes

```
21X+⁽¤Ḷ“Ð€ÑƊʂ!ṡxẈ»,K;”!µ“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ḟ⁻?“BYE”

```

Try it online!

---

The first one is perhaps the most faithful interpretation of the question. It is a full program which reads input line by line from STDIN and acts on it line by line, terminating either when it reaches "BYE" or the end of STDIN (at which point it exits with an error).

The second is a full program which takes a single string as input (e.g. `Hello`, `HELLO`, `BYE`, etc.) and outputs the corresponding output (an empty output for `BYE`)

This third is a function which can be repeatedly called with arguments in a similar version to the second, but each argument is independent - calling it with `BYE` will not prevent you calling it again.

All three output not in uppercase, reflecting the text of the question rather than the sample program provided. +5 bytes to output in all uppercase

---

As they all have the same basic structure, I'll only explain the first one, and leave the other two as exercises for the reader

## How it works

```
21X+⁽¤Ḷ“Ð€ÑƊʂ!ṡxẈ»,K”! - Helper link. This takes no arguments, outputs a string and returns "!"
21                     - Yield 21
  X                    - Choose a random integer between 1 and 21 inclusive
    ⁽¤Ḷ                - Compressed integer: 1929
   +                   - Add to the random integer. Call that Y
       “Ð€ÑƊʂ!ṡxẈ»     - Compressed string: "No, not since"
                  ,    - Pair; ["No, not since", Y]
                   K   - Join the two with spaces
                    ”! - Unparseable nilad; Output the space separated string and return "!"

ɠ¢“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ṄßƊḟ⁻?“BYE - Main link f(). Takes no arguments
ɠ                               - Read a line of STDIN, L
                          ?     - If:
                         ⁻ “BYE -   Condition: L does not equal "BYE"
                       Ɗ        -   Then:
                    ?           -     If:
                   Ƒ            -       Condition: L does not change when:
                 Œu             -         Converted to uppercase
 ¢                              -       Then: Call the helper link, yielding "!"
  “®VẹQƝɗi³ỤwṖoỴ»               -       Else: Compressed string "Huh?! Speak up, sonny!"
                     Ṅ          -     Print with a trailing newline
                      ß         -     Recurse, calling f() again
                        ḟ       -   Else: Return the empty string and halt execution

```
> 1 votes

# Answer
# Vyxal, 57 bytes

```
{:‛Ṗ⊍⇧≠|aA[`No, λ† ∧Ṡ %!`»÷ḟ»21℅+%,|`Huh?! ∞⇧ up, ½Ŀny!`,

```

Try it Online!

Vyxal's not particularly good at English compression.

```
{                                # While...
 :   ≠|                          # Take an input, is it not equal to...
  ‛Ṗ⊍⇧                           # "BYE"
       aA[                       # If all uppercase
          `...`        %,        # Print "No, not since" formatted by
               »÷ḟ»21℅+          # 1929 + random(1..21)
                          `...`, # Otherwise print "Huh?! Speak up, sonny!"

```
> 1 votes

# Answer
**Clojure - 160 154 Characters**

```
(#(if(= % "BYE")%(do(if(=(.toUpperCase %)%)(prn(str"No, not since "(+ 1930(rand-int 9))"!"))(prn"Huh?! Speak up, sonny!"))(recur(read-line))))(read-line))

```

Working on golfing it a bit more. Suggestions welcome.

Run through REPL
> 0 votes

# Answer
# Q, 115

```
{while[1;v:read0 0;$[v~"BYE";'`;v~upper v;-1"No, not since ",/:(($)1?1930+(!)20),'"!";-1"Huh?! Speak up, sonny!"]]}

```

usage

```
q){while[1;v:read0 0;$[v~"BYE";'`;v~upper v;-1"No, not since ",/:(($)1?1930+(!)20),'"!";-1"Huh?! Speak up, sonny!"]]}`
Hi
Huh?! Speak up, sonny!
Hello
Huh?! Speak up, sonny!
HELLO!
No, not since 1938!
Goodbye Grandma
Huh?! Speak up, sonny!
BYE
'

```
> 0 votes

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


title: Finish a symmetrical map

text:
# Question
Title: Finish a symmetrical map
You are given one-quarter of a map that is symmetrical over the x- and y-axes as input. The program should print the complete map.

The map can contain the following characters: `-+/\|.`, and they should be turned as expected. The in data is always rectangular and small.

## Example

```
$ cat in
+---
|./.
|/..

$ ./solution < in
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+

```

Shortest code wins.

# Answer
## Golfscript - 32 chars

```
n%{{.-1%{.3%2=115*^}%+}%zip}2*n*

```

Due to the symmetry of the problem, we repeat twice {flip horizontally, transpose (`zip`)}. As a bonus, you can change the value `2` to a larger number to repeat the image more.

Character transposition is done as `x^=155 if x%3==2`, due to the restricted character space. There's also `{.5^3%(45+}` at the same length.
> 1 votes

# Answer
# Canvas, ~~5~~ 4 bytes

```
║Ｑ↷↷

```

First Canvas answer, so let's start with an easy one. :)

-1 byte thanks to *@dzaima*.

The slashes are automatically converted when mirroring or rotating in Canvas.
Could have been 1 byte  (Try it online), but unfortunately it also transforms the dots `.` to single quotes `'` when mirroring horizontally.

Try it online.

**Explanation:**

```
         # (Take the multi-line input implicitly as canvas object)
║        # Palindromize the canvas object (without overlap)
 Ｑ      # Output it with a trailing newline (without popping)
  ↷↷    # Rotated the canvas object that's still on the stack by 90 degrees twice
         # (and output it implicitly as well at the end)

```
> 4 votes

# Answer
## Windows PowerShell, 99 ~~103~~ ~~117~~ ~~126~~ ~~129~~

```
filter x{$_-split'/'-replace'\\','/'-join'\'}$input|%{$_+-join($_[40..0]|x)}|%{$_
$s=,($_|x)+$s}
$s

```

Notes:

* This unfortunately needs two things that PowerShell is notoriously bad at while golfing: Reversing a string (or sequence of values) and transliterating stuff in a string. I'm fairly sure that this is at least twice as long as a Perl of Ruby solution.

Test:

```
> gc in| .\map.ps1
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+

> gc in2
+\/
/\/
> gc in2| .\map.ps1
+\/\/+
/\/\/\
\/\/\/
+/\/\+

```

History

* 2011-02-09 11:10 (129) – First attempt.
* 2011-02-09 11:27 (126) – `OFS` to save the `-join` and stored `99..0` in a variable.
* 2011-02-09 11:31 (117) – `-replace` works against arrays, so I don't need three `-replace`s but can do a `-split`, `-replace`, `-join` instead.
* 2011-02-09 15:03 (105) – Instead of doing the same thing twice, do it once and reverse it. And putting an assignment into parentheses causes it to spit out its value to the pipeline :-)
* 2011-02-09 15:08 (103) – I don't need `$a` anymore since `99..0` isn't used that often by now.
* 2011-02-09 15:17 (99) – There doesn't need to be whitespace after the `filter` definition. Removed `$x` and instead collecting every line during the first run in an array and then outputting that for the second half.
> 2 votes

# Answer
# Ruby - 88 87 chars

```
t=->s{s.tr'/\\\\','\\\\/'}
puts a=$<.map{|l|l.chop!+t[l.reverse]}
puts a.reverse.map &t

```

## Test Run

```
D:\tmp>ruby cg_sym_map.rb < sym_map.in.
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+

```
> 2 votes

# Answer
# Charcoal, ~~5~~ 4 bytes

```
Ｓ‖Ｍ⌈

```

-1 byte thanks to *@Neil*.

Charcoal automatically handles reflecting the slashes correctly.

Try it online (verbose) or Try it online (pure).

**Explanation:**

Take the input as a string:

```
InputString()
Ｓ

```

Reflect mirror it both towards the right and downwards (`:⌈` is a builtin for `:Right, :Down`):

```
ReflectMirror(:⌈)
‖Ｍ⌈

```
> 2 votes

# Answer
# APL (Dyalog Classic), ~~25~~ ~~23~~ ~~22~~ ~~21~~ 19 bytes

```
(⌽⍪⊖){⊃3⌽⍵∪'/\'}¨,⌽

```

Try it online!
> 2 votes

# Answer
## Perl, 80 chars

```
print reverse map{s@.*@($b=$&)=~y:/\\:\\/:,$&.reverse$b@e;print;y@/\\@\\/@;$_}<>

```
> 1 votes

# Answer
Shell Scripting!!

```
#!/bin/sh

rm temp
touch temp
file=$1
for STRING in `cat $1`
do
   printf $STRING >> temp
   for ((COUNT=0; COUNT<${#STRING}; COUNT++))
   do
      RECORD[$COUNT]=${STRING:$COUNT:1}
   done
   for ((REV_COUNT=${#STRING}; REV_COUNT>=0; REV_COUNT--))
      do
        if [ "${RECORD[$REV_COUNT]}" = "\\" ]; then
            printf "/" >> temp
        elif [ "${RECORD[$REV_COUNT]}" = "/" ]; then
            printf "\\" >> temp
        else
           printf "${RECORD[$REV_COUNT]}" >> temp
        fi
      done
   echo >> temp
done
cat temp
tac temp > temp2
for STRING in `cat temp2`
do
   for ((COUNT=0; COUNT<${#STRING}; COUNT++))
   do
      RECORD[$COUNT]=${STRING:$COUNT:1}
   if [ "${RECORD[$COUNT]}" = "\\" ]; then
            printf "/"
   elif [ "${RECORD[$COUNT]}" = "/" ]; then
            printf "\\"
   else
           printf "${RECORD[$COUNT]}"
   fi
   done
echo
done

```

I/O

```
./solution in

+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+

```
> 1 votes

# Answer
# CJam, 26 bytes

CJam is newer than this challenge, so this answer is not eligible for the green checkmark, but it was a fun exercise anyway

```
qN/{{_W%"\/"_W%er+}%z}2*N*

```

Test it here.

## Explanation

```
qN/{{_W%"\/"_W%er+}%z}2*N*
qN/                        "Read STDIN and split on newlines.";
   {                 }2*   "Execute this block twice.";
    {             }%       "Map this block onto each line.";
     _W%                   "Duplicate and reverse.";
        "\/"               "Push the string '\/'.";
            _W%            "Duplicate and reverse.";
               er          "Character transliteration, swaps slashes and backslashes.";
                 +         "Append to first half of the line.";
                    z      "Zip, i.e. transpose the map.";
                        N* "Join with newlines.";

```

The transposing at the end leads the the second flipping to be performed along the columns. At the end we transpose the map again, so we end up with the original orientation.
> 1 votes

# Answer
# Powershell, 95 bytes

*Inspired by Joey's answer.*

```
filter x{$_;$_[40..0]|%{$_-split'/'-replace'\\','/'-join'\'}},($args|%{-join(,($_|% t*y)|x)})|x

```

Note: `40` because the author posts the comment `Let's say the input is at most 16 rows and 40 characters`.

Test script:

```
$f = {

filter x{$_;$_[40..0]|%{$_-split'/'-replace'\\','/'-join'\'}}
,($args|%{-join(,($_|% t*y)|x)})|x

}

@(
    ,( ("+---",
        "|./.",
        "|/.."),
        "+------+",
        "|./..\.|",
        "|/....\|",
        "|\..../|",
        "|.\../.|",
        "+------+")
    ,( ("+\/",
        "/\/"),
        "+\/\/+",
        "/\/\/\",
        "\/\/\/",
        "+/\/\+")
    ,( ("+---",
        "|...",
        "|..\"),
        "+------+",
        "|......|",
        "|..\/..|",
        "|../\..|",
        "|......|",
        "+------+")
) | % {
    $m,$expected = $_
    $result = &$f @m
    "$result"-eq"$expected"
    $result
}

```

Output:

```
True
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+
True
+\/\/+
/\/\/\
\/\/\/
+/\/\+
True
+------+
|......|
|..\/..|
|../\..|
|......|
+------+

```
> 1 votes

# Answer
# Vyxal, 5 bytes

```
øṀ¶+∞

```

Try it Online!

```
øṀ    # Vertically mirror, flipping /\
  ¶+  # Append a newline
    ∞ # Palindromise

```
> 1 votes

# Answer
# Ruby - 105

```
t=->s{s.tr '/\\\\','\\\\/'}
$<.read.split.map{|l|print l+=t[l.reverse]+"
"
l}.reverse.map{|l|print t[l]}

```
> 0 votes

# Answer
## Golfscript - 44 chars

```
n%{.-1%'/'/{'\\'/'/'*}%'\\'*+}%.-1%{-1%}%+n*

```

result

```
$ cat in2
+-/|/\
/\|//-
$ cat in2 | golfscript codegolf-761.gs
+-/|/\/\|\-+
/\|//--\\|/\
\/|\\--//|\/
+-\|\/\/|/-+

```

### Another script that only work for example and does not flip for '\\' - 32 chars

```
n%{.-1%'/'/'\\'*+}%.-1%{-1%}%+n*

```

result

```
$ cat in
+---
|./.
|/..
$ cat in | golfscript codegolf-761.gs
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+
$

```
> 0 votes

# Answer
# Haskell, 76 bytes

```
c '/'='\\';c '\\'='/';c x=x;i=(c<$>)
q#x=x++q(reverse x)
f=((i<$>)#).map(i#)

```

Try it online!

```
-- Only / and \ get converted, all other chars are passed as is
c '/'='\\';c '\\'='/';c x=x

-- "Invert" the string (that is switch all / and \ in it)
-- Just map our conversion function over the string
i = (c<$>)

-- Helper: Concatenate a list with its reversed copy (with the given function applied to the copy)
q # x = x ++ q (reverse x)

-- the resulting function:
f = ((i<$>)#) . -- produce the lower half of the image by reversing the upper half and inverting slashes in each line
    map (i#) -- produce the upper half or the image (by concating each input line with its reversed, inverted version)

```
> 0 votes

# Answer
# MS-SQL 2017, 243 bytes

**input**:

```
DECLARE @s VARCHAR(100) ='+---'+CHAR(10)+'|...'+CHAR(10)+'|..\';

```

*compressed*:

```
declare @t TABLE(l INT IDENTITY(1,1),s CHAR(40));INSERT INTO @t(s)SELECT value+TRANSLATE(REVERSE(value),'\/','/\')FROM STRING_SPLIT(@s,char(10));SELECT s FROM(SELECT l,s FROM @t UNION ALL SELECT 1e3-l,TRANSLATE(s,'\/','/\')FROM @t)b ORDER BY l

```

*human readable*:

```
declare @t TABLE(l INT IDENTITY(1,1),s CHAR(40));
INSERT INTO @t(s)
  SELECT value+TRANSLATE(REVERSE(value), '\/', '/\')
  FROM STRING_SPLIT(@s,char(10));

SELECT s
FROM(
   SELECT l, s FROM @t
   UNION ALL
   SELECT 1e3-l, TRANSLATE(s, '\/', '/\') FROM @t
  )b
ORDER BY l

```

**output** (as text in ex.management studio):

```
+------+
|......|
|..\/..|
|../\..|
|......|
+------+

(6 rows affected)

```
> 0 votes

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


title: Tips for golfing in tinylisp

text:
# Question
Title: Tips for golfing in tinylisp
`tinylisp` is, in its essence, a very stripped-down version of Lisp, as the name suggests. It was made by @DLosc for an "interpret this language" challenge, which can be found here. It features a small amount of builtins, which can be used to create practically anything.

There is a repository for the "official" tinylisp interpreter/documentation here, and it is available to try online here.

What tips do you have for golfing (creating the shortest program possible) in tinylisp? This question is looking for tips to golf specifically in tinylisp, not general tips that can be applied to any language.

# Answer
# Abuse builtins for type-checking

The official way to check the type of a value is with the `type` builtin, which returns one of `Int`, `List`, `Name`, or `Builtin`. However, `(e(type x)(q Int))` is pretty verbose, and `(type? x Int)` with the library isn't too much shorter.

The good news here is that errors in tinylisp generally aren't fatal--they just print a warning to stderr and return `()` (nil). So under certain circumstances, we can use the one-letter builtins in unintended ways to perform ad-hoc type-checking. Supposing we have some value bound to the name `x`:

* `(a x 1)` \- truthy for all integers except -1; falsey for -1; error for any other type
* `(s x 1)` \- same, but replace -1 with 1
* `(a x 0)` \- same, but with 0
* `(t x)` \- truthy for lists with more than 1 element; falsey for nil and single-element lists; error for any other type
* `(h x)` \- truthy for nonempty lists with a truthy first element; falsey for nil and lists with a falsey first element; error for any other type
* `(c()x)` \- truthy for lists; error for any other type
* `(l()x)` \- truthy for nonempty lists; falsey for nil; error for any other type
* `(l 0 x)` \- truthy for positive integers; falsey for 0 and negative integers; error for any other type
* `(v x)` \- truthy for nonzero integers; falsey for 0 and nil; error for any list that's not a valid s-expression (including any nonempty list of integers); result varies for valid s-exprs and names

Even the string builtins, though longer, could be useful under certain circumstances:

* `(string x)` \- truthy for integers, builtins, names, and lists of integers (including nil); error for lists containing anything other than integers
* `(chars x)` \- truthy for nonempty names; falsey for empty name; error for any other type

For example, here's a function that adds all the integers in a ragged list such as `(1 2 (3 4 (5) 6))`:

```
(d S(q((L)(i L(i(e(type L)(q Int))L(a(S(h L))(S(t L))))0

```

(We could write `(type? L Int)` for the type-check if we loaded the library, but that costs more bytes unless we need the library for something else.)

By the time execution reaches `(e(type L)(q Int))`, we know that `L` is either a nonempty list or a nonzero integer. We want a test that's truthy if `L` is an integer and falsey/error if `L` is a list. `(a L 0)` fits the bill:

```
(d S(q((L)(i L(i(a L 0)L(a(S(h L))(S(t L))))0

```

But in this case, so does `(v L)`. That's because:

* `v` on any integer returns the integer unchanged, and we know the integer won't be zero, so it's always truthy
* `v` on any list tries to evaluate the list as tinylisp code
* Nil evaluates to itself, but we know the list is nonempty
* A nonempty list evaluates as a function call, where the first element of the list is the function or macro. An integer isn't a valid function or macro; neither is nil; and a nonempty list will get evaluated as a function call, simply trying the same thing one layer down. Upshot: `v` will always error on a nonempty ragged list of integers.

Total savings: 13 bytes.

```
(d S(q((L)(i L(i(v L)L(a(S(h L))(S(t L))))0

```
> 5 votes

# Answer
# Take advantage of parenthesis autocompletion

The tinylisp parser will fill in missing close parens at the end of each line, provided that each of your top-level expressions is on a single line (which it should be anyway for code golf). So instead of this:

```
(load library)(d D(q((M)(i(h M)(c(h(h M))(D(map t(t M))))()))))

```

you can write this, for a savings of 5 bytes:

```
(load library
(d D(q((M)(i(h M)(c(h(h M))(D(map t(t M))))(

```

(Just make sure that your test code in the header or footer is formatted the same way, or you may get some puzzling error messages.)
> 2 votes

# Answer
# Use lambdas instead of full functions

To save a few bytes, you can make your answer a lambda instead of a full function:

```
Predecessor function:
(q (
  (n)
  (s n 1)))

Golfed:
(q((n)(s n 1)))

```

This is only useful if the function doesn't recurse.
> 2 votes

# Answer
# Use the library

Although tinylisp itself has a small set of builtins, it also comes with a standard library that adds a lot of functionality. You can access any function in the library by running `(load library)`.

The names of library functions/constants are not golfy like the builtins are, so some of them aren't worth it. For example, there's no need to load the library just to use `inc` or `dec`, since `(a 1 x)` is the same length as `(inc x)` and `(a(some-expr)1)` is shorter than `(inc(some-expr))`. For others, it depends on the use case: using `reverse` is probably shorter than reimplementing it yourself, but you may be able to restructure your code to avoid using it at all. Others, like `*`, are indispensable (multiplication isn't built in, and reimplementing it would be prohibitively long).

One drawback: there's not really any documentation besides just reading the code.
> 2 votes

# Answer
# Try switching the order of expressions

When you have multiple atoms (names/integers) next to each other, they have to be separated by whitespace. In some cases, you can rearrange the expression to eliminate the whitespace. A common example is with addition:

```
(a 1(subexpression))
(a(subexpression)1)

```

A less obvious case is when you have a function with multiple arguments. Consider a function `F` with arguments `(A B)`. If you're calling the function like this:

```
(F A(s B 1))

```

then you may be able to save a byte by taking the arguments as `(B A)` instead:

```
(F(s B 1)A)

```

(These particular examples only work if they're not at the end of a line; in that case, parenthesis autocompletion would make both options the same length. But there are instances where switching the order helps even at the end of a line.)

Reordering can be especially helpful with conditionals. Frequently, you will have a recursive function with a body structured like this:

```
(i(condition)(recursive call)(base case))

```

In some instances, you can save bytes by inverting the condition and reversing the order of the truthy and falsey branches:

```
(i(inv-condition)(base case)(recursive call))

```

For example, here's a function `F` that returns the length of a number's Collatz orbit:

```
(load library
(d F(q((N)(i(l 1 N)(a(F(i(odd? N)(a(* 3 N)1)(/ N 2)))1)0

```

If we change the condition `(l 1 N)` (truthy if N is greater than 1, falsey if N is 1 or less) to `(l N 2)` (truthy if N is less than 2, falsey if N is 2 or greater), we can switch the truthy and falsey branches and save a byte thanks to parenthesis autocompletion:

```
(d F(q((N)(i(l N 2)0(a(F(i(odd? N)(a(* 3 N)1)(/ N 2)))1

```

In this particular case, we can then save more bytes by rewriting `(a(...)1` to `(a 1(...`:

```
(d F(q((N)(i(l N 2)0(a 1(F(i(odd? N)(a(* 3 N)1)(/ N 2

```
> 2 votes

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


title: Fix a broken random function

text:
# Question
Title: Fix a broken random function
A friend has an add-on card in their computer which generates a perfectly random number from 1 to 5 inclusive. Unfortunately, they spilt cola on it somehow, and it now generates only 2's for all numbers from 1 to 4. Luckily the randomness is preserved, but 2 has a probability of 80% and 5 has a probability of 20%, and there are no 1's, 3's or 4's generated. Using this random source (call it `BrokenRand()` or something similar), write a working random number generator which produces numbers from 1 to 5 each with an equal 20% probability with the same perfect randomness as the original source.

Shortest program wins. Bonus points awarded for the minimum number of calls to `BrokenRand` impartially by a demographically-selected customer service focus consultancy, broken down by age and sex - i.e. me.

# Answer
> 11 votes
## JavaScript - 69 characters

This uses the von Neumann extractor to generate unbiased bits; the general algorithm is also described on the HotBits website. Three bits are used to form a number from 0 to 7. All numbers 5 and above are discarded, and 1 is added to each of the rest before they are printed. I made a simulation to show that this is not heavily biased.

You need to provide your own function `r()` to access the RNG.

```
 for(;;v<5&&alert(v+1))for(v=i=0;i<3;a-b&&(v*=2,v+=a<b,i++))b=r(a=r())

```

# Answer
> 6 votes
## scala 79 chars:

```
// preparation:
val r = util.Random
def defektRNG = if (r.nextInt (5) == 0) 5 else 2

(1 to 20).foreach (_ => print (" " + defektRNG))
// first impression:
// 2 2 2 2 2 2 2 5 2 2 5 2 2 2 5 2 2 2 2 2

def rnd : Int = { val k = (1 to 5).map (_ => defektRNG)
  if (k.sum == 13) k.findIndexOf (_ == 5) + 1 else rnd }

// first impression:
(1 to 20).foreach (_ => print (" " + rnd))
// 3 3 2 3 5 2 2 5 1 1 3 4 3 2 5 3 3 1 5 4
// control:
(1 to 50000).map (_ => rnd).groupBy (identity) .map (_._2.length)
// scala.collection.immutable.Iterable[Int] = List(10151, 9997, 9971, 9955, 9926)

```

Now for the real golf, defektRNG alias brokenRand is renamed to b.

```
def r:Int={val k=(1 to 5).map(_=>b)
if(k.sum==13)k.findIndexOf(_==5)+1 else r}

```

How it works: Most often, b returns a sequence of 2s. But if you do 5 calls to b, you will very often end with a result of 4x2 and 1x5, it is the second most probable event, and can be 5-2-2-2-2, 2-5-2-2-2, 2-2-5-2-2, 2-2-2-5-2 and 2-2-2-2-5.

These have in common, that the sum is 4\*2+5=13. The index of the first five can be used to define a valid random number. If there is more or less than one 5, a sum greater or lower 13, repeat.

A counter in 'rnd' aka 'r' can show how many calls are necessary in average to produce the numbers. There are 121 200 calls to r for 50 000 random numbers, which is not impressing. :)

# Answer
> 3 votes
## \>\<\> (Fish) \- 55 bytes

Updated to use the same algorithm as @user unknown in his scala answer

```
<v?=d+&:i&+&:i&+&:i&+&:i&:i
 0
 >1+$5(?vnao;
 ^      <

```

It expects the broken generator to be connected to stdin; here's the python script I used. The code matches the current Fish spec, but I used a modified version of the old interpreter.

```
bash:$ for i in $(seq 1000); do ./bad_rand.py | ./myfish.py rand.fish; done >res.txt
bash:$ for i in $(seq 5); do echo -n "$i : "; grep -c $i res.txt; done
1 : 193
2 : 204
3 : 198
4 : 206
5 : 199

```

I'd do a bigger sample but it's slow.

# Answer
> 3 votes
# GolfScript, 23 bytes

Late answer, but since this just happened to pop up on the front page...

```
0{;[{r}5*].5?)\5-,4-}do

```

Uses the same algorithm as user unknown's Scala solution. Assumes that the biased random number generator is given as a GolfScript subroutine named `r`; you can define a suitable biased RNG yourself e.g. as:

```
{5rand!3*2+}:r;

```

Here's a quick test demonstrating lack of bias. Unfortunately, the online GolfScript server is kind of slow, so I had to cut the demonstration down to just 100 samples to make it complete on time. If running the test locally with the GolfScript interpreter, try increasing the `100*` to `1000*` or even `10000*`.

(The GolfScript server also sometimes randomly freezes and times out anyway. If this happens for you, trying again usually solves it. It happens with other code too, and only happens on the server, not on my own computer, so I'm confident that it's a problem with the server and not with my code.)

# Answer
> 2 votes
# Python 3, 119 bytes

```
def F():
  l=[]
  while 1:
    l=[]
    for i in range(5):
      l.append(B())
    if l.count(5) == 1:
      return l.index(5)

```

Could be golfed to below 100 probably, but it's decent for now. Have no idea how a Python answer (or one with this method) hasn't popped up. Assumes the broken random function is B.

---
Tags: code-golf, random, probability-theory
---