# Question
Title: I transpose the source code, you transpose the input!
*Rip-off of a rip-off of a rip-off of a rip-off. Go upvote those!*

Your task, if you wish to accept it, is to write a program/function that outputs/returns its input/argument¹. The tricky part is that if I transpose your source code², the output/result must be transposed too.

1. You may choose which kind of 2D data your solution can accept. For example a list of lists, a matrix, a list of strings, etc. State which one(s) it handles. You may assume that the input will always be rectangular and will have a length of 1 or more along each dimension.
2. For the purposes of transposing, short lines in your source code will be considered as padded with trailing spaces until it is rectangular, however, these padded trailing spaces do not contribute to your code length.

Since this is , the target is to optimize the byte count of the original source code (not the transposed version).

## Examples

Let's say your solution takes a numeric matrix and your source code is

```
AB
DEF

```

and its input/argument is `[[1,2],[3,4],[5,6]]`. If I write

```
AD
BE
 F

```

instead and run it, the output/result must be `[[1,3,5],[2,4,6]]`.

Let's say your solution takes a linefeed-separated string and your source code is

```
ABC

```

and its input/argument is `"96\n"`. If I write

```
A
B
C

```

instead and run it, the output/result must be `"9\n6\n"`.

# Answer
# Python 3 \+ numpy, 45 bytes

```
lambda\
a:a
ma= """
b.    "
dT"   "
a "
\ """

```

Try it online!

*Thanks to @EriktheOutgolfer pointing out a bug of the previous version*

## Transposed:

```
lambda\
a:a.T
ma= """
b     "
d "   "
a "
\ """

```

Try it online!

The functions take a numpy matrix as input and output a numpy matrix. The solution does not rely on comments like many other solutions do but instead exploits multi-line strings.
> 28 votes

# Answer
# Jelly, 2 bytes

Input is a list of lists. Thanks to Luis Mendo and Nick Kennedy for improving the answer.

```
ZZ

```

Try it online! Try it transposed!

The program transposes the input twice, returning the original input. The transposed version ignores the first line and only transposes once.
> 15 votes

# Answer
# , ~~5~~ 4 bytes

```
#t
I

```

Try it online!

An R function, either the identity function `I` or the transpose function `t` when transposed. Footer on TIO shows output of both.

Thanks to @RobinRyder for saving a byte!
> 13 votes

# Answer
# C (gcc), ~~209~~ ~~205~~ ~~203~~ 201 bytes

## Normal

```
f(n,L,r,c)char**L;{for(c=0;0?L+  c:c<n;c+=puts(""))for(r=0;0?r :L[c][r];r++)putchar(L[ c ][ r ]);}/*
          \\\      \\      1 [0][]      \ \\\  \   \\      1 <n          \  \\\\\\   r+-c c+-r    */

```

Try it online!

## Transposed

```
f
(
n
,
L
,
r
,
c
)
c\
h\
a\
r
*
*
L
;
{
f\
o\
r
(
c
=
0
;
01
?
L[
+0
 ]
 [
c]
:
c
<
n
;
c
+\
=
p\
u\
t\
s
(
"\
"
)
)
f\
o\
r
(
r
=
0
;
01
?
r<
 n
:
L
[
c
]
[
r
]
;
r
+\
+
)
p\
u\
t\
c\
h\
a\
r
(
L
[r
 +
c-
 c
]
[c
 +
r-
 r
]
)
;
}
/*
*/

```

Try it online!
> 11 votes

# Answer
# Haskell, 51 bytes

This version is valid, but will not halt when given `[]` as input.

```
f
--(:[|,<zabf=]f
--abx(y-i$]
-- ):x) pf;x[:x
 y =y

```

Try it online!

### Transposed, 75 bytes

```
f---
 ---y
 (a
 :b)=
 [x:y
 |(x
 ,y)
 <-
 zip
 a$f
 b];
 f x
 = [
 ] :
 f x

```

Try it online!

# Haskell, 51 bytes

This version is valid, but crashes with `[]` as input for the transposed version.

```
f
--d[(idi)z[.]d!0
-- m!)|,<i0.$ !]
-- a! (_-p
 p=p

```

Try it online! Transposed

# Haskell, ~~75~~ ~~67~~ 57 bytes

*At least 7 bytes saved thanks to Ørjan Johansen*

This version outputs `[]` when given `[]` as input.

```
f
--[[d(i<di)z[.$!0
--]]=!)$|,<i0.d!]
-- ;[! >(_-p ]
 f=f

```

Try it online!

Transposed
> 8 votes

# Answer
# Python 3, 51 bytes

```
lambda\
a:a
mz= '''
bi'   '
dp'   '
a('
 *
 a
\)'''

```

Try it online!

Based on Joel's approach. The input is a `tuple` of `tuple`s, and the output is a `zip` (converted to a `tuple` over TIO for better visibility).

Transposed:

```
lambda  \
a:zip(*a)
ma='''  '
b       '
d '     '
a '
\ '''

```

Try it online!
> 7 votes

# Answer
# Perl 6, ~~20~~ 11 bytes

```
#&
*[
#Z
 ]

```

Try it online!

### Transposed

```
#*#
&[Z]

```

Try it online!

Both functions work on list of lists.

`*[ ]` is a WhateverCode returning the zen slice of its argument, effectively the identity function.

`&[Z]` is the zip operator.
> 5 votes

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

```
//m0()m  ]
//=](=a  )
//>.a>p( )
//mm,m/aa
//[ap./=[
   p  =>p

```

Try it online!

Improved with a different layout

```
/////
/////
m=>m[
0].map
((a,p
)=>m.
map//=
  (a=>
   a[p
]))

```
> 5 votes

# Answer
## Haskell, ~~185~~ 161 bytes

```
t i
 =
 i
af

 n m
 u a e i
 l p s d
 lu h=u
 (
 h
 e
 a
 d

 a
 )
 t
 h
 e
 n
 [
 ]
 e
 l
 s
 e

 m
 a
 p

 h
 e
 a
 d

 a
 :
 t
 (
 m
 a
 p

 t
 a
 i
 l

 a
 )

```

Try it online!

Transposed:

```
t  a
 =if null(head a)then[]else map head a:t(map tail a)
i       u
     map
        h
      es=
        u
      id

```

Try it online!

No comments, no string literals, just some additional function definitions.

Edit: -24 bytes thanks to @Ørjan Johansen.
> 5 votes

# Answer
# PHP (7.4), ~~114~~ ~~86~~ 70 bytes

My first ever experience doing something like this in PHP, there must be a better way I cannot see! Input is an array of arrays like `[[1,2],[3,4],[5,6]]`.

### Normal:

```
fn($a)=>$a/*
nu         /
(l
$l
a,
).
=.
>.
a$
ra
r)
a/
y*
_
m
a
p
(*/

```

Try it online!

### Transposed (space padded):

```
fn($a)=>array_map(
null,...$a)/*    *
(                /
$
a
)
=
>
$
a
/
*/

```

Try it online!
> 4 votes

# Answer
# Japt, 2 bytes

```
ÕU

```

Try it | Transposed

```
ÕU     :Implicit input of string/array U
Õ      :Transpose U
 U     :Original U
       :Implicit output

```

```
Õ\nU     :Implicit input of string/array U
Õ        :Transpose U
 \n      :Reassign to U
   U     :Newly transposed U
         :Implicit output

```
> 4 votes

# Answer
# Brain-Flak (BrainHack), ~~382~~ ~~375~~ 337 bytes

*No comments!*

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

```

Try it online!

For the input the first two numbers are the dimensions of the matrix and the remainder is the contents of the matrix. Output is given in the same format.

## Transposed

# Brain-Flak (BrainHack), 465 bytes

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

```

Try it online!
> 4 votes

# Answer
# Charcoal, 19 bytes

```
Ａ¿⁰«
‖⁰¿
↗⁰
¿⁰
⁰¿
«

```

Try it online! Takes input as an array of strings. Explanation:  implicitly prints the explicit input, while `¿⁰` is a conditional, with `0` as the condition, which is therefore always false. `«` then starts a block of meaningless Charcoal code which never gets executed. (It might be possible to remove some of those bytes but in that case I'm not sure whether Charcoal would parse the program correctly.) Transposed, 17 bytes:

```
Ａ‖↗¿⁰«
¿⁰⁰⁰¿
⁰¿
«

```

Try it online! Explanation: Much the same as the previous program, except for the addition of the transpose command `‖↗`.

I have an alternative solution where both the original and transposed program are 18 bytes:

```
Ａ⊞υ”y
‖υ⁺y
↗⁺
⊞⁺
υ

```

Try it online! Explanation:  as above; `⊞υ` pushes a value to the predefined empty list (which doesn't affect the output); `”y` begins an arbitrary string (ends at end of program or matching ). Transposed:

```
Ａ‖↗⊞υ
⊞υ⁺⁺
υ⁺
”y
y

```

Try it online! Explanation: `Ａ‖↗` as above; `⊞υ` as above; the minor difference here is that I'm pushing concatenations of smaller strings, since I don't want to repeat the .
> 3 votes

# Answer
# Haskell, ~~153~~ 144 bytes

(thanks, Sriotchilism O'Zaic)

```
f
 [
 ]=
   [
   ];
    f(
     x:
      l)
       =(
        :)
         x l
-- :   z $
-- f   i f
-- [   p
-- ]   W
--     i
--     t
--     h

```

Try it online!

Try it transposed!
> 3 votes

# Answer
# Ruby, 35 bytes

```
#-sz##
->hip{
 hip  }
#{f
#ht*
#..h

```

Try it online!

Hip to be square! (Almost)

Accepts ruby matrices as input (arrays of arrays)
> 2 votes

# Answer
# APL (Dyalog Unicode), 7 bytes

```
{⍵
⍉
⍵}

```

Try it online!

Transposed:

```
{⍉⍵
⍵ }

```

Probably a rather boring answer, but anyway here it goes.

The inline function definition `{...}` can span multiple lines. In this case, each line is sequentially executed, but any line without an assignment  immediately returns its computed value. So the first function returns  while the second returns `⍉⍵`.

Even more boring answer would be the comment abuse:

# APL (Dyalog Unicode), 4 bytes

```
⍝⍉
⊢

```

No TIO is necessary, I guess...
> 2 votes

# Answer
# Wolfram Language (Mathematica), 13 bytes

```
#&(*
 *)
\

```

Try it online! / Transposed
> 1 votes

# Answer
# 05AB1E, 4 bytes

```
øø
q

```

Try it online.

```
øq
ø

```

Try it transposed.

**Explanation:**

Unlike some of the other languages, newlines are simply ignored in 05AB1E, so I don't think a 2-byter is possible (although I'd love to be proven wrong).

```
ø    # Transpose the (implicit) input
 ø   # Transpose it back
  q  # Stop the program (and output the top of the stack implicitly as result)

ø    # Transpose the (implicit) input
 q   # Stop the program (and output the top of the stack implicitly as result)
  ø  # No-op, since the program has already stopped

```
> 1 votes

# Answer
# Clean, 64 bytes

```
//i$
//mp
$ p=p
//ot
//rr
//ta
// n
//Ss
//tp
//do
//Ls
//ie
//b

```

Try it online!

```
//$//////////
// //////////
import StdLib
$p=transpose
  p

```

Try it transposed!
> 1 votes

# Answer
# Runic Enchantments, 88 bytes

```
vrlril1-{)?\:',=4*?~r0[
i! '${U [0r/?*7̸0l{$
$ka6 ̹\!$,'/;? =  ̹
'              ̸

$

```

Try it online!
Try it transposed!

Input is *space separated* for each value and *comma separated* for each row (newlines are optional) and supports both strings and (non-zero) numbers. This makes parsing the input easier as input is automatically broken by spaces and newlines. So for example, the input:

```
1 2 3 , 4 5 6 , 7 8 9

```

Would be represented in nested array form as `[[1,2,3],[4,5,6],[7,8,9]]`. Minimal support for jagged arrays (only the last one can be short), but as inputs are expected to be rectangular, this satisfies that requirement.

Output is represented in the same format (transposed version outputs with newlines, but its zero bytes different to use a space instead). Normal version has a trailing space, transposed version has a trailing comma and newline (due to the difficulty of determining when there is no more data to print).

Normal version does have modifier characters in weird places (eg. `7̸0`), but this is due to needing them in the right place when the source is transposed and the normal execution only utilizes the leftmost column of instructions.

### Explanation

Explanation of the transposed source will be in a non-transposed form. Arrows will represent IP directionality at the entrance and exit of various blocks.

```
→rlril1-{)?\:',≠4*?~r0[    Initial position. Read and parse input.
           ↓               Input loop exit and direction

```

The input is read, and when a `,` character is found, a new substack is pushed. This allows each stack to hold each row separately in memory. Enters next section from the top.

```
           ↓
.. '${̹L [0r/?*7≠0l{̹$       When no more input:
      ↑    ↓

```

`[0` (executed leftwards) sets up a an empty stack to act as a boundary between the first row and the last row and then rotates to the first stack () and starts printing elements and rotating stacks. The `i!` is not executed and `{̹L [0r` is only executed once. When a zero-size stack is found, the loop exits.

```
      ↑    ↓
$ka6  \!$,'/;?             Row separation formatting

```

When the empty-stack is found, a `,` and newline are printed, and value loop is re-entered. Execution order (mirrored for readability) where `.` is an un-executed command: `\',$!.6ak$?....../`. Changing `ak` to `'<space>` would print spaces instead of newlines.

Execution halts when the program attempts to write from an empty stack; this is why only last-row jagginess works correctly and why there is a trailing `,` in the output: the comma has already been printed before the program knows that there's no more data.
> 1 votes

# Answer
# Vyxal, 2 bytes

```
#∩

```

Try it online or try it online transposed.

Receives a list of lists (a list of strings will work too).

*-2 bytes thanks to lyxal*
> 1 votes

# Answer
# Python 3, ~~118~~ 95 bytes

Input and result are lists of tuples.

```
f=lambda i:i;"""
=              "
l              "
a
m
b
d
a

i
:
[
*
z
i
p
(
*
i
)
]
;
"
"
"""

```

Try it online!
> 0 votes

# Answer
# Cjam, 13 bytes

```
qo
~
z
`

```

Try it online!

## Transposed version:

```
q~z`
o

```

Try it online!

## Input format

The input format is the standard CJam array format: `[[1 2] [3 4]]`

# No crash version, 12 bytes

The normal version crashes *after* printing the array. A version which doesn't crash would be:

```
qo{
~
z
` };

```

Try it online!

or transposed:

```
q~z`
o
{  };

```

Try it online!

There are probably a few extra bytes that can be saved, i accidentaly worked on the transposed version first, which led to a few extra linebreaks and it's been a long time since i last used CJam. Any improvements welcome.
> 0 votes

# Answer
# Zsh, 75 bytes

```
  <<<${(F)@}
fa<
o[<
r+$
 +{
si(
;]F
i+)
==a
&$}
&s
r[
ei
p+
e1
a]
t

$
#
s

```

TIO: Normal Transposed

The garbage below the main print is harmless, it prints an error when encountering a newline after `fa<` and exits. 86 bytes to remove that error.

The transposed version is here. After printing it errors on seeing `<` at the end of a line and exits.

```
 for s;i=&&repeat $#s
 a[++i]+=$s[i+1]
<<<${(F)a}
<
<
$
{
(
F
)
@
}

```
> 0 votes

# Answer
# Pyth, 10 bytes

```
CCQ "
Q

"

```

Try it online!

# Transposed

```
CQ "
C
Q

"

```

Try it online!

## Explanation

The program transposes the input twice, returning the original input. The transposed version only transposes once.
> 0 votes

---
Tags: code-golf, matrix, source-layout
---


# Question
Title: Double it? Then halve it! But multiply it? Then divide it!
Idea from the doubler challenge, this may be more difficult.

The program should output a positive integer or decimal point value higher than 0.

If I duplicate the source code, the output should halve the original integer or decimal point value.
But the trickier part is: If I duplicate your code any integer value \\$n\\$ times, the output should divide by the original integer or decimal point value \\$n\\$ times too! Edit: As per my mistake (see Jonah's comment) you can divide by `2^n` too.

# Rules

* The output must be printed to the program's default STDOUT.
* The initial source must be at least 1 byte long.
* Both the integers (or decimal point values) must be in base 10 (outputting them in any other base or with scientific notation is forbidden).
* Your program must *not* take input (or have an unused, empty input).
* Outputting the integers with trailing / leading spaces is allowed.
* You may not assume a newline between copies of your source.
* This is , so the shortest (original) code in each language wins!
* **Default Loopholes** apply.

### Example

Let's say your source code is `ABC` and its corresponding output is `2`. If I write `ABCABC` instead and run it, the output must be `1`. If I write `ABCABCABC` instead and run it, the output must be `0.5` (or `0.3333333`).

This uses uses @manatwork's layout.

```
/* Configuration */

var QUESTION_ID = 222818; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 96037; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
```

Disclaimer: Example and Rules from the original challenge with modifications.

# Answer
> 14 votes
# Jelly, 3 bytes

```
o⁹H

```

Try it online!

Try it online!Try it online!

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

## How It Works

```
o⁹H - Main link. Takes implicit argument of 0
o⁹  - Logical OR of 0 and 256
  H - Halve to 128

o⁹Ho⁹H - Main link. Takes implicit argument of 0
o⁹     - Logical OR of 0 and 256
  H    - Halve to 128
   o⁹  - Logical OR of 128 and 256
     H - Halve to 64

```

And so on

# Answer
> 8 votes
# , 9 bytes

```
a=T=T/2;T

```

Try it online!

`T` is a (built-in) shortcut for `TRUE`, which is automatically initialized to a numeric value of `1`. We redefine it to half what it was before using `T=T/2`.  outputs the values of statements consisting of unassigned expressions, so `T` on its own outputs the current value of `T` (now equal to `0.5` if there's only one copy of the code).

When we double (or triple...) the code, the final `T` is appended with `a=T=T/2` to become `Ta=T=T/2`: so, the previously-final unassigned `T` now becomes an assignment for the variable `Ta`, which we will never use, but which stops the value from being outputted. `T` is then halved (again), and its value (now `0.25`) output, unless there's another copy of the code...

# Answer
> 7 votes
# Bash, 23

```
trap echo\ $[8>>n++] 0

```

Try it online!

Try it online!Try it online!

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

# Answer
> 6 votes
# Python 2, ~~42~~ 41 bytes

```
print.5**(len(open(__file__).read())/41)#

```

Try it online!

Read the source file and divide it's byte count by 41 (the length of the original code). Then raise 2 to that power and print it.

*thanks to Jonathan Allan for -1 byte*

# Answer
> 6 votes
# Python 2, 28 bytes

```
+0and'',;True/=2.
print True

```

Try it online! \- Outputs `0.5`
Try it online! x2 \- Outputs  `0.25`
Try it online! x3 \- Outputs  `0.125`

## Explanation

The built-in constant `True` is modified to be halved after every duplication with `True/=2`. This prevents the hassle of declaring a new variable. The tricky part is making sure that `True` is outputted only once. Now is where the `+0and'',` comes in. It basically fills every `print` statement with `print True+0and'',`, which outputs a space. Then on the very last line, `print True` will output the correct result.

# Answer
> 5 votes
# Desmos, 5 bytes

Original - Outputs `0.5`

```
(1/2)

```

Doubled - Outputs `0.25`

```
(1/2)(1/2)

```

Tripled - Outputs `0.125`

```
(1/2)(1/2)(1/2)

```

Try It On Desmos!

# Answer
> 4 votes
# Perl 5 (`-0777l070p`), ~~10~~, 6 bytes

```
;$\/=2

```

switches :
-0777 : undef input record separator (read whole input once).
-l070 : set output record separator to `070` octal character 8.
-p : to print

`$\/=2` : divide output record separator (coerced to number) by 2

Try it online!

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

# Answer
> 4 votes
# JavaScript, 44 bytes

Uses a custom getter property `o.l` to execute `console.log`. Duplicating the program produces the useless code `o.lo={...}`.

```
o={get l(){console.log(o.x)},x:2};o.x/=2;o.l

```

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

---

# JavaScript, 44 bytes

Same approach, but using a top-level variable instead of a property.

```
o={get l(){console.log(x)}};var x=x/2||1;o.l

```

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

# Answer
> 3 votes
# Japt, 4 bytes

```
I*=½
I    // Builtin variable, initially equals 64
 *=  // times equals
   ½ // half.

```

Try it here.

# Answer
> 3 votes
# Charcoal, 6 bytes

```
⎚≦⊘φＩφ

```

Try it online! Outputs 500. Try it online! Try it online! Outputs 250. Try it online! Try it online! Try it online! Outputs 125. Explanation:

Clear canvas of previous iterations.

```
≦⊘φ

```

Halve the predefined variable for 1,000.

```
Ｉφ

```

Print its current value.

# Answer
> 3 votes
# , ~~22~~ 17 bytes

```
cat(T<-T/2,"\r");

```

Try it online!

Carriage return doesn't work as intended in TIO, but on my machine the next output flushes the previous one.

*-5 bytes using @Dominic's approach*

# Answer
> 2 votes
# Befunge-93, ~~32~~ 30 bytes

```
82>:0\g7%!#v_\.@
  v\/2 \+2 <

```

Try it online!

To reduce the size, the code starts with 8 and does what is required. However, at some point the output will be always zero, due to the lack of the fp division.

Since it's not guaranteed that the copy will have a new line char, I have included the new line char at the end of the second line in the byte count (it's really required for this to work).

Code need to be back to back for it to work (I hope this is acceptable), e.g.:

```
82>:0\g7%!#v_\.@
  v\/2 \+2 <
82>:0\g7%!#v_\.@
  v\/2 \+2 <

```

will output 4.

Edit: saved 2 bytes by changing the comparison from subtraction to modulo.

## Explanation

```
82                    Push 8 and 2
>                     Execution goes right (this is where the other copies of the program start executing)
:                     Duplicate the top of the stack (this is n*2, the line of the next copy of the program)
0g                    Push 0 and get the char in (0,n*2). If there are other copies
                      of the program, this will read '8', otherwise ' ' (space)
7%!                   Push 7, do modulo, and not the result. 8 is 56 in ascii, 56%7=0; with space char is 32%7≠0
#v_\.@                If not zero, go down, if zero, swap the stack, print, and end the program
<                     If not zero before, continue left.
\+2                   Add two to the top of the stack (the line of the next copy of the program) and swap (executed right to left)
\/2                   Divide the future output by 2 and swap the stack to get the correct order
v                     Continue the execution in the code below (matches the > at the beginning).

```

# Answer
> 2 votes
# Javascript ES6, 60 bytes

`[0];b=function(){console.log(a)};b[0]=Map;var a=a/2||1;new b`

Try it online!

Makes use of the fact that we can call a function without parantheses using `new`, and the fact that brackets, or computed member access has a higher precedence than `new`

# Answer
> 2 votes
# Scratch, ~~42~~ 43 bytes

Try it online!

I'm pretty certain that this is optimized:

```
when gf clicked
change[D v]by(1
say((1)/(D

```

Alternatively, 5 blocks.

# Answer
> 2 votes
# Pip, 5 bytes

```
h:h/2
```

Attempt This Online!

Attempt This Online!Attempt This Online!

Attempt This Online!Attempt This Online!Attempt This Online!

# Answer
> 2 votes
# Desmos, 1 or 2 bytes

```
½

```

outputs `0.5`. Inputting a string consisting of multiple `½` characters multiplies them together, giving ½^n.

I'm not sure if this should count as 1 or 2 bytes - the `½` character is 2 bytes in UTF-8, but is present in many extended ASCII tables as well, and Desmos doesn't take files as input so it's not tied to any particular encoding afaik.

# Answer
> 1 votes
# Pyth, ~~8~~ 6 bytes

```
e[=cT2

```

Try it online!

# Explanation

```
e    # Last element of list
[    # Begin list
=    # Set to
cT2  # Float division T/2

```

*thanks to FryAmTheEggman for -2 bytes*

# Answer
> 1 votes
# , 18 bytes

```
a=.1+a"_ ::0:0
%a

```

Try it online! \- Returns 1

Try it online!Try it online! \- Returns 0.5

Try it online!Try it online!Try it online! \- Returns 0.33333

This is the body of an explicit function in J. Note that while J does not have 0 argument functions, this function ignores its input, and so should not be in violation of the "no input" rule.

# how

* `a` is a local variable, and `a"_` is a verb that returns the value stored in `a`.
* `::0` says that if the verb `a"_` errors while executing, return `0`. This will only happen on the first line, when `a` is undefined. After this line is executed the first time, `a` will be set to `1`, since the first line will resolve as `1+0`.
* On the next run of `1+a"_ ::0:0`, `a` will already be 1, and so it will resolve as `1+1`, or `2`.
* Meanwhile `%a` -- the reciprocal of `a` -- will be a no-op on all lines in the middle of the function (it won't result in any output). However, the final instance of `%a` is the return value of the function.

# 2^n version, 19 bytes

```
1: :*g(g=.1r2"_ :*)

```

Try it online!

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

This starts with `1/2`, and divides by 2 one more time each time the source is repeated.

This works by combining J trains with verbs that behave differently depending on if they are being called with 1 or 2 arguments. Though again, the input itself is always ignored.

# Answer
> 1 votes
# 05AB1E, 3 bytes

*Ties caird coinheringaahing's Jelly answer for #1.*

```
X;U

```

Try it online!

Try it online!Try it online!

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

```
X;U  # full program
  U  # set X to...
X    # variable (initalized to 1)...
 ;   # divided by 2
     # (implicit) push last popped value
     # implicit output

```

# Answer
> 1 votes
# Vyxal `H`, 1 byte

```
½

```

Try it Online!

Try it Online!Try it Online!

Try it Online!Try it Online!Try it Online!

Vyxal flag abuse FTW.

---
Tags: code-golf, source-layout
---


title: Iterative Smallest Complement

text:
# Question
Title: Iterative Smallest Complement
For this challenge, we will define the "complement" of a list of integers `A` as being any list `B` such that the union of `A` and `B` is a list of consecutive integers with no repeats.

In other words, `B` is the complement of `A` if

* `B` has all of the integers between the minimum and maximum of `A` which are missing from `A`, and
* `B` has none of the integers present in `A`

For example: `[2, 4, 6, 7]` is a complement of `[1, 3, 5, 8, 9]`, `[1, 3, 5]`, and `[3, 5]`, but it is *not* a complement of `[1, 2, 3, 5]` or `[1, 3, 5, 9]`.

Worth noting: For a list of consecutive integers, a complement may be the empty list, as no integers are "missing" between the minimum and maximum.

Any given list of integers with no repeats has infinitely many complements (proof left as an exercise for the reader), but has exactly one smallest complement, which itself has this very same property.

For example, if we start with the list `[1, 2, 3, 5, 8, 13]` and repeatedly find the smallest complement, we get this chain of lists:

```
[1, 2, 3, 5, 8, 13]
[4, 6, 7, 9, 10, 11, 12]
[5, 8]
[6, 7]
[]

```

The smallest complement of the empty list is the empty list, so we can stop here.

## Challenge

Given a list of non-repeating *positive* integers `A`, output the `A`'s smallest complement, followed by that list's smallest complement, all the way until the empty list.

## Rules

* You may choose to include or omit the input list in your output.
* You may choose to include or omit the empty list in your output.
* The input list will always have complements. (i.e. the list will never contain duplicates)
* The input will be sorted.
* The input will never be the empty list.
* The input will never contain 0 or negative integers. (although they are well defined)
* This is , so shortest code in bytes wins.

## Examples

Outputs will include both the original list and the empty list, for clarity

```
input => output
[1, 3, 5, 7, 9] => [[1, 3, 5, 7, 9], [2, 4, 6, 8], [3, 5, 7], [4, 6], [5], []]
[5, 10, 15, 20] => [[5, 10, 15, 20], [6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19], [10, 15], [11, 12, 13, 14], []]
[5, 10, 15] => [[5, 10, 15], [6, 7, 8, 9, 11, 12, 13, 14], [10], []]
[1, 2, 6, 7, 11, 12] => [[1, 2, 6, 7, 11, 12], [3, 4, 5, 8, 9, 10], [6, 7], []]
[1, 2, 3] => [[1, 2, 3], []]
[5, 6, 7] => [[5, 6, 7],  []]

```

# Answer
> 8 votes
# , ~~45~~ 44 bytes

```
f=function(r)r&f(print(setdiff(r:max(r),r)))
```

Attempt This Online!

Derived without peeking at pajonk's R answer, but ended-up with a pretty similar approach ...

# Answer
> 6 votes
# Husk, 5 bytes

```
U¡S-…

```

Try it online!

```
 ¡     # Apply function repeatedly, collect values in infinite list:
   -   # list difference of
  S    # last result (or input for first iteration)
  S …  # and last result with gaps filled with numeric ranges;
U      # Finally, get longest prefix of the list with all unique elements.

```

# Answer
> 5 votes
# , ~~55~~ 50 bytes

*Edit: -5 bytes thanks to @Giuseppe.*

```
f=function(v)if(s<-setdiff(v:max(v),print(v)))f(s)

```

Try it online!

Prints the inital list but not the empty one. Terminates with an error.

In ==4.1 replace `function` with `\` to achieve **43 bytes** (still longer than @Dominic van Essen's answer working in \>=4.1 after also implementing this notation there). This doesn't work in \>=4.2.0 (and consequently in ATO), due to introduction of a strict check for argument length for `if`.

### Explanation outline

1. Compute sequence from min to max with `v:max(v)` (`:` takes first element of a vector and as input is sorted, this is the minimum).
2. Take set difference `setdiff` of this and input (we print it here and `print` conveniently returns its argument).
3. Assign this to `s`.
4. `if` takes the first element of a vector and checks if it's truthy (not `0` or `FALSE`) and errors for empty input. Essentially, check if `s` is nonempty.
5. Recurse.

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

Includes input and empty list (`!0`) in the output.

```
{(x,/x_!0^*|x)^x}\

```

Try it online!

`{ ... }\` Converges; Call the lambda repeatedly until the value doesn't change.
`( ... )^x` The range computed in the parentheses without the elements in x.

`*|x` Last (largest) value in x. This returns `0N` if x is empty, then `0^` replaces `0N` with 0.
`!` range from 0 to this value value (exclusive).
`x_` cut this range at the indices given by x. Because the first slice is omitted, this gets rid of the numbers up to the minimum of x.
`x,/` Flatten the cutted list, prepending x. We need to prepend x to get the shape right for the empty list.

Instead of *converges* we could use *whiles* to avoid dealing with the empty list. This would save 3 bytes in the lambda, but add 4 on the outside:

```
(::){(,/x_!*|x)^x}\

```

Try it online!

# Answer
> 4 votes
# Vyxal, 7 bytes

```
≬₌gGṡ⊍İ

```

Try it Online! or Try all the tests

Input list not included, empty list is.

## Explained

```
≬₌gGṡ⊍İ
≬-----     # Next three elements as a function:
 ₌gG       #   Get the smallest and largest item of the argument
    ṡ      #   Create an incluse range between those values
     ⊍     #   and set xor with the original argument
      İ    # Repeat that function until the result is no longer unique, collecting results

```

# Answer
> 4 votes
# Python 3, 56 bytes

```
f=lambda l:l and[l]+f(sorted({*range(l[0],l[-1])}-{*l}))

```

Try it online!

# Answer
> 4 votes
# , 18 bytes

```
(-.~{:-.&i.{.)^:a:

```

Try it online!

thejonymyster has allowed this output... since J only supports heterogeneous lists with boxing, and since 0 is disallowed in the input, I am displaying the output as a homogeneous matrix with 0 fill, so that the successive lists are simply each row, without the 0 fill:

```
1 2 3 5  8 13  0
4 6 7 9 10 11 12
5 8 0 0  0  0  0
6 7 0 0  0  0  0
0 0 0 0  0  0  0

```

Note that, if desired, we could add boxing for 3 more bytes.

* `(...)^:a:` Until a fixed point is reached, collecting results, do the following...
* `-.~{:-.&i.{.` Remove `-.` the input from `0 1 ... <largest element - 1>` without `0 1 ...<smallest element - 1>`

# Answer
> 4 votes
# Pyth, ~~9~~ 8 bytes

```
#p=-rhQe

```

Try it online!

```
#p=(Q)-rhQe(QQ)
              // Implicitly initialize Q as the input
#             // Repeat until an error occurs:
     rhQeQ    // Range from first to last element of Q...
    -     Q   // ...with elements of Q removed
  =Q          // Set Q to the result
 p            // Print

```

# Answer
> 4 votes
# Zsh, 44 bytes

```
<<<$@
a=({$1..$@[$#]})
(($#))&&$0 ${a:|argv}

```

Try it online!

```
<<<$@             # output arguments
a=({$1..$@[$#]})  # all integers between first and last args
(($#)) &&         # if there was at least one argument
    $0 ${a:|argv}  # recurse with set difference between $a and the arguments

```

Using $argv is needed in the `${a:|b}` notation, `${a:|@}` does not work.

# Answer
> 3 votes
# Factor \+ `math.unicode`, ~~51~~ 50 bytes

```
[ [ 3 dupn . minmax [a,b] swap ∖ ] until-empty ]

```

Input list is included; empty list is omitted.

Try it online!

* `[ ... ] until-empty` Call `[ ... ]` on the input repeatedly until it is empty.

```
         ! { 1 3 5 7 9 }
3        ! { 1 3 5 7 9 } 3
dupn     ! { 1 3 5 7 9 } { 1 3 5 7 9 } { 1 3 5 7 9 }
.        ! { 1 3 5 7 9 } { 1 3 5 7 9 }   ((output to stdout))
minmax   ! { 1 3 5 7 9 } 1 9
[a,b]    ! { 1 3 5 7 9 } { 1 2 3 4 5 6 7 8 9 }
swap     ! { 1 2 3 4 5 6 7 8 9 } { 1 3 5 7 9 }
∖        ! { 2 4 6 8 }    ((set difference))
         !   ((and so forth...))

```

# Answer
> 3 votes
# JavaScript (ES10), 66 bytes

The empty list is included. The input list is not.

```
f=a=>a+a&&[b=a.flatMap(p=g=v=>++p-v?[p,...g(v)]:(p=v,[])),...f(b)]

```

Try it online!

Or as **ES6** (also 66 bytes):

```
f=a=>a+a&&[a.map(p=g=v=>++p-v?g(v,b.push(p)):p=v,b=[])&&b,...f(b)]

```

Try it online!

# Answer
> 3 votes
# BQN, 23 bytes

```
{¬∘∊⟜⊸/⊑⊸↓↕⌈´•Show}

```

Try it here!

Terminates with error.

## Explanation

Input is *x*.

* `•Show` output *x*
* `↕⌈´` exclusive range from 0 to max of *x*
* `⊑⊸↓` drop (first element in *x*) elements
* `¬∘∊⟜⊸/` filter elements not in *x*
* recurse

# Answer
> 3 votes
# Haskell, ~~65~~ 49 bytes

*-10 bytes thanks to @Lynn*

```
g[]=[];g x=x:g[e|e<-[head x..last x],notElem e x]

```

# Answer
> 2 votes
# Charcoal, 15 bytes

```
Ｗθ«≔⁻…⌊θ⌈θθθ⟦Ｉθ

```

Try it online! Link is to verbose version of code. Does not output the initial list. Would output the final list except that Charcoal has no output for an empty list. Explanation:

```
Ｗθ«

```

Repeat until the list is empty.

```
≔⁻…⌊θ⌈θθθ

```

Subtract the list from the range of its lowest to highest elements.

```
⟦Ｉθ

```

Output the new list with separation from the previous list.

# Answer
> 2 votes
# Burlesque, 39 bytes

```
1{sa1.>{Jl_g_/vjr@j\\}q{}IE}C~J{}Fi+..+

```

Try it online!

The only bit which is required to compute this is

```
1{Jl_g_/vjr@j\\}C~

```

Unfortunately, this crashes on reaching a 0/1 element block because it tries to pull head/tail from an empty list.

```
1        # Number of elements Continue forever keeps from the top of the stack
{
 sa1.>   # Length of block at least 2 elements
 {
  J      # Duplicate
  l_g_/v # Get head and tail of list
  jr@    # Range head..tail
  j\\    # List difference with original
 }
 q{}IE   # If list too short return empty list
}C~      # Continue forever
J{}Fi    # Find the first occurrence of empty list
+..+     # Take that many (including an empty element)

```

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
Δ=WsàŸyK

```

Outputs the intermediate lists separately to STDOUT; includes both the input-list and empty-list. Stops with an error.

Try it online or verify all test cases.

**Explanation:**

```
Δ         # Loop until the result no longer changes
          # (although it'll basically loop until the error in this case)
 =        #  Print the current list with trailing newline (without popping)
          #  (which will use the implicit input-list in the first iteration)
  W       #  Push its minimum (without popping)
   s      #  Swap so the list is at the top again
    à     #  Pop and push its maximum
     Ÿ    #  Pop both, and push a list in the range [min,max]
          #  (the min/max of an empty list are ""; so here it'll error)
      y   #  Push the current list again
       K  #  Remove all those values from the [min,max]-ranged list

```

# Answer
> 2 votes
# Ruby, 34 bytes

```
f=->a{a[0]&&f[p [*a[0]..a[-1]]-a]}

```

Try it online!

# Answer
> 2 votes
# Rust, 138 bytes

```
let f=|l:Vec<u8>|std::iter::successors(Some(l),|l|if l.len()>0{Some((l[0]..l[l.len()-1]).filter(|i|!l.contains(i)).collect())}else{None});

```

Returns a generator.

Goal was to get the longest answer possible, right?

try it yourself

# Answer
> 2 votes
# Retina 0.8.2, 80 bytes

```
$
;¶$%`
\d+
$*
%(M!&`^.+;|(1+)$(?<!^\1.*)(?<!\b\1\b.*)
O`
)`¶
,
1+
$.&
}`;¶$

;

```

Try it online! Explanation:

```
$
;¶$%`

```

Duplicate the last line and mark the previous line as not to be altered.

```
\d+
$*

```

Convert to unary.

```
%(`
)`

```

Run the next three commands separately for each line, so that they don't accidentally clobber one another.

```
M!&`^.+;|

```

Just output the previous lines in full, so nothing happens...

```
(1+)$

```

... but for the last line, output overlapping substrings of the final run of `1`s...

```
(?<!^\1.*)

```

... that are greater than the first run of `1`s...

```
(?<!\b\1\b.*)

```

... and do not match any of the runs of `1`s.

```
O`

```

Sort the lines into ascending order.

```
¶
,

```

Join them with commas.

```
1+
$.&

```

Convert to decimal.

```
;¶$

```

If the were no matching runs of `1`s, then just undo everything, so that the loop stops repeating.

```
}`

```

Repeat the above commands until the buffer stops changing.

```
;

```

Remove the markers on the previous lines.

# Answer
> 2 votes
# GeoGebra, 93 bytes

```
l={
InputBox(l
a=IterationList(Remove(Min(L)...Max(L),L),L,{l},Length(l
Take(a,1,IndexOf({},a

```

Input as comma separated numbers in the input box. Output is the list `l1`.

Try It On GeoGebra!

Try It On GeoGebra! (with example test case)

# Answer
> 2 votes
# Wolfram Language (Mathematica), 55 bytes

```
NestWhileList[Complement[Range@@MinMax@#,#]&,#,#!={}&]&

```

Try it online!

# Answer
> 1 votes
# Python 3, 50 bytes

```
f=lambda K:[*K]and[K]+f({*range(min(K),max(K))}-K)

```

Try it online!

Takes input as a set rather than a list so I can use the more efficient set difference operator. Output will not be sorted. Basic logic to build a list efficiently copied from @m90

---
Tags: code-golf
---


# Question
Title: What is the shortest infinite loop statement in Java?
I'm working on a golf for Java and I need an infinite loop. Obviously, I don't want to spend any more bytes than I have to, especially in such an expressive language.

Assuming I have some code I want to run, obviously the baseline is set at `while(1>0)/*stmt*/` or 10 additional characters for a single line and `while(1>0){/*stmt1*//*stmt2*/}` or 12 additional characters for multiple lines. I say additional because the code I want to loop forever (well, forever-ish... I may or may not want to break out of or return from the loop) will have a certain length, and then I must tack on additional characters to make it actually loop.

At first I thought this was the best I'd get, but I figured I'd throw it out to the experts to see if they can find a better one.

# Answer
> 18 votes
```
for(;;){}

```

It works cause no condition evaluates to always true. Insert the code between the braces.

If you only got a few statements you can place them inside the head (the (;;) part. That the loop still runs is caused by when the condition statement is not a boolean it counts as always true. Thanx to @Ypnypn for the reminder

# Answer
> 2 votes
# 50 bytes

```
interface M{static void main(String[]a){for(;;);}}

```

# Answer
> 1 votes
# Java - 60 bytes (complete code)

I'm probably not interpreting the question correctly, but this code when compiled and run results in an infinite-ish loop, in that technically it should run forever, but usually it will exhaust the stack memory.

```
public class X{public static void main(String[]a){main(a);}}

```

On Coding Ground it ends quite quickly, on my Windows 7 laptop with advanced virtual memory management, it runs a long time, just making the system slower and slower.

# Answer
> 0 votes
```
for(/*init*/;;/*stmt*/){/*stmt*/}

```

To save characters, you can use the init and increment parts of the loop to save a few bytes by using the semicolons.

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


title: Write a fast-growing assembly function

text:
# Question
Title: Write a fast-growing assembly function
## Synopsis

Your goal is to implement the (asymptotically) fastest growing function within bounded code on a fictional CPU utilizing a quite limited, yet (probably) turing-complete instruction set.

## Environment

The CPU utilizes unbounded RAM as well as two registers, the accumulator A and the program counter C, with words consisting of arbitrary integers, such that neither overflows nor underflows are possible. RAM is used to store data as well as code, allowing for self-modifying programs. Each instruction takes one parameter and therefore consists of two words; all instructions of your program are stored sequentially in RAM, starting at address 0. The following instructions can be used, P representing the parameter of the instruction:

| Mnemonic | Corresponding word | Behavior |
| --- | --- | --- |
| LOAD P | 0 | A := RAM\[P\]; C += 2 |
| SAVE P | 1 | RAM\[P\] := A; C += 2 |
| CNST P | 2 | A := P; C += 2 |
| ADDT P | 3 | A += RAM\[P\]; C += 2 |
| NEGA P | 4 | A := -RAM\[P\]; C += 2 |
| JUMP P | 5 | C := P |
| JMPN P | 6 | If A \<= 0 then C := P else C += 2. |
| HALT P | every other number | The program halts. |

At each step, the instruction at address C will be executed using the parameter stored at C + 1. Both A and C will be initialized to 0 at the start of a program's execution. The word at -1 is supposed to be your input which can be guaranteed to be non-negative, other words not storing any instructions initially contain 0. The number stored at -2 will be considered your program's output, which must also be positive in all but finitely many cases.

## Rules

At the initial state, your program may not occupy more than the first 2048 words each storing integers between -2^64 and 2^64, however, during execution, there are no bounds. Of course, you don't have to write your program in bytecode, using some assembly equivalent or ultimately any other language is fine as well, as long as you provide some rules/translator and show the result does not exceed the given bounds.

Every answer should come with some rough argument showing the program always halts, as well as some approximate lower bound on its growth rate. As the given space might very well suffice for some extremely fast-growing functions, it might be helpful to utilize the slow-/fast-growing hierarchy, as it provides a relatively simple way to compare two answers. Answers will be ranked by lower bounds that can be shown to hold.

# Answer
x=\>x\*2^x, 29 words

I use only some constants in addition to constant valued pointers, which you can replace into their values for a true program, along with C-style comments. I believe with enough patience and macros, any function ala "Largest Number Printable" should be implementable.

```
// constant definitions
// do not take any space of their own
IN = -1
OUT = -2
NULL = 0

/*
PROGRAM x => x*2^x
*/

LOAD IN         // VALUE = in; COUNTER = in;
SAVE VALUE      //
SAVE COUNTER    //

loop:           // do {

LOAD VALUE      // VALUE *= 2;
SAVE (INC_BY+1) //
INC_BY: ADDT NULL //
SAVE VALUE      //

LOAD COUNTER    // COUNTER--;
ADDT NEGONE     //
SAVE COUNTER    //

JMPN end        // if (COUNTER<=0) break;
JUMP loop       // } while (true)
end:            //

LOAD VALUE      // return VALUE;
SAVE OUT        //
NEGONE: HALT 0  // HALT is -1

COUNTER: NULL   // var COUNTER, VALUE;
VALUE: NULL     // these variables are both trailing 0s, so can be ignored as the tape defaults to 0.

```

Also push and pop, which I think much helps a turning completeness proof.

```
/*
MACRO stack_manipulation_push_a
14 words
*/
STACKPTR: -2    // put outside of codespace.
CNST 01337      // assume A has the value you want, in this cse, 1337 in base 8

SAVE 0          // probably not being used.
LOAD STACKPTR   // move the stack pointer down to the next open free space.
ADDT NEGONE     //
SAVE STACKPTR   //
SAVE (EAT_ME+1) // put the fresh stack position into the save command, basically dereference.
LOAD 0          // load back in value to be saved
EAT_ME: SAVE NULL // save the orignal A value to where stackptr points

/*
MACRO stack_manipulation_pop_a
16 words
*/
LOAD STACKPTR       // *0 = *STACKPTR;
SAVE (EAT_ME+1)     //
DRINK_ME: LOAD NULL //
SAVE 0              //
LOAD STACKPTR       // move the stack pointer up to the last space.
ADDT 1              //
SAVE STACKPTR       //
LOAD 0              // put the value back in A

```
> 2 votes

---
Tags: restricted-source, atomic-code-golf, busy-beaver
---


title: Laggy text editor

text:
# Question
Title: Laggy text editor
Your challenge is to write a program that constantly prompts for input, and when input is given, output that five seconds\* later. However, your program must continue prompting for input during that time.

Since this is a bit confusing, here's a demo.

```
<pre id=x></pre><input id=h onchange='var k=this;(()=>{let a=k.value;setTimeout(_=>document.getElementById("x").innerText+=a+"\n", 5000)})();this.value="";' >
```

(Try typing multiple things into the box and pressing enter.)

This is , shortest wins!

*Anywhere between four and six seconds is fine.

## Definition of "prompting for input"

I'm not really sure how to define "prompting for input" in a way that works across most languages, so here's a couple of ways you can do this:

* Prompt for input in a terminal, recieving it on pressing enter
* Open a dialog box that asks for input
* Record every keypress and output those delayed - see this fiddle thanks to tsh

If you're not sure, ask. Note that for the first two options, the operation must not block further output.

# Answer
> 17 votes
# JavaScript, ~~53~~ ~~51~~ 44 bytes

Now 44 bytes thanks to @DomHasting's suggestion to omit `window.`.

(Records every keypress; keyboard events won't register unless you focus on the opened iframe when you click run)

```
onkeyup=e=>setTimeout(console.log,5e3,e.key)
```

# Answer
> 10 votes
# Minecraft Command Blocks, ~895 bytes

My Java answer I already have on this question is pretty good, but as I do also have some skill with Minecraft redstone, I wondered if there was a decent way to do this in Minecraft, and it turns out there is. Because inputting data into Minecraft programs is never quite easy, but I was able to figure out a decent method for this: input is provided by placing a named Creeper mob in a specific location; output is much simpler, as it is simply read out to the game chat.

## Explanation

This "program" consists of two chains of command blocks, as follows:

```
chain 1:
Repeat block, Always active: data modify entity @e[type=minecraft:creeper,dx=2,dy=1,dz=0,limit=1,sort=nearest] PersistenceRequired set value 1
Chain block, Conditional: tp @e[type=minecraft:creeper,dx=3,dy=1,dz=0,limit=1,sort=nearest] ~1 ~222 ~-1

chain 2:
Impulse block, Needs Redstone: say @e[type=creeper,limit=1,sort=nearest]
Chain block, Unconditional: kill @e[type=creeper,limit=1,sort=nearest]
Chain block, Unconditional: kill @e[type=item]

```

Minecraft command block programs are mainly formed by chaining command blocks, where a start block (of either Impulse or Repeat type) can activate a Chain block its pointing at, and those Chain blocks can activate more Chain blocks, etc. Chains can be started by either an Impulse or Repeat block, where Impulse blocks trigger once when activated, and then do not trigger again until they are de- and then re-activated, while Repeat blocks trigger every in-game tick while they are activated. both of these blocks can be in either "Always active" or "Needs Redstone" mode, where they are either, respectively, active all the time, or only active when powered by a Redstone signal. Chain blocks also have a conditional feature, where they can be set to only activate if the command of the block that triggered them executed successfully.

The first chain queues up the signal Creeper, with the Repeat block looking continuously for a nearby Creeper and trying to set its PersistenceRequired property to 1 (true). If it succeeds at this, the Conditional Chain block is triggered, which teleports the Creeper up 222 blocks, a distance which I calculated takes almost exactly 5 seconds for it to fall. The first command block is necessary as that property prevents it from despawning, as normally all mobs despawn instantly if they are more than 128 blocks from the player.

This teleport also lines it up so it falls into a tripwire, which provides the Redstone signal that triggers the start of the second chain, which writes the name of the Creeper to chat, kills the Creeper, and then destroys all the items the creeper dropped, as otherwise these would clog up the tripwire and prevent further messages from functioning. There is a pool of water placed under the tripwire to prevent the fall from killing the Creeper, as it needs to stay there long enough for the command block to read its name.

The sign indicates where the Creeper should go, although this positioning is not precise, and is mainly there to fulfill my interpretation of the "prompt for input" requirement.

## Byte Count Calculation and Golfing

Per consensus, MC "program" bytecounts are calculated using the size of the structure block .nbt file needed to contain them, which I have uploaded to dropbox here, so that you can test it in your own world if you want.

Golfing with structure block files is irritating, as its often not clear what increases or decreases bytecount except through trial and error, and bytecount even seems to vary by a few bytes for identical structures. I have tried a few variations of commands, but the ones here seem to have the lowest bytecount. I have tried to fit the "program" into the smallest possible bounding box, and all air blocks in the program are replaced with structure void blocks. I had the sandstone floor as voids too, but that somehow seemed to be larger, so I returned it to sandstone, although it is possible some other block may reduce the file size. The iron block the tripwire is on can also be any block, as long as it supports the tripwire. The sign also seems to be contributing almost 100 bytes, so if it is judged to be unnecessary for the "prompting user" requirement, it would certainly shave off a good deal.

# Answer
> 8 votes
# Bash, 37 bytes

Doesn't work online for obvious reasons!

@Digital Trauma correctly pointed out an unnecessary spaces for -1, thanks!

```
while read a;do sleep 5&&echo $a&done

```

Try it online!

# Answer
> 6 votes
# Factor, 46 bytes

```
[ readln '[ _ print ] 5 seconds later t ] loop

```

Factor has a nice timer vocabulary. `later` Takes a quotation to perform and a duration and calls the quotation after the duration has passed. Since TIO is unsuited for displaying the functionality, here's an animated GIF of running this code in Factor's REPL:

# Answer
> 6 votes
# Java 8, 447 437 404 380 374 278 272 259 219 210 bytes

This is my first code golf, and I'm certain both that I could golf this down more, and that Java is a horrible language for this problem and for golfing in, but for my first try I think this isn't too bad. I tried to golf this in Python, which I'm more familiar with, first, but I simply couldn't get around the non-blocking input restriction in Python.

Edit: Screwing around a lot more I found a much shorter version using threads and waiting instead of my list+timestamp idea for the old one:

```
import java.util.*;class B{static void main(String[]a){Scanner s=new Scanner(System.in);for(;;){String t=s.nextLine();new Thread(()->{try{Thread.sleep(5000);}finally{System.out.println(t);return;}}).start();}}}

```

Edit: -6 bytes, I think I'm solidly addicted to code golfing now.

Edit 2: -13 bytes, realized I could put the whole thing in one class and it'd still work.

Edit 3: -41 bytes from @Clashsoft's excellent idea to use a lambda for the thread class instead.

Edit 4: Apparently the lambda actually means I don't need to extend `Thread` anymore, although I do now need `Thread.sleep()` instead of just `sleep()`

### Old Solution

```
import java.util.*;class A{long t;String s;A(long T,String S){t=T;s=S;}public static void main(String[]a)throws java.io.IOException{List<A>L=new ArrayList<>();Scanner s=new Scanner(System.in);for(;;){if(System.in.available()>0&&s.hasNext()){L.add(new A(System.nanoTime(),s.nextLine()));}if(L.size()>0&&L.get(0).t+5e9<System.nanoTime()){System.out.println(L.remove(0).s);}}}}

```

Edit: -10 bytes from trimming the "public" off Main class declaration and a bit of whitespace.

Edit 2: -33 bytes with a bit more trimming and a better import.

Edit 3: -18 bytes by using System.nanoTime() instead of System.currentTimeMillis(), and -6 by Seggan's suggestion to switch to an interface to drop the public modifier, for total of -24.

Edit 3.5: Pasted the wrong code for edit 3, now showing the correct code (I think, I don't have the actual code or an IDE on hand at the moment) with those changes.

Edit 4: @Neil's suggestion to put it all in one class let me save another six bytes, I think I'm getting close to how far this approach can be golfed in Java, but there could be something more I'm not seeing yet.

# Answer
> 5 votes
# Rust, ~~180~~ 127 bytes

```
use std::{io::*,thread::*};fn main(){for s in stdin().lock().lines(){spawn(move||{sleep_ms(5000);println!("{}",s.unwrap())});}}

```

Runs an infinite loop, reads the string and spawns a new thread. After 5s of blocking that thread, it prints it back to the console.

```
use std::{io::*, thread::*};
fn main() {
    for s in stdin().lock().lines() {
        spawn(move || {
            sleep_ms(5000);
            println!("{}", s.unwrap())
        });
    }
}

```

Thanks to Xiretza and the community in #rust matrix server :)

## Old answer

```
use std::*;fn main(){let s=io::stdin();loop{let mut b=String::new();s.read_line(&mut b).unwrap();thread::spawn(move||{thread::sleep(time::Duration::from_secs(5));print!("{b}")});}}

```

Runs an infinite loop, reads the string and spawns a new thread. After 5s of blocking that thread, it prints it back to the console.

```
use std::*;
fn main() {
    let s = io::stdin();
    loop {
        let mut b = String::new();
        s.read_line(&mut b).unwrap();
        thread::spawn(move || {
            thread::sleep(time::Duration::from_secs(5));
            print!("{b}")
        });
    }
}

```

Sadly it's not possible to run such programs in rust playground.

Not the best language for code-golf, I know, but just wanted to give it a shot. :)

# Answer
> 5 votes
# Python 63 bytes

```
from threading import*
while 1:Timer(5,print,[input()]).start()

```

Thanks AnttiP for showing me that Timer can directly pass arguments to the callback itself, which cut the solution by 20 bytes.

Thomas Baruchel pointed out a valid criticism of the original recursive solution: that the program would crash after 1000 inputs because of Python's recursion limit. Luckily AnttiP's new design is even shorter without recursion.

# Answer
> 4 votes
## Batch, 63 bytes

```
@set/ps=
@start /b cmd /c"ping -n 6 0.0.0.0>nul&echo %s%"
@%0

```

Explanation: `start /b` runs a command in the background in the same console. `ping` is used for the five second delay between the first and last pings. Note that the string is echoed unquoted so that some shell metacharacters may cause the echo to fail.

# Answer
> 4 votes
# QBasic, 167 bytes

```
DIM d(999),o$(999)
DO
c$=INKEY$
IF""<>c$THEN o$(j)=c$:d(j)=TIMER+5+86400*(TIMER>=86395):j=(j+1)MOD 1E3
IF(INT(TIMER-d(i))=0)*d(i)THEN?o$(i);:d(i)=0:i=(i+1)MOD 1E3
LOOP

```

Runs as an infinite loop; outputs character-by-character. Don't run this unless you have a good way to kill the program. Here's a nicer version that quits when you press Escape:

```
DIM d(999),o$(999)
CLS
DO
c$=INKEY$
IF c$=CHR$(27)THEN END
IF""<>c$THEN o$(j)=c$:d(j)=TIMER+5+86400*(TIMER>=86395):j=(j+1)MOD 1E3
IF(INT(TIMER-d(i))=0)*d(i)THEN?o$(i);:d(i)=0:i=(i+1)MOD 1E3
LOOP

```

You can try it at Archive.org.

### Approach

QBasic doesn't have any non-blocking sleep command or multithreading capabilities that I'm aware of, so we're going to go low-tech on this and use `TIMER`, which provides the (floating-point) number of seconds since midnight. When a key is pressed, we store it in the `o$` array, and we also store `TIMER + 5` at the same index in the `d` array. Then we check the first time in `d` to see if it has arrived yet; if so, we output the corresponding character.

Some complexity is added because:

* QBasic has fixed-size arrays rather than lists, so there aren't any pop or push operations. We have to track the index of the next insertion and the index of the next removal, and we have to wrap both around when they reach the size of the array.
* `TIMER` resets at midnight, which breaks the math unless we correct for it.

### Ungolfed

```
CONST ARRAYSIZE = 999
CONST TIMERMAX = 86400  ' Number of seconds in a day
DIM d(ARRAYSIZE)        ' Times at which to output characters
DIM o$(ARRAYSIZE)       ' Characters to output
i = 0                   ' Index of first meaningful entry in d and o$
j = 0                   ' Index just past last meaningful entry in d and o$

' Clear screen
CLS
' Loop forever
DO
  ' If a key is being pressed, store it in c$
  c$ = INKEY$
  ' If it is Esc, quit the program
  IF c$ = CHR$(27) THEN END
  ' For any other key...
  IF c$ <> "" THEN
    ' Store it in o$
    o$(j) = c$
    ' Store 5-seconds-in-the-future time in d
    d(j) = TIMER + 5
    ' Correct for midnight wraparound
    IF d(j) >= TIMERMAX THEN d(j) = d(j) - TIMERMAX
    ' Increment next-entry index
    j = j + 1
    ' Wrap index around if necessary
    IF j > ARRAYSIZE THEN j = 0
  END IF
  ' If we've reached the time for the first character in the array...
  IF d(i) > 0 AND TIMER - d(i) > 0 AND TIMER - d(i) < 1 THEN
    ' Print it without a newline
    PRINT o$(i);
    ' Zero out the time for that character
    d(i) = 0
    ' Increment first-entry index
    i = i + 1
    ' Wrap index around if necessary
    IF i > ARRAYSIZE THEN i = 0
  END IF
LOOP

```

# Answer
> 4 votes
# Julia, ~~53~~ 42 bytes

```
~_=(r=readline();~@async sleep(5)print(r))

```

*-11 bytes thanks to @MarcMush*

Previous version that's perhaps easier to understand at a glance:

```
while 1>0
r=readline()
@async (sleep(5);print(r))
end

```

# Answer
> 4 votes
# C, ~~63~~ ~~62~~ 57 bytes

```
main(b){for(;;){gets(&b);if(fork()){sleep(5);puts(&b);}}}

```

Try online!

Similar to Amir reza Riahi's answer managed to remove `i` variable and used an 8 byte int buffer.

Shaved off a byte by declaring b as `int b`(instead of `int b[8]`) and by using `&` operator

-5 bytes: `b` is passed in to the main function instead of being declared.

# Answer
> 3 votes
# C, ~~83~~ ~~73~~ 69 bytes

```
main(){for(int i=0;;){char*b;gets(b);if(fork()){sleep(5);puts(b);}}}

```

Try online!

The only problem is that the program should break by ctrl-c and is not terminated by the ctrl-d.

Thanks to Neil, I removed 10 bytes.

# Answer
> 3 votes
# HTML/CSS, 73 72 bytes

I wanted to try solving this without JavaScript, so I came up with this solution. To use it, open it in a browser, press tab, then enter, then start typing and submit a line by pressing enter again. Up to you to decide whether or not this user interaction disqualifies the answer.

```
<p contenteditable><style>p>:last-child{font:0 a}*{transition:5s steps(1

```

## Demo

Note that this demo has to close off the CSS for it to work as a code snippet - this is not necessary when opening the HTML by itself in a browser.

```
<p contenteditable><style>p>:last-child{font:0 a}*{transition:5s steps(1)}
```

## Explanation

The `contenteditable` tag makes it possible for the user to edit the DOM text directly. If you've never heard of it before, run `document.body.setAttribute("contenteditable", true)` on random sites and have fun! Since in this case a `<p>` tag is being edited, adding a newline creates a new `<div>` element for each line, which we can use to our advantage in the CSS.

A simplified version of the CSS is pretty self-explanatory:

```
div {
 font: initial; /* implied */
 transition: font 5s steps(1);
}

div:last-child {
 font: 0px Arial;
}

```

The only uncommon part here is the `steps(1)` setting for the transition, which makes the transition go straight from one state to another (instead of fading smoothly).

# Answer
> 3 votes
# TI-Basic (TI-84), ~~76~~ ~~128~~ ~~121~~ 120 bytes

```
1→X
1→Y
{0→A
Ans→B
While 1
startTmr→ʟB(X
getKey→ʟA(X
X+tanh(Ans→X
If 5≤checkTmr(ʟB(Y
Then
ʟA(Y
Disp sub("ABC.HDEFGMIJKLRNOPQWTSUV.XYZ",5int(Ans/10-4)+5fPart(Ans/5),1
IS>(Y,X
End
End

```

`ʟA` stores the pressed keycodes, `ʟB` the time at which they were pressed, `X` is the length of the lists, and `Y` the index of the next letter to print. The precision is one second (precision of `startTmr`) so it should be between 4 and 6 seconds delay. `tanh` serves as a `sign` function since `getKey` is big enough (\> 41 for letters)

there's no built-in to translate numbers to characters, hence the long line with all the letters (strange ordering to use mod 5 instead of mod 10). I'm pretty sure this can be further goffed by being clever. Outputing the keycodes instead would save 52 bytes (previous solution)

-1 byte: I believe this is the first time I successfully use `IS>(` in code golf, which only works because X is always greater than Y

# Answer
> 2 votes
# **Kotlin, 122 bytes**

```
import kotlinx.coroutines.*;suspend fun main()=coroutineScope{while(true){readLine()?.let{launch{delay(5000);print(it)}}}}

```

Also my first code-golf. Looking forward for tips and advices.

Explanation: main function is suspendable for non-blocking print. Infinite loop is running under CoroutineScope created with coroutineScope() function. In infinite loop program constantly reads the prompt with standard function readLine(). Result of readLine() is used under scope function let() in newly created coroutine created with launch() builder, which delays printing for 5 seconds without blocking the next propmt

# Answer
> 2 votes
# Bash, 34 bytes

```
f(){ read c;sleep 5&&echo $c&f;};f

```

Try it online!

Pretty similar to Dom Hasting's answer, but managed to save 4 bytes by using a function instead of a loop.

Does *not* work correctly on TIO.

# Answer
> 2 votes
# Seal, 25 bytes

```
w(1){i=h#l;t{z(5);p(i);}}

```

# Answer
> 2 votes
# Ruby, 32 bytes

```
loop{a=gets;fork{sleep 5;$><<a}}

```

Spawns child processes for each timer. They aren't terminated since the program is non-terminating anyways, so if this is ever run it should be followed with a `Process.waitall`.

No TIO link since TIO has static input.

`fork` is not supported on all OSes (most notably Windows), but it is listed in Ruby documentation. An alternative solution that works on all OSes is:

```
loop{a=gets;Thread.new(a){sleep 5;$><<_1}}

```

which is 42 characters instead.

# Answer
> 2 votes
# Scratch, 168 bytes

Try it online!
This takes advantage of a clone storing a variable's value at the time of the clone's creation. Alternatively, 11 blocks.

```
when gf clicked
delete all of[O v
forever
ask()and wait
set[t v]to(answer
create clone of[myself v
when I start as a clone
wait(5)seconds
add(t)to[O v
delete this clone

```

```
when gf clicked            Syntax
delete all of[O v          Clears the output
forever                    Loops code forever
ask()and wait              Prompts user input
set[t v]to(answer          Sets variable 't' to the input
create clone of[myself v   Creates clone
when I start as a clone    Syntax, also ends 'forever' loop
wait(5)seconds             Waits 5 seconds
add(t)to[O v               Adds to the output the value of 't' at the time of the clone's creation
delete this clone          Deletes itself to avoid the 300 clone limit

```

# Answer
> 0 votes
# TI-Basic (TI-89), 117 bytes

```
Prgm
 {}→g
 g→t
 xscl→x
 x→y
 Loop
  startTmr()→t[x]
  getKey()→g[x]
  x+min(xscl,g[x])→x
  If checkTmr(t[y])≥5 Then
   Disp char(g[y])
   y+xscl→y
  EndIf
 EndLoop
EndPrgm

```

Port of my answer for the TI-84. The TI-Basic of the TI-89 is much more advanced (it has the `char` command and much much more) but the tokens are often longer (a literal `1` is stored as 3 bytes, that's why we use `xscl` \[2 bytes\] instead)

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


title: Check a mushroom forest

text:
# Question
Title: Check a mushroom forest
In this challenge you will receive a list of pairs of non-negative integers representing a mushroom forest. Each pair represents a mushroom whose center is at that horizontal coordinate. The only part of the mushroom we care about is the cap (the flat bit at the top).

The first integer in each pair represents which row the cap is placed in. i.e. the height of the mushroom.

The second integer represents the radius of the cap. If it's zero then there just isn't a mushroom in that position. Other for size \\$n\\$ a total of \\$2n-1\\$ spaces are occupied centered at the index of the pair. For example `1` means that its cap only occupies a space above it, a `2` means it occupies a space above it and the spaces one unit to the left and right.

As an example here's an example with the forest drawn:

```
=-=-= =-=-=-=-=-=-= =
  |         |       |
  | =-=-=   |   =-=-=
  |   |     |     | |
  =-=-=     =-=-=-=-=
  | | |     |   | | |
[ 2,0,1,0,0,2,0,0,1,2 ] <- Heights
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths

```

(For clarity, stems are drawn with `|` and extra spacer rows are added between layers)

Your task is to determine from an input list whether there are any collisions between mushroom caps. That is if there is any pair of mushrooms that both occupy 1 or more common spaces.

You should output one of two distinct values. One if there is a collision and the other if there is not.

You may take input instead of a list of pairs as two separate lists of the same length.

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

## Test cases

Test cases are provided with an illustration.

### No collision

```
=-=-= =-=-=-=-=-=-= =
  |         |       |
  | =-=-=   |   =-=-=
  |   |     |     | |
  =-=-=     =-=-=-=-=
  | | |     |   | | |
[ 2,0,1,0,0,2,0,0,1,2 ] <- Heights
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths

  =-=-= =
    |   |
=-=-= =-=-=-=-=
  | |   | |
[ 0,1,0,1,0 ] <- Heights
[ 2,2,0,1,3 ] <- Widths

    =-=-=-=-=-=-=
          |
  =-=-=-=-=-=-=
        | |
    =-=-= |
      | | |
    = | | |
    | | | |
=-=-= | | |
  | | | | |
[ 0,1,2,3,4 ] <- Heights
[ 2,1,2,4,4 ] <- Widths

```

### With Collisions

Locations with a collision are marked with `X`.

 =-X-X-=
   | |
   | |
   | |
[0,1,1] <- Heights
[0,2,2] <- Widths

   X-=-=-=-=-=-=
   |     |
[0,0,0,0,0] <- Heights
[0,1,0,0,4] <- Widths

 =-=-X-=-=-=-=
   |     |
[0,0,0,0,0] <- Heights
[0,2,0,0,3] <- Widths
```
</code></pre>

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

```
{a~?a:,/x,''(!#y)+(?,/-:\!:)'y}

```

Try it online!

-4 bytes thanks to @ovs! Golfed even more with inspiration from @UnrelatedString's approach.

## Explanation

Height list is *x*, width list is *y*.

* `(?,/-:\!:)'y` convert each width to range `(-width, width)`
* `(!#y)+` add indices
* `x,''` add corresponding height to each index in each width range
* `a~?a:,/` flatten, check for duplicates

# Answer
> 3 votes
# MathGolf, 22 bytes

```
mÆ╤╞╡ï+m▐ò┤\h?a*^~]_▀=

```

Port of my 05AB1E answer (the 19-bytes version; since the 22-bytes version was using a group-by, which MathGolf lacks and I also couldn't find any suitable alternative for with its available builtins after some trial-and-error for more than an hour.. :/)

Just like my 05AB1E answer: input as two separated (equal-length) lists, first being the list of widths, second the heights.

Try it online.

**Explanation:**

Basically the same three steps as my 05AB1E answer:

Step 1: Change each value in the input to a list of indices it can reach:

```
m          # Map over the first (implicit) input-list of widths,
 Æ         # using 5 bytes as inner code-block:
  ╤        #  Convert it to a list in the range [-n,n]
   ╞╡      #  Remove the first/last items to change it to range (-n,n)
     ï+    #  Add the 0-based map index to each value as offset

```

Try just this first step.

Step 2: Pair each inner index with the height of the second input:

```
m▐         # Append each value in the second (implicit) input-list of heights to
           # the (-n,n)-list at the same position
  ò        # Loop over the lists, using 8 bytes as inner code-block:
   ┤       #  Extract tail; push remainder-list and last item separated
    \      #  Swap so the remainder-list is at the top
     h     #  Push its length (without popping)
      ?    #  Triple-swap the [tail,list,length] to [list,length,tail]
       a   #  Wrap the tail into a list
        *  #  Repeat it the length amount of times
         ^ #  Zip to create pairs of the list with these repeated tails

```

Try just the first two steps.

Step 3: Check if all (flattened) pairs are unique, and output the result:

```
   ~       #  Still in the loop of step 2: dump the pairs to the stack
]          # After the loop: wrap all pairs on the stack into a list
 _▀=       # Check if all pairs are unique:
 _         #  Duplicate the list of pairs
  ▀        #  Uniquify the copy
   =       #  Check if both lists are still the same
           # (after which the entire stack is output implicitly as result)

```

# Answer
> 2 votes
# Python, ~~153~~ ~~105~~ 86 bytes

*-19 bytes thanks to @Unrelated String*

```
lambda l:len(d:=[(h,z)for i,(h,x)in enumerate(l)for z in range(-x-~i,x+i)])==len({*d})
```

Attempt This Online!

# Answer
> 2 votes
# 05AB1E, ~~22~~ 19 bytes

```
εD(Ÿ¦¨N+INèδ‚}€`DÙQ

```

-3 bytes using a similar approach as *@UnrelatedString*'s Python answer

Input as two separated (equal-length) lists, first being the list of widths, second the heights.

Try it online or verify all test cases.

**Explanation:**

Step 1: Exact same first step as in the previous related challenge: Change each value in the input to a list of indices it can reach:

```
ε         # Map over each value of the (implicit) input-list:
 D(       #  Create a negative copy
   Ÿ      #  Pop both, and push a list in the range [n,-n]
    ¦¨    #  Remove the first and last to make the range (n,-n)
          #  (or empty the list if n=0)
      N+  #  Add the current map-index as offset

```

Try just this first step.

Step 2: Pair each inner index with the height of the second input:

```
 I        #  Push the second input-list of heights
  Nè      #  Use the map-index to get the current height
    δ     #  Apply double-vectorized:
     ‚    #   Pair this height with each index in the (n,-n) range
}         # Close the map

```

Try just the first two steps.

Step 3: Check if all (flattened) pairs are unique, and output the result:

```
€`        # Flatten the list of lists of pairs one level down
  DÙQ     # Check if all pairs are unique:
  D       #  Duplicate the list
   Ù      #  Uniquify this copy
    Q     #  Check if both lists are still the same
          # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Haskell, ~~112~~ ~~85~~ 75 bytes

*-37 bytes thanks to @Wheat Wizard's tips*

```
import Data.List
f k|z<-do(i,(y,x))<-zip[0..]k;(y,)<$>[2-x+i..x+i]=z==nub z
```

Attempt This Online!

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

Expects `(heights)(widths)`. Returns a Boolean value.

```
h=>w=>w.some((w,x)=>h[H=~h[x]]&(h[H]|=m=4**w/2-1<<x>>w,m))

```

Try it online!

### How?

This is using the same method as in my answer to the other challenge. But since there's no search involved, we can just store the bitmasks in one of the input arrays with negative indices.

---

# JavaScript (ES6), 65 bytes

Expects `(heights)(widths)`. Returns a Boolean value.

```
h=>w=>w.some((p,i)=>w.some((q,j)=>p*q&&h[i]==h[j]&j>i&i+p-1>j-q))

```

Try it online!

### Commented

```
h =>                // h[] = array of heights
w =>                // w[] = array of widths
w.some((p, i) =>    // for each mushroom of width p at index i:
  w.some((q, j) =>  //   look for another mushroom of width q at index j:
    p * q           //     such that they both actually exist,
    && h[i] == h[j] //     they have the same height,
    & j > i         //     the 2nd one is located after the 1st one,
    & i + p - 1     //     and the right part of the 1st one intersects
      > j - q       //     with the left part of the 2nd one
  )                 //   end of inner some()
)                   // end of outer some()

```

# Answer
> 2 votes
# Pyth, ~~22~~ ~~21~~ 18 bytes

```
{Is.e,RGtr-keAb+kH

```

Try it online! or Verify all test cases

### Explanation

`.e` enumerates over the implicit input with index `k` and value `b`.

`Ab` sets `G` and `H` to the elements of `b` (in this case, height and width respectively)

`tr-keAb+kH` builds a range from **k-H+1** to **k+H** (half inclusive)

`,RG` appends the height to each element of that list, resulting in a list of coordinates for the current mushroom.

`s` flattens the list by one level. And `{I` checks whether the list remains invariant under deduplication, meaning that no two mushrooms share a coordinate.

# Answer
> 2 votes
# Desmos, 156 bytes

```
l=W.length
k=max(0,i-W[i])
L=[1...n]
g(n)=L[L0+n>0]0
f(H,W)=0^{0^{[max(∑_{i=1}^ljoin(g(k),g(W[i]+i-1-k)+1,g(l))[1...l]0^{(h-H[i])^2})forh=H[1...]].max-1}}

```

My attempt at solving this challenge without looking at the other answers lolol. You can see how terribly that came out just by how long the answer is.

The function `f` takes in the height list first and the width list second, and returns `0` for no collisions, `1` if there is a collision.

Also the `H[1...]` can't be golfed to `H` (I checked), because apparently `H` is recognized as a number, not a list, so the list comprehension errors out. `H[1...]` circumvents this error by forcing Desmos to recognize `H` as a list.

Try It On Desmos!

Try It On Desmos! - Prettified

I have added an explanation of my code below because I'm bored :P.

### Explanation

The general rundown of my strategy is for each height, construct lists of `1`'s and `0`'s which correspond to the spaces that each mushroom takes up for that particular height. Then, all these lists are summed together. If there is a collision at that height, then there will be a number \\$\>1\\$ in the list.

Now, to explain each part of the code.

```
L=[1...n]
g(n)=L[L0+n>0]0

```

`g` is a function that will return a list of `n` zeroes.

```
f(H,W)=0^{[max(∑_{i=1}^ljoin(g(k),g(W[i]+i-1-k)+1,g(l))[1...l]0^{(h-H[i])^2})forh=H[1...]].max-1}

```

`f` is the function that returns the answer. Let's break it down:

```
... [ ... forh=H[1...]]

```

For `h` in list `H` (looping over all heights)...

```
... ∑_{i=1}^l ...

```

Take the summation from `i=1` to the length of list `W` of (looping over indices of the width list)...

```
join(g(k),g(W[i]+i-1-k)+1,g(l))[1...l]

```

A list of `1`'s and `0`'s, representing the spaces that the mushroom at index `i` in the width list takes up, with `1` representing the space taken up by the mushroom. This list is constructed by joining three individual lists into one list: `g(k)`, `g(W[i]+i-1-k)+1`, and `g(l)`.

The first list, `g(k)`, consists of the `0`'s before the range of `1`'s which represent the mushroom. The number of `0`'s needed can be calculated by subtracting the width of the mushroom `W[i]` from its index `i` (The mushroom extends `W[i]-1` spaces to the left from the center space, so `i-W[i]` is essentially calculating the index of the last `0` right before the mushroom.). The issue with this is that some mushrooms extend past the front of the list, which will make `i-W[i]` negative. While this is no problem for `g` (it returns an empty list for negative inputs), it may cause issues for length calculations later on (i.e. the list of `1`'s right after), so instead we store the length of the list as `k=max(0,i-W[i])`, and call `g(k)` to construct the list of `0`'s.

The second list, `g(W[i]+i-1-k)+1`, constructs a list of `1`'s which represent the space that the mushroom takes up. `g` returns a list of `0`'s, so we convert that to a list of `1`'s by adding 1 to the list. At first, it might be obvious to do `g(2W[i]-1)+1` as each mushroom takes up \\$2w-1\\$ spaces. But this runs into the problem of width 0, as `g(-1)+1` is just an empty list, but what we actually wanted was the list `[0]`. Also, the bigger problem is that it doesn't account for mushrooms extending past the front of the list, and will have too many `1`'s for those mushrooms. To counteract this problem, note that the length of the list up to the end of the mushroom has to be `i+W[i]-1` (the mushroom extends `W[i]-1` spaces to the right of its center, `i`, so the index of the last `1` in the mushroom is `i+W[i]-1`). The first list already accounted for `k` of the elements, so the second list will have a length of `i+W[i]-1-k` to account for the rest of the elements.

The last list, `g(l)`, is simply to pad the end of the list with enough `0`'s to make the list have a length of at least `l=W.length` for the slice (explained below).

`[1...l]` is a slice that takes the first `l` elements of the list. This is to ensure that all the lists being summed have the same length, as Desmos gives an error if they aren't all the same length.

```
0^{(h-H[i])^2}

```

This checks if the height of the mushroom at index `i` is the same as the current height `h` (if we don't have this code, then the function would detect for collisions as if they were all on the same height). `(h-H[i])^2` returns `0` if the current height `h` is the same as the mushroom's height `H[i]`. Otherwise, it returns a positive integer. Then, `0^{(h-H[i])^2}` returns `1` if `(h-H[i])^2` is `0`, and `0` if `(h-H[i])^2` is a positive integer.

Putting that all together, `0^{(h-H[i])^2}` returns `1` if `h` equals `H[i]`, and returns `0` otherwise. When multiplying this value with the list, if it is `1`, then nothing happens to the list, but if it is `0`, then all the entries in the list become `0`, which essentially means that the list won't contribute to the summation at all. This causes any mushroom that isn't at the current height of the loop to be nullified, leaving only the mushrooms which are at the current height to contribute to the summation.

```
0^{0^{[max( ... ) ... ].max-1}}

```

Recall that if the summed list contains any number \\$\>1\\$, then that means there is a collision. If there are any numbers \\$\>1\\$, then the `max` of the summed list will be \\$\>1\\$. The list comprehension will create a list of maximums for each height in `H`. By taking the maximum of the list comprehension, we can then detect if there were any collisions in any of the heights if the maximum is \\$\>1\\$. We can do this by first subtracting one from the maximum, and then wrapping `0^{0^{ ... }}` around it. `0^{0^n}` for any integer `n` returns `1` if `n` is positive, and `0` if `n` is `0` or negative. This means if the maximum is `0` or `1`, the function will return `0`, because both `0^{0^{-1}}` and `0^{0^0}` return `0`. If the maximum is `2` or above, then the function will return `1`.

# Answer
> 1 votes
# Charcoal, 26 bytes

```
⊙η∧ι⊙…ηκ∧λ∧⁼§θκ§θμ›⁺ιλ⊕⁻κμ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if there's a collision, nothing if not. Explanation:

```
 η                          Input widths
⊙                           Any element satisfies
   ι                        Current width
  ∧                         Logical And
      η                     Input widths
     …                      Truncated to length
       κ                    Outer index
    ⊙                       Any element satisfies
         λ                  Current width
        ∧                   Logical And
             θ              Input heights
            §               Indexed by
              κ             Outer index
           ⁼                Equals
                θ           Input heights
               §            Indexed by
                 μ          Inner index
          ∧                 Logical And
                    ι       Outer width
                   ⁺        Plus
                     λ      Inner width
                  ›         Is greater than
                        κ   Outer index
                       ⁻    Minus
                         μ  Inner index
                      ⊕     Incremented

```

Bonus program!

# Answer
> 1 votes
# Factor \+ `math.unicode`, 100 bytes

```
[ [ swap dup neg (a,b) n+v ] map-index zip expand-keys-push-at values [ concat dup members = ] ∀ ]

```

Attempt This Online!

Oh how I wish there was a word for `expand-keys-push-at values` that was around 6 bytes instead of 26. This uses the algorithm described in Kevin Cruijssen's 05AB1E answer.

# Answer
> 1 votes
# C (clang), 128 bytes

```
i;j;k;*c;r;f(*h,*w,n){for(r=i=0;i<n;++i)for(c=calloc(n,8)+n,j=i;j<n;++j)for(k=-~j-w[j];h[i]==h[j]&k<j+w[j];)r|=++c[k++]>1;*h=r;}

```

Try it online!

Inputs a pointer to an array of mushroom heights \\$h\\$, a pointer to an array of mushroom widths \\$w\\$, and the length of the arrays (since pointers in C carry no length info).
Returns, through the input pointer \\$h\\$, \\$0\\$ if there aren't any collisions between mushroom caps and \\$1\\$ otherwise.

# Answer
> 1 votes
# Vyxal, 19 bytes

```
¨2$:NrḢ+⁰ntiv";ÞfÞu

```

Try it online or verify all test cases.

Port of 05AB1E. Too bad we don't have a loop index variable. Then it could be 16 bytes.

```
¨2$:NrḢ+⁰ntiv";ÞfÞu
¨2                  # Open a dyadic map lambda: Map over the implicit first input, pushing both item and index
  $                 #  Swap so the item is at the top
   :Nr              #  Range [n, -n)
      Ḣ             #  Remove the first item to make this (n, -n)
       +            #  Add the index
        ⁰nti        #  Index the loop-index into the second input
            v"      #  Pair each in the list with this
              ;     # Close map
               Þf   # Flatten one level
                 Þu # Is this unique?

```

# Answer
> 1 votes
# , 100 bytes

```
\(h,w,a=\(x,y,z)`if`(z>=0,complex(0,x,-z:z+y),y),p=mapply(a,h+1,seq(!h),w-1))any(table(unlist(p))>1)
```

Attempt This Online!

Complex numbers!

# Answer
> 1 votes
# BQN, 36 bytes

```
(∨˝⍟2((∧´+´>≠⋈⌈´)¨·∾´↑¨∘↓)˘)∘⍉=⌜⟜⍷⊸×

```

Dyadic function; takes a list of heights as its left argument and a list of widths as its right argument. Returns 0 for no collisions or 1 for one or more collisions, wrapped in a unit array.

Try it at BQN online!

### Explanation

```
=⌜⟜⍷⊸×

```

Splay the widths out into different columns of a 2D array, one column for each distinct height in the heights list.

```
(...)∘⍉

```

Transpose so each list of widths-at-a-given-height is now a row. Then:

```
(...)˘

```

Map over each row:

```
·∾´↑¨∘↓

```

Generate a list of all sublists; then:

```
(...)¨

```

Map this function to each sublist:

```
∧´+´>≠⋈⌈´

```

Is the sum of the sublist greater than both the length of the sublist and the max of the sublist?

This function will always return 1 for any sublist that:

* Starts and ends with a nonzero mushroom width, and
* Has all zeros between the two nonzero values, if
* The two mushrooms overlap

It will also return 1 for certain other sublists, but only if they contain a sublist that matches the above criteria. Thus, if there are any 1's in the results, that indicates the existence of some overlapping pair of mushrooms.

```
∨˝⍟2

```

We have a 2D array of 0's and 1's; fold its leading axis on logical OR twice, giving a 0D array containing 1 if there were any 1's and 0 otherwise.

# Answer
> 1 votes
# Python 3 with NumPy, 83 bytes

```
def f(h,w):
 for j in h:x,=(w*(h==j)>0).nonzero();1**((x-w[x])[1:]+1-(w[x]+x)[:-1])

```

Try it online!

Takes two array arguments and signals by error/no error.

# Answer
> 1 votes
# Jelly, 15 bytes

```
Ḥ’R_"ƲĖS€;€"ẎQƑ

```

A dyadic Link that accepts the widths on the left and the heights on the right and yields `0` if there are collisions or `1` if not.

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

### How?

```
Ḥ’R_"ƲĖS€;€"ẎQƑ - Link: widths, heights
     Ʋ          - last four links as a monad - f(widths):
                      e.g. widths = [3,2,0,1]
Ḥ               -   double          [6,4,0,2]
 ’              -   decrement       [5,3,-1,1]
  R             -   range           [[1,2,3,4,5],[1,2,3],[],[1]]
    "           -   zip with:
   _            -     subtract      [[-2,-1,0,1,2],[-1,0,1],[],[0]]
      Ė         - enumerate         [[1,[-2,-1,0,1,2],],[2,[-1,0,1]],[3,[]],[4,[0]]]
       S€       - sum each          [[-1,0,1,2,3],[1,2,3],[],[4]]
           "    - zip with heights applying:
         ;€     -   concatenate (the current height) to each
            Ẏ   - tighten
              Ƒ - is invariant under?
             Q  -   deduplicate

```

---
Tags: code-golf, array, decision-problem
---


title: Is this a strange pond?

text:
# Question
Title: Is this a strange pond?
In this challenge we considered a frog hopping around a lily pond. To recap the lily pond was represented as a finite list of positive integers. The frog can only jump forward or backwards by a distance equal to the number at its current location. So for example:

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

```

Here the frog is on a `1` so it can move forward 1 to the `4` or backwards 1 to the `3`. In the last challenge the frog had a specific starting location, but in this one we don't care about that. We just care what jumps a frog can make from a particular lily pad.

We can represent these as a directed graph, where each pad is a vertex and the edges represent hops the frog can make. Thus each vertex can have at most 2 children (forward and backwards), vertices can have fewer children if jumping in a certain direction would put them out of bounds. And indeed at least two vertices in every lily pond have fewer than two children.

As an example the pond shown above `[2,3,1,4,1]` can be represented as the graph:

```
{ 0 : [ 2 ]
, 1 : [ 4 ]
, 2 : [ 1, 3]
, 3 : []
, 4 : [ 3 ]
}

```

Of course not all graphs where each node has fewer than 2 children represents a lily pond. For example, the complete graph of order 3:

```
{ 0 : [ 1, 2 ]
, 1 : [ 0, 2 ]
, 2 : [ 0, 1 ]
}

```

Each node has two children, but the first element of the list can have at most 1 child (can't go backwards from the start). So none of the elements can go first, thus this can't be a lily pond.

## Task

Your answer should take as input a directed graph which satisfies the following properties:

* it doesn't have a vertex with more than 2 outgoing edges (children).
* it doesn't have a self loop (an edge from a vertex to itself).
* it doesn't have two edges with the same origin and destination vertices (the graph is simple).

Graph nodes are unlabeled and unordered.

Your answer should output one of two consistent values. The first if the input represents some lily pond, the second if it does not. What the two values are are up to you to decide.

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

## Test cases

Test cases are given where each element is a list of indices that are children. Note that since graph nodes are unlabeled and unordered the order given in the input in the case below **does not** represent positioning of the potential solution. The second test case should demonstrate this.

### Represents a lily pond

Here each input is provided with a potential solution. The solution does not need to be output it is just there to help you.

```
[[2],[4],[1,3],[],[3]] ~ [2, 3, 1, 4, 1]
[[],[2],[0],[4],[0,1]] ~ [2, 3, 1, 4, 1]

```

### Represents no lily ponds

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

```

# Answer
> 1 votes
# Python3, 264 bytes:

```
def f(g):
 for i in permutations(g,len(g)):
  G=dict(enumerate(i))
  for p in c(G):
   if len(G[p[0]])==1and len(G[p[-1]])<2and p:return 1
def c(g,s=0,k=[0]):
 if not g[s]:yield k;return
 for i in g[s]:
  if(i in k)^1:yield from c(g,i,k+[i])
from itertools import*

```

Try it online!

---
Tags: code-golf, decision-problem, graph-theory
---