# Question
Title: Split a list into maximal equal-sum sections
## Task

Given a non-empty list of positive digits, group them into sublists of equal sum. You may output any subset of solutions with maximal number of sublists (equivalently, minimal sum).

The input may contain repeat elements. There may not exist any solution but the singleton list containing the input itself. The output does not need to be in any particular order. You may not assume in the input list is in any particular order.

## Format

You must accept a non-empty list of positive integers and output a 2D list of those integers, both in any reasonable format. Since I have restricted the inputs to 1-9, you may just accept a string of digits as input. However, your output give an obvious indication as to how the sublists are split.

## Test Cases

These only show one solution, but if more exist, you may output them instead, or multiple, etc.

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

```

Here is an extremely inefficient test case generator.

# Answer
# , 65 bytes

```
<@/:~((i.~/:~@;&.>)>@{])[:(\:#&>)@,@(g/.~+/&>)g=:<@#~"#.2#:@i.@^#

```

Try it online!

A different approach to brute force. All test cases execute in a few seconds on TIO.

Consider `2 7 4 5`...

* `g=:<@#~"#.2#:@i.@^#` Generate all subsets of the input, and save the verb that does this as `g` so we can use it again later.

```
┌┬─┬─┬───┬─┬───┬───┬─────┬─┬───┬───┬─────┬───┬─────┬─────┬───────┐
││5│4│4 5│7│7 5│7 4│7 4 5│2│2 5│2 4│2 4 5│2 7│2 7 5│2 7 4│2 7 4 5│
└┴─┴─┴───┴─┴───┴───┴─────┴─┴───┴───┴─────┴───┴─────┴─────┴───────┘

```
* `(g/.~+/&>)` Group subset elements by sum, and for each group of same-sum elements, generate all of *its* subsets:

```
┌┬─────────┬─────┬───────────┐
││┌┐       │     │           │
││││       │     │           │
││└┘       │     │           │
├┼─────────┼─────┼───────────┤
││┌─┐      │     │           │
│││5│      │     │           │
││└─┘      │     │           │
├┼─────────┼─────┼───────────┤
││┌─┐      │     │           │
│││4│      │     │           │
││└─┘      │     │           │
├┼─────────┼─────┼───────────┤
││┌───┐    │┌───┐│┌───┬───┐  │
│││2 7│    ││4 5│││4 5│2 7│  │
││└───┘    │└───┘│└───┴───┘  │
├┼─────────┼─────┼───────────┤
││┌───┐    │┌─┐  │┌─┬───┐    │
│││2 5│    ││7│  ││7│2 5│    │
││└───┘    │└─┘  │└─┴───┘    │
├┼─────────┼─────┼───────────┤
││┌───┐    │     │           │
│││7 5│    │     │           │
││└───┘    │     │           │
├┼─────────┼─────┼───────────┤
 etc...

```
* `[:(\:#&>)@,@` Flatten, and sort down by length:

```
┌─────────┬───────┬───────────┬──┬───┬───┐
│┌───┬───┐│┌─┬───┐│┌───┬─────┐│┌┐│┌─┐│┌─┐│
││4 5│2 7│││7│2 5│││7 4│2 4 5││││││5│││4││ ...etc..
│└───┴───┘│└─┴───┘│└───┴─────┘│└┘│└─┘│└─┘│
└─────────┴───────┴───────────┴──┴───┴───┘

```
* `<@/:~((i.~/:~@;&.>)>@{])` Find the first one whose elements match those of the input, and open it:

```
┌───┬───┐
│4 5│2 7│
└───┴───┘

```
> 7 votes

# Answer
# Jelly, 13 bytes

```
Œ!ŒṖ€Ẏ§E$ƇLÐṀ

```

Try it online!

Very slow, works on \\$O(2^{n!})\\$ complexity, where \\$n\\$ is the length of the array. Times out for anything with \\$n \ge 8\\$ on TIO.

This feels too long, especially the `Œ!ŒṖ€Ẏ` bit to generate all possible partitions.

This outputs all possible solutions, but the TIO link (the `ÇḢ` bit in the Footer) limits it to just one

## How it works

```
Œ!ŒṖ€Ẏ§E$ƇLÐṀ - Main link. Takes a list L on the left
Œ!            - All permutations of L
  ŒṖ€         - Get all partitions of each permutation
     Ẏ        - Drop these down into a single list of 2d lists
        $Ƈ    - Keep those for which the following is true:
      §       -   Sums of each sublist
       E      -   Are all equal
          LÐṀ - Get those with a maximal length

```
> 6 votes

# Answer
# 05AB1E, 12 bytes

```
œ€.œ€`éR.ΔOË

```

Try it online!

```
œ             # all permutations of the input
 €.œ          # for €ach permutation, get each partition
    €`        # flatten by one level to get a list of many partitions
      é       # sort by length (number of sublists in a partition)
       R      # reverse, longest are now at the front
        .Δ    # find the first partition where ...
          OË  # ... each sublist sums to the same value

```
> 5 votes

# Answer
# Brachylog, 12 bytes

```
∧≜S&p~c.+ᵛS∧

```

Try it online!

Even less efficient than caird's Jelly solution, as it recomputes every partition of every permutation for each sum it tries.

```
     ~c.        Output a partition of
   &p           a permutation of the input
        +ᵛ      in which every sublist has the same sum,
∧≜S       S∧    which is as small as possible.

```
> 5 votes

# Answer
# JavaScript (ES6), 124 bytes

```
f=(a,n=1)=>(g=(a,q=[],b=[],s=n)=>s?a.some((x,i)=>g(a.filter(_=>i--),q,[...b,x],s-x)):!a[Q=[...q,b],0]||g(a,Q))(a)?Q:f(a,n+1)

```

Try it online!

### Commented

```
f = (                       // f is a recursive function taking:
  a,                        //   a[] = input list
  n = 1                     //   n = target sum, starting with 1
) => (                      //
  g = (                     // g is a recursive function taking:
    a,                      //   the original a[] or a subset of it
    q = [],                 //   q[] = list of sublists
    b = [],                 //   b[] = current sublist
    s = n                   //   s = n minus the sum of the terms in b[]
  ) =>                      //
  s ?                       //   if s is not equal to 0:
    a.some((x, i) =>        //     for each value x at index i in a[]:
      g(                    //       do a recursive call to g:
        a.filter(_ => i--), //         remove the i-th element from a[]
        q,                  //         pass q[] unchanged
        [...b, x],          //         append x to b[]
        s - x               //         subtract x from s
      )                     //       end of recursive call
    )                       //     end of some()
  :                         //   else:
    !a[ Q = [...q, b],      //     Q[] = copy of q[] with b[] appended
        0                   //     test whether a[] is empty
    ] ||                    //     if it's not:
      g(a, Q)               //       recursive call to g with q[] = Q[]
)(a) ?                      // initial call to g; if a solution is found:
  Q                         //   return it
:                           // else:
  f(a, n + 1)               //   try again with n + 1

```
> 4 votes

# Answer
# Ruby, ~~110 109~~ 107 bytes

```
->l,*r{1.step.find{|x|l.permutation.find{|c|w=-1;r=c.chunk{|z|(w+=z)/x}.map &:last;r.all?{|v|v.sum==x}}};r}

```

Try it online!

### How:

* Starting with x=1, check if we can split the list into chunks whose sum is x.
* Do the same check with every possible permutation of the list.
* If not, increase x and try again.
* The trick is here: `c.chunk{|z|(w+=z)/x}`. This function splits an array into smaller
> 4 votes

# Answer
# Wolfram Language (Mathematica), 145 bytes

```
(l=Length@#;Catch[Do[If[SameQ@@Total/@(t=TakeList[p,i]),Throw@t],{d,Reverse@Divisors@Total@#},{i,IntegerPartitions[l,{d}]},{p,Permutations@#}]])&

```

Try it online!

Rough compromise between speed/memory optimization and code-golf.
The following facts are used:

* Array can only be splitted by the number of parts that are dividing its sum
* The lengths of parts of any split must be integer partition of length of array

Of course, one can optimize the search much better (for example, the dividers of the sum of the array must be less than its length), but it lengthens the code. On the other hand, I don’t want to take away given optimization, because it reduces runtime significantly.
> 1 votes

# Answer
# Scala, 773 bytes

\\$\text{773 bytes, it can be golfed much more.}\\$

Golfed version. Try it online!

```
def findX(list: List[Int]): Option[List[List[Int]]] = {
  @tailrec
  def findXRec(x: Int): Option[List[List[Int]]] = {
    list.permutations.collectFirst {
      case perm if {
            val chunks = perm.foldRight(List.empty[List[Int]]) {
              case (z, acc) =>
                if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
                else (z :: acc.head) :: acc.tail
            }
            chunks.forall(_.sum == x)
          } =>
        perm
    } match {
      case Some(perm) => {
        Some(perm.foldRight(List.empty[List[Int]]) { case (z, acc) =>
          if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
          else (z :: acc.head) :: acc.tail
        })
      }
      case None => findXRec(x + 1)
    }
  }
  findXRec(1)
}

```

Ungolfed version. Try it online!

```
import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    println(findX(List(9, 5, 1, 2, 9, 2)))
    println(findX(List(1, 1, 3, 5, 7, 4)))
    println(findX(List(2, 9, 6, 1, 5, 8, 2)))
    println(findX(List(2, 2, 2)))
    println(findX(List(2, 4, 5)))
  }

  def findX(list: List[Int]): Option[List[List[Int]]] = {
    @tailrec
    def findXRec(x: Int): Option[List[List[Int]]] = {
      val permutations = list.permutations
      val validPartition = permutations.collectFirst {
        case perm if {
          var w = -1
          val chunks = perm.foldRight(List.empty[List[Int]]) {
            case (z, acc) =>
              if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
              else (z :: acc.head) :: acc.tail
          }
          chunks.forall(_.sum == x)
        } => perm
      }
      validPartition match {
        case Some(perm) => {
          var w = -1
          Some(perm.foldRight(List.empty[List[Int]]) {
            case (z, acc) =>
              if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
              else (z :: acc.head) :: acc.tail
          })
        }
        case None => findXRec(x + 1)
      }
    }
    findXRec(1)
  }
}

```
> 1 votes

# Answer
# Julia 1.7 \+ Combinatorics, 74 bytes

```
using Combinatorics
~x=argmin(p->keys(sum.(p)∪0)=>sum.(p),partitions(x))

```

Attempt This Online!

`argmin(f, itr)` needs julia 1.7 or later
> 1 votes

# Answer
# Nekomata, 10 bytes

```
O:ᵐ∑≡$Ðaṁl

```

Attempt This Online!

```
O:ᵐ∑≡$Ðaṁl
O               Non-deterministically choose a set partition of the input
 :              Duplicate
  ᵐ∑            Sum each
    ≡           Check if all sums are equal, and get the equal value
     $Ð         Pair the sum with the partition
       a        Get all possible values
        ṁ       Minimum (by the sum)
         l      Take the last element (the partition)

```
> 1 votes

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


# Question
Title: 8-bit style bouncing ball around a canvas
Inspired by this listing from the Commodore 64 User's Guide:

```
10 PRINT "{CLR/HOME}"
20 POKE 53280,7 : POKE 53281,13
30 X = 1 : Y = 1
40 DX = 1 : DY = 1
50 POKE 1024 + X + 40 * Y, 81
60 FOR T = 1 TO 10 : NEXT
70 POKE 1024 + X + 40 * Y, 32
80 X = X + DX
90 IF X <= 0 OR X >= 39 THEN DX = -DX
100 Y = Y + DY
110 IF Y <= 0 OR Y >= 24 THEN DY = -DY
120 GOTO 50

```

Make a similar program in your chosen language/platform to bounce a ball-alike object around your terminal, screen, canvas or other visual display area.

You don't have to mimic the C64's PETSCII graphics exactly, a simple `O` or `o` will do, nor do you have to use the `GOTO` command if it exists in your language still. As long as your ball starts at the top of your canvas and travels diagonally until it hits a canvas limit, and then bounces accordingly, as follows:

* Travelling downwards and right and hits the bottom of the screen area, bounces up and continues right;
* Travelling up and right and hits the right-most boundary, and bounces left and up;
* Travelling left and up and hits the top, bounces left and down;
* Travelling left and down and reaches the left-most boundary, bounces right and down;
* Hits any corner and reverses direction;

Then we're all good.

You don't have to move the ball 8-pixels at a time either, like is happening in the BASIC listing on the C64; you can move one character block or one pixel at a time, whichever you think is most appropriate.

To see this BASIC listing working, you can type it in with this online Commodore 64 emulator providing your browser supports JavaScript.

# Answer
# 6502 machine code (C64), 90 89 91 bytes

+2 bytes because it **needs** a load address (not PIC because of self modification)

```
00 C0 20 44 E5 CA D0 FD C6 FC D0 F9 A2 20 86 FC A9 D8 85 9E A9 03 85 9F A4 CA
18 A5 9E 69 28 85 9E 90 02 E6 9F 88 10 F2 A4 C9 8A 91 9E C9 20 D0 08 E6 C9 E6
CA A2 51 10 D7 A5 C9 F0 04 C9 27 D0 08 AD 2F C0 49 20 8D 2F C0 A5 CA F0 04 C9
18 D0 B4 AD 31 C0 49 20 8D 31 C0 D0 AA

```

**Online demo**

Usage: `sys49152`

I tried hard to reduce size (e.g. NOT using IRQs for timing but stupid empty loops instead), still impossible to reach the level of Titus' golfed C64 BASIC :o oh, well. But it looks less flickering ;)

**Explanation:** (vice disassembly)

```
00 C0       .WORD $C000         ; load address
20 44 E5    JSR $E544           ; clear screen
CA          DEX
D0 FD       BNE $C003           ; inner wait (256 decrements)
C6 FC       DEC $FC
D0 F9       BNE $C003           ; outer wait (32 decrements in zeropage)
A2 20       LDX #$20            ; wait counter and screen code for "space"
86 FC       STX $FC             ; store wait counter
A9 D8       LDA #$D8            ; load screen base address ...
85 9E       STA $9E             ; ... -40 (quasi row "-1") ...
A9 03       LDA #$03            ; ... into vector at $9e/$9f
85 9F       STA $9F
A4 CA       LDY $CA             ; load current row in Y
18          CLC                 ; clear carry flag
A5 9E       LDA $9E             ; add ...
69 28       ADC #$28            ; ... $28 (40 cols) to ...
85 9E       STA $9E             ; ... vector
90 02       BCC $C023
E6 9F       INC $9F             ; handle carry
88          DEY                 ; count rows down
10 F2       BPL $C018
A4 C9       LDY $C9             ; load current col in Y
8A          TXA                 ; copy screen code from X to A
91 9E       STA ($9E),Y         ; store at position of screen
C9 20       CMP #$20            ; screen code was "space"
D0 08       BNE $C037           ; if not, ball was drawn
E6 C9       INC $C9             ; next column   | opcodes are modified
E6 CA       INC $CA             ; next row      | here for directions
A2 51       LDX #$51            ; screen code for "ball"
10 D7       BPL $C00E           ; and back to drawing code
A5 C9       LDA $C9             ; load current column
F0 04       BEQ $C03F           ; if zero, change X direction
C9 27       CMP #$27            ; compare with last column (39)
D0 08       BNE $C047           ; if not equal, don't change X direction
AD 2F C0    LDA $C02F           ; load opcode for X direction
49 20       EOR #$20            ; toggle between ZP INC and DEC
8D 2F C0    STA $C02F           ; store back
A5 CA       LDA $CA             ; load current row
F0 04       BEQ $C04F           ; if zero, change Y direction
C9 18       CMP #$18            ; compare with last row (24)
D0 B4       BNE $C003           ; if not equal, don't change Y direction
AD 31 C0    LDA $C031           ; load opcode for Y direction
49 20       EOR #$20            ; toggle between ZP INC and DEC
8D 31 C0    STA $C031           ; store back
D0 AA       BNE $C003           ; -> main loop

```

---

Just for fun, here's a more professional variant using a sprite for the ball and flashing the border when hit in **385** bytes (containing the sprite data that's used *in place*):

```
00 C0 AD 15 D0 F0 30 A9 CC 85 FC A9 04 20 A2 C0 A9 97 8D 00 DD A9 15 8D 18 D0
A9 00 8D 15 D0 8D 1A D0 A2 81 8E 0D DC A2 31 8E 14 03 A2 EA 8E 15 03 58 A6 D6
4C F0 E9 A9 04 85 FC A9 CC 20 A2 C0 A2 31 86 01 A2 10 A9 D0 85 FC B1 FB C6 01
91 FB E6 01 C8 D0 F5 E6 FC CA D0 F0 A9 37 85 01 A9 94 8D 00 DD A9 35 8D 18 D0
8D 27 D0 A2 05 8E F8 CF A2 01 8E 15 D0 8E 1A D0 8E 12 D0 86 FD 86 FE A2 18 8E
00 D0 A2 1B 8E 11 D0 A2 32 8E 01 D0 A2 7F 8E 0D DC AE 0D DC AE 20 D0 86 FB A2
C1 8E 14 03 A2 C0 D0 8A 85 FE 8D 88 02 A9 00 85 FB 85 FD A2 04 A0 00 78 B1 FB
91 FD C8 D0 F9 E6 FC E6 FE CA D0 F2 60 A6 FB 8E 20 D0 CE 19 D0 A5 FD F0 20 AD
00 D0 18 69 04 8D 00 D0 90 03 EE 10 D0 C9 40 D0 2C AD 10 D0 29 01 F0 25 20 38
C1 C6 FD F0 1E AD 00 D0 38 E9 04 8D 00 D0 B0 03 CE 10 D0 C9 18 D0 0C AD 10 D0
29 01 D0 05 20 38 C1 E6 FD A5 FE F0 14 AD 01 D0 18 69 04 8D 01 D0 C9 E6 D0 19
20 38 C1 C6 FE F0 12 AD 01 D0 38 E9 04 8D 01 D0 C9 32 D0 05 20 38 C1 E6 FE 4C
31 EA A9 01 8D 20 D0 60 00 00 00 7E 00 03 FF C0 07 FF E0 1F FF F8 1F FF F8 3F
FF FC 7F FF FE 7F FF FE FF FF FF FF FF FF FF FF FF FF FF FF 7F FF FE 7F FF FE
3F FF FC 1F FF F8 1F FF F8 07 FF E0 03 FF C0 00 7E 00 00 00 00

```

**Online demo** -|- **browse ca65 assembler source**

Start and stop the bouncing ball with `sys49152`.

* This leaves the C64 BASIC running, that's done by moving the VIC-II address space up to `$C000`, which requires copying the screen contents and the character set (font).
* It hooks into the system IRQ and to avoid flicker, changes the source of this IRQ to the VIC-II graphics chip, so updates are always done between frames.
* Glitches:
    1. `RUN/STOP + RESTORE` is broken, don't try.
    2. With the VIC-II as IRQ source, the cursor blinks slightly slower and `TI$` will lag behind as well.
    3. when stopping while the border is flashed (very unlikely but possible), it **stays** white -- you have to restore it manually.
> 4 votes

# Answer
# Bash + Unix utilities, ~~125~~ 117 bytes

```
for((x=y=u=v=1;;x+=u,y+=v,u=(x<1||x>=`tput cols`-1)?-u:u,v=(y<1||y>=`tput lines`-1)?-v:v)){
tput cup $y $x
sleep .1
}

```

---

Animation of sample run:
> 17 votes

# Answer
## CP-1610 assembly, ~~67~~~~64~~ 62 DECLEs = 78 bytes

This code is intended to be run on an Intellivision. It's using one of its hardware sprites, known as a MOB (for Mobile Object).

A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This program is 62 DECLEs long, starting at $4800 and ending at $483D.

### Hexadecimal dump + source

```
                            ROMW  10            ; use 10-bit ROM
                            ORG   $4800         ; start program at address $4800

                    FRAME   EQU   $17E          ; frame #

                            ;; ------------------------------------------------ ;;
                            ;;  main entry point                                ;;
                            ;; ------------------------------------------------ ;;
                    main    PROC

4800 0001                   SDBD                ; load Interrupt Service Routine
4801 02B8 002B 0048         MVII  #isr,   R0    ; into R0

4804 0240 0100              MVO   R0,     $100  ; update ISR
4806 0040                   SWAP  R0
4807 0240 0101              MVO   R0,     $101

4809 02B9 0208              MVII  #$0208, R1    ; initialize R1 = X
480B 02BA 0108              MVII  #$0108, R2    ; initialize R2 = Y
480D 02BB 0001              MVII  #1,     R3    ; initialize R3 = DX
480F 009C                   MOVR  R3,     R4    ; initialize R4 = DY

4810 0002                   EIS                 ; enable interrupts

                            ;; ------------------------------------------------ ;;
                            ;;  main loop                                       ;;
                            ;; ------------------------------------------------ ;;
4811 0280 017E      @@loop  MVI   FRAME,  R0    ; R0 = current frame #

4813 0340 017E      @@spin  CMP   FRAME,  R0    ; wait for next frame
4815 0224 0003              BEQ   @@spin

4817 00D9                   ADDR  R3,     R1    ; X += DX

4818 0379 02A0              CMPI  #$2A0,  R1    ; reached right border?
481A 0204 0003              BEQ   @@updDx

481C 0379 0208              CMPI  #$208,  R1    ; reached left border?
481E 002F                   ADCR  PC

481F 0023           @@updDx NEGR  R3            ; DX = -DX

4820 00E2                   ADDR  R4,     R2    ; Y += DY

4821 037A 0160              CMPI  #$160,  R2    ; reached bottom border?
4823 0204 0003              BEQ   @@updDy

4825 037A 0108              CMPI  #$108,  R2    ; reached top border?
4827 002F                   ADCR  PC

4828 0024           @@updDy NEGR  R4            ; DY = -DY

4829 0220 0019              B     @@loop        ; loop forever

                            ENDP

                            ;; ------------------------------------------------ ;;
                            ;;  ISR                                             ;;
                            ;; ------------------------------------------------ ;;
                    isr     PROC

482B 01DB                   CLRR  R3            ; clear a bunch of STIC registers
482C 02BC 0020              MVII  #$20,   R4

482E 0263           @@clear MVO@  R3,     R4    ; (including background color,
482F 037C 0032              CMPI  #$32,   R4    ; border color, etc.)
4831 0226 0004              BLE   @@clear

4833 0259                   MVO@  R1,     R3    ; update X register of MOB #0
4834 0242 0008              MVO   R2,     $8    ; update Y register of MOB #0
4836 02BB 017E              MVII  #$017E, R3    ; update A register of MOB #0
4838 0243 0010              MVO   R3,     $10   ; (using a yellow "O")

483A 0298                   MVI@  R3,     R0    ; increment frame #
483B 0008                   INCR  R0
483C 0258                   MVO@  R0,     R3

483D 00AF                   JR    R5            ; return from ISR

                            ENDP

```

### Output
> 13 votes

# Answer
# TI-BASIC, ~~71~~ 70

```
1->A
1->B
1->C
1->D
While 1
ClrHome
Output(B,A,0
A+C->A
B+D->B
If A<2 or A>15
~C->C
If B<2 or B>7
~D->D
End

```

Quite literal translation, I wouldn't be surprised if there are tricks to make it smaller.

The screen is 16x8 and 1-indexed so the constants are different.

`~` is the SourceCoder way to write the negation symbol.

It looks smoother on hardware.
> 11 votes

# Answer
# HTML (Microsoft Edge/Internet Explorer), 81 bytes

Pretend it's 1998 with these nested `<marquee>` tags:

```
<marquee behavior=alternate direction=down><marquee behavior=alternate width=99>O
```

Tested in Microsoft Edge, though from what I've read IE should also still support marquees. Decidedly does *not* work in Chrome.

Setting `direction=up` would save 2 bytes, but break the rule that the ball has to start at the top of the canvas.
> 10 votes

# Answer
# Befunge, 209 bytes

```
>10120130pppp>"l52?[J2["39*,,,,39*,,,,,,v
v+56/+55\%+55:+1g01*83-"6!"7\-"6!?"8-*86<
>00g1+:55+%\55+/"+!6"-48*,68>*#8+#6:#,_v$
v:+g03g01p02+-\g02*2!-*64\*2!:p00:+g02g<$
>10p:!2*\"O"-!2*30g\-+30p"2"::**>:#->#1_^

```

This assumes a screen size of 80x25, but you can easily tweak the range by replacing the `"O"` (79) on the last line and the `*64` (24) on the second last line (note that the second last line is executed right to left). The speed can also be adjusted by replacing the `"2"` (50) on the last line.
> 7 votes

# Answer
# Java, ~~184~~ 176 bytes

```
class A{public static void main(String[]a)throws Exception{for(int X=1,Y=1,x=1,y=1;;System.out.print("\033["+X+";"+Y+"H"),Thread.sleep(50),X+=x=X%25<1?-x:x,Y+=y=Y%85<1?-y:y);}}

```

This makes use of ANSI Escape Sequences to relocate the cursor, which is the object that bounces around a `85 x 25` terminal display. Save in a file named `A.java`.

## Ungolfed

```
class Terminal_Bouncing_Ball {
    public static void main(String[] args) throws InterruptedException {
        int X = 0, Y = 0, dx = 1, dy = 1;
        while (true) {
            System.out.print(String.format("\033[%d;%dH",X,Y));
            Thread.sleep(50);
            dx = (X < 1) ? 1 : (X > 71) ? -1 : dx;
            dy = (Y < 1) ? 1 : (Y > 237) ? -1 : dy;
            X += dx;
            Y += dy;
        }
    }
}

```

## Demo
> 7 votes

# Answer
# Clojure, ~~398~~ ~~380~~ 375 bytes

```
(ns g(:require[quil.core :as q]))(def w 1e3)(def h 1e3)(def f 100)(def b(atom{:x f :y f :n 1 :m 1}))(q/defsketch . :size[w h]:setup #(do(q/text-font(q/create-font""f))(q/fill 255 255 255)):draw #(let[s 9{x :x y :y n :n m :m}@b c(+ x(* n s))u(+ y(* m s))](q/background 0 0 0)(reset! b{:x c :y u :n(if(< 0 c(- w f))n(* -1 n)):m(if(<(+ 0 f)u h)m(* -1 m))})(q/text"O"(:x @b)(:y @b))))

```

-18 bytes by changing the font name to an empty string to default it, inlining the boundary checks, and fixing the bottom boundary issue (which you can see in the GIF). Fixing that actually saved bytes.

-5 bytes by changing to a more succinct destructuring syntax and shrinking the ball by a pixel.

Uses Quil.

I tried to switch to functional mode, but it required a lot of extra code and ended up being more expensive.

```
(ns bits.golf.ball-bounce
  (:require [quil.core :as q]))

(def width 1000)
(def height 1000)

(def font-size 100)

; Mutable state holding the properties of the ball. n and m are the directions on the x and y axis.
(def ball (atom {:x 300 :y 600 :n 1 :m 1}))

(q/defsketch b
  :size [width height] ; Window size

  :setup #(do
            (q/text-font (q/create-font "Arial" font-size)) ; Set the font
            (q/fill 255 255 255)) ; And the text color

  :draw
  #(let [speed 9
         ; Deconstruct the state
         {:keys [x y n m]} @ball
         next-x (+ x (* n speed))
         next-y (+ y (* m speed))

         ; I'm adding/subtracting the font-size so it stays in the window properly
         x-inbounds? (< 0 next-x (- width font-size))
         y-inbounds? (< (+ 0 font-size) next-y height)]

     ; Wipe the screen so the ball doesn't smear
     (q/background 0 0 0)

     ; Reset the state
     (reset! ball
             {:x next-x
              :y next-y
              :n (if x-inbounds? n (* -1 n))
              :m (if y-inbounds? m (* -1 m))})

     ; Draw the ball
     (q/text "O" (:x @ball) (:y @ball))))

```

(Note, the new version doesn't bounce early along the bottom of the screen like it does in the GIF.)
> 4 votes

# Answer
## Racket 247 bytes

```
(let*((w 500)(h(* w 0.6))(x 100)(y 0)(d 10)(e d)(G(λ(t)(set! x(+ x d))(when(or(> x w)(< x 0))
(set! d(* d -1)))(set! y(+ y e))(when(or(> y h)(< y 0))(set! e(* e -1)))
(underlay/xy(rectangle w h"solid""white")x y(circle 10"solid""black")))))(animate G))

```

Ungolfed:

```
(require 2htdp/image
         2htdp/universe)

(let* ((wd 500)            ; define variables and their initial values
       (ht 300)
       (x 100)
       (y 0)
       (dx 10)
       (dy 10)

       (imgfn              ; define function to draw one frame; called repeatedly by animate fn;
        (λ (t)             ; t is number of ticks till now- sent by animate fn; ignored here;

                           ; update location (x and y values):
          (set! x (+ x dx))
          (when (or (> x wd) (< x 0))
            (set! dx (* dx -1)))             ; invert direction at edges
          (set! y (+ y dy))
          (when (or (> y ht) (< y 0))
            (set! dy (* dy -1)))             ; invert direction at edges

                           ; draw image:
          (underlay/xy
           (rectangle wd ht "solid" "white") ; draw background
           x y                               ; go to location (x,y)
           (circle 10 "solid" "black")       ; draw ball
          ))))

  (animate imgfn))         ; animates the images created by imgfn (default rate 28 times/sec)

```

Output:
> 4 votes

# Answer
# Simons´ BASIC (C64), ~~66~~ 65 bytes

One byte saved thanks @ShaunBebbers.

I need only one line here, because Simons´ Basic has a modulo function.
AfaIk, this requires a physical C64 and a Simons´ BASIC module
(or any other BASIC extension that has a `mod` function).

```
0fori=0to623:print"{CLR}":poke1024+40*abs(mod(i,48)-24)+abs(mod(i,78)-39),81:next:goto

```

Type in these 69 characters:

```
0fOi=0TO623:?"{CLR}":pO1024+40*aB(mod(i,48)-24)+aB(mod(i,78)-39),81:nE:gO

```

`{CLR}` is PETSCII 147, which clears the screen. Use Shift+CLR/HOME to type it in.

**bytecount**

When saved to disk, it takes 65 bytes, because the commands are tokenized:
`for`, `to`, `poke`, `abs`, `next` and `goto` are one byte each; `mod` takes two bytes.
That makes 59 bytes of code plus 4 bytes for pointers and 2 bytes for the line number.

For reference, see Mapping the C64 and search for `$800` (BASIC Program Text).
(You can find the Video Screen Memory Area at `$400`.)

**breakdown**

The program loops `I` from 0 to 623 (=LCM of 48 and 78 minus 1). In the loop

* the screen is cleared
* `I` gets mapped to 39..0..38 respectively 24..0..23
* and the blob (PETSCII 81) is put at the corresponding position in the video memory
(like the original program does).

When the loop is done, the program is restarted by jumping to line 0.

# C64 BASIC, ~~77~~ 76 bytes

```
0fori=0to623:print"{CLR}"
1poke1024+40*abs(i-48*int(i/48)-24)+abs(i-78*int(i/78)-39),81:next:goto

```

---

Unfortunately I need two lines, because even with all possible abbreviations it would take 83 characters - too many to use the C64 line editor:

```
0fOi=0to623:?"{CLR}":pO1024+40*aB(i-48*int(i/48)-24)+aB(i-78*int(i/78)-39),81:nE:gO

```

(A hex editor could be used to create a longer line - which would make it 73 bytes.)
> 4 votes

# Answer
# Jelly, 37 bytes

```
“ñc‘Ọ24ḶŒḄṖ⁸ị⁷x⁸µ80ḶŒḄṖ⁸ị⁶x⁸‘œS.1
Ç1¿

```

With some help from this answer for getting the loop and escape characters right. Currently it bounces around in a 80x24 screen, but that can be easily modified in the code.

The coördinates in each direction can be represented as elements of two lists `[0, 1,..., 24, 23,..., 1]` and `[0, 1,..., 80, 79,..., 1]`, let's call them `Y` and `X`, that are infinitely repeated. This infinite repetition can be emulated using modular indexing -- using  in Jelly. Example: in the `i`th iteration the ball is at position `(X[i%|X|], Y[i%|Y|]) = (iịY, iịX)`. The moving *ball* is just the cursor that is put into position by emitting `iịY` newlines and `iịX` spaces.

## Demo

## Explanation

```
“ñc‘Ọ24ḶŒḄṖ⁸ị⁷x⁸µ80ḶŒḄṖ⁸ị⁶x⁸‘œS.1        Monadic helper link - argument i.
                                         Resets the terminal, prints Y[i] newlines,
                                         X[i] spaces and returns i + 1.
“ñc‘                                     Set the output to [27, 99]
    Ọ                                    Convert to characters and print (\x1bc)
                                          -> Cursor is at position (0,0)
     24Ḷ                                 Lowered range of 24. Yields [0,...,23].
        ŒḄ                               Bounce. Yields [0,...,23,22,...,0].
          Ṗ                              Pop. Yields [0,...,23,22,...,1] = Y.
           ⁸ị                            Modular index i (⁸) into Y. The current
                                         value is the Y coordinate, y.
              x                          Repeat y times
             ⁷                           the newline character ('\n').
               ⁸                         Output that (y times '\n') and continue
                                         with value i.
                                          -> Cursor is at position (0, y)
                µ                        Monadic chain separation.
                 80ḶŒḄṖ                  Same as above, but this time yielding X.
                       ⁸ị                Modular index i into X, yielding the
                                         value for x.
                          x              Repeat x times
                         ⁶               the whitespace character.
                           ⁸             Output that (x times ' ') and continue
                                         with value i.
                                         -> Cursor is at position (x, y), the
                                            final position.
                             œS.1        Wait 0.1 seconds.
                            ‘            Return i + 1.

Ç1¿                                      Main (niladic) link.
 1¿                                      While true.
Ç                                        Call the helper link. The first time
                                         there is no argument and i will be [],
                                         which is cast to 0 when used as integer
                                         (e.g. try ‘¶Ç). After that, the previous
                                         return value (i + 1) is used.

```
> 3 votes

# Answer
# SmileBASIC, ~~85~~ 74 bytes

```
SPSET.,9M=MAINCNT
SPOFS.,ASIN(SIN(M/5))*122+192,112+71*ASIN(SIN(M/3))EXEC.

```

The position of the ball can be modelled with 2 triangle waves, and the shortest way I could find to produce them in SmileBASIC was arcsine(sine(x)). (the algorithm using MOD was longer since SB uses `MOD` instead of `%`)
> 2 votes

# Answer
## CSS/HTML, 200 + 7 = 207 bytes

```
p{position:relative}a{position:absolute;animation:infinite linear alternate;animation-name:x,y;animation-duration:7.9s,2.3s}@keyframes x{from{left:0}to{left:79ch}}@keyframes y{from{top:0}to{top:24em}}
```

```
<p><a>O
```

This version shows you the size of the canvas and also gives the animation a more pixilated feel:

```
p {
  position: relative;
  width: 80ch;
  height: 25em;
  border: 1px solid black;
}
a {
  position: absolute;
  animation: infinite alternate;
  animation-name: x, y;
  animation-duration: 7.9s, 2.3s;
  animation-timing-function: steps(79), steps(23);
}
@keyframes x {
  from {
    left: 0;
  } to {
    left: 79ch;
  }
}
@keyframes y {
  from {
    top: 0;
  } to {
    top: 24em;
  }
}
```

```
<p><a>O</a></p>
```
> 2 votes

# Answer
# PHP, ~~112~~ ~~97~~ ~~94~~ ~~103~~ 102 bytes

```
for(;;usleep(1e5),$i%=624)echo($r=str_repeat)(A^K,99),$r(A^a,abs($i%78-39)),O,$r(A^K,abs($i++%48-24));

```

bounces a capital `O` on a 40x25 grid, starting at the top right corner;
prints 99 newlines to clear the screen.

Run with `-nr`.

`A^K` = `chr(10)` = newline
`A^a` = `chr(32)` = space
> 2 votes

# Answer
# Dyalog APL, 44 bytes

```
{⎕SM∘←0,G←⍺+⍵⋄G∇⍵×1-2×⊃1 G∨.≥G⎕SD⊣⎕DL.1}⍨1 1

```

Explanation:

* `{`...`}⍨1 1`: call the given function with ⍺=⍵=1 1
    + `⎕SM∘←0,G←⍺+⍵`: store `⍺+⍵` in `G`, display a `0` at that location in the `⎕SM` window.
    + `⎕DL.1`: wait 1/10th of a second
    + `⊃1 G∨.≥G⎕SD`: check if `G` is at the `⎕SM` window boundary (`1≥G` or `G≥⎕SD`, `⎕SD` is the **s**creen **d**imensions)
    + `1-2×`: map `[1,0]` onto `[¯1,1]`, to flip the direction of travel
    + `⍵×`: multiply the current direction of travel by that
    + `G∇`: recursion, let `G` be the new location () and `⍵....` be the new direction ().
> 2 votes

# Answer
# C + curses, 190 bytes

```
#include<curses.h>
w;h;x;y;d;main(e){initscr();curs_set(0);getmaxyx(stdscr,h,w);for(d=e;;usleep(20000),mvaddch(y,x,32)){mvaddch(y+=d,x+=e,48);if(!y||y>h-2)d=-d;if(!x||x>w-2)e=-e;refresh();}}

```

**Explanation:**

```
#include<curses.h>
w;h;x;y;d;
main(e)
{
    initscr();
    curs_set(0);
    getmaxyx(stdscr,h,w);

    // initialize distances to 1 (e is 1 when called without arguments)
    // wait for 1/5 second, then write space character at current pos
    for(d=e;;usleep(20000),mvaddch(y,x,32))
    {
        // advance current pos and write ball character (`0`)
        mvaddch(y+=d,x+=e,48);

        // check and change direction:
        if(!y||y>h-2)d=-d;
        if(!x||x>w-2)e=-e;

        // trigger output to screen:
        refresh();
    }
}

```
> 2 votes

# Answer
# QBasic, 71 bytes

```
DO
CLS
LOCATE 24-ABS(i MOD 46-23),80-ABS(i MOD 158-79)
?"O";
i=i+1
LOOP

```

This version loops forever, although it might break when `i` gets too large--I haven't tested. Also, how fast it moves depends on the hardware you use, but on the emulator at Archive.org it runs too fast to see the motion. Therefore, here's a somewhat friendlier version that terminates once the ball gets back to the top left corner:

```
FOR i=0TO 3634
CLS
LOCATE 24-ABS(i MOD 46-23),80-ABS(i MOD 158-79)
?"O";
z=COS(1)
NEXT

```

Change the `COS(1)` to `COS(1)+COS(1)+COS(1)` (etc.) to slow it down further. Try it here!

### Explanation

Our bounding box is QBasic's standard text mode screen, 80 characters wide by 24 characters tall, 1-indexed. As several other answers have observed, we can calculate the correct x and y coordinates, given a frame number, using modular arithmetic:

| Frame `i` | `i MOD 46` | `(i MOD 46)-23` | `ABS((i MOD 46)-23)` | y = `24-ABS(...)` | x = `80-ABS(...)` |
| --- | --- | --- | --- | --- | --- |
| 0 | 0 | -23 | 23 | 1 | 1 |
| 1 | 1 | -22 | 22 | 2 | 2 |
| 22 | 22 | -1 | 1 | 23 | 23 |
| 23 | 23 | 0 | 0 | 24 | 24 |
| 24 | 24 | 1 | 1 | 23 | 25 |
| 45 | 45 | 22 | 22 | 2 | 46 |
| 46 | 0 | -23 | 23 | 1 | 47 |
| 47 | 1 | -22 | 22 | 2 | 48 |
| 79 | 33 | 10 | 10 | 14 | 80 |
| 80 | 34 | 11 | 11 | 13 | 79 |

After that it's just an issue of clearing the screen with `CLS`, moving to the proper coordinates with `LOCATE`, and printing `"O"`.
> 2 votes

# Answer
# Python 2, ~~176~~ 168 Bytes

This assumes a terminal size of 80x24. Definitely not optimal but I'm new to golfing so yeah.

```
import time;x=y=d=e=1
while 1:
 m=[[' 'for i in' '*80]for j in' '*24];x+=d;y+=e;m[y][x]='O';time.sleep(.1)
 if x%79<1:d=-d
 if y%23<1:e=-e
 for r in m:print''.join(r)

```

Thanks to R. Kap for suggesting the x%79\<1 instead of x\<1or x\>79 and ditto for y.
> 1 votes

# Answer
# Rebol/View, 284 266 bytes

```
rebol[]p: 3x9 d:[3 3]view layout[b: box blue 99x99 effect[draw[circle p 2]]rate :0.01 feel[engage: func[f a e][if a = 'time[case/all[p/x < 2[d/1: abs d/1]p/y < 2[d/2: abs d/2]p/x > 98[d/1: negate d/1]p/y > 98[d/2: negate d/2]]p/x: p/x + d/1 p/y: p/y + d/2 show b]]]]

```

Ungolfed:

```
rebol []

p: 3x9     ;; starting position
d: [3 3]   ;; direction

view layout [
    b: box blue 99x99 effect [
        draw [
            circle p 2
        ]
    ]

    rate :0.01 feel [
        engage: func [f a e] [
            if a = 'time [
                case/all [
                    p/x < 2  [d/1: abs d/1]
                    p/y < 2  [d/2: abs d/2]
                    p/x > 98 [d/1: negate d/1]
                    p/y > 98 [d/2: negate d/2]
                ]
                p/x: p/x + d/1
                p/y: p/y + d/2
                show b
            ]
        ]
    ]
]

```
> 1 votes

# Answer
## C 294 bytes

```
#include<graphics.h> f(){int d=0;g,x,y,a=0,b=0;initgraph(&d,&g,NULL);x=30;y=30;while(1){x+=6;y+=7;if(y<60)b=0;if(x<60)a=0;if((y>getmaxy()-40)) b=!b;if((x>getmaxx()-40))a=!a;if(b){y-=18;x+=3;}if(a){x-=15;y+=2;}usleep(10000);setcolor(4);cleardevice();circle(x, y,30);floodfill(x,y,4);delay(45);}}

```

Ungolfed version:

```
#include<graphics.h>
void f()
{
 int d=DETECT,g,x,y,r=30,a=0,b=0;
 initgraph(&d,&g,NULL);
 x=30;
 y=30;

 while(1)
 {
   x+=6;
   y+=7;

   if(y<60)
     b=0;
   if(x<60)
     a=0;

   if((y>getmaxy()-40))
        b=!b;

   if((x>getmaxx()-40))
        a=!a;

    if(b)
    {
        y-=18;
        x+=3;
    }

    if(a)
    {
       x-=15;
       y+=2;
    }
    usleep(10000);
    setcolor(RED);
    cleardevice();
    circle(x,y,r);
    floodfill(x,y,RED);
    delay(45);

  }

}

```

## Explanation

* So in order to begin with this, I had to get `graphics.h` in my `/usr/include` directory. Therefore, i searched and this is what I found. It is a TurboC Graphics implementation using SDL for Linux. One could also use OpenGL. In windows, I guess it is already installed, not sure about MacOS.
* `void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);` initialises the system and puts it in a graphics mode, in this case graphics driver is automatically detected. Please refer to this link for more details.
* `x` and `y` are coordinates that determines the ball's position.
* `a` and `b` are flags, `a` is set to zero when the `x` value drops below 60 and `b` is set to zero when `y` drops below 60.
* The flags are toggled when `x` and `y` exceeds boundary values of window, and the coordinates are accordingly adjusted.
* I put a `usleep` so that my CPU does not get stressed out.
* One should normally use a `closegraph()` call, in order to close the window. But it's missing here.

Must be compiled with the linker flag `-lgraph`

It runs smoother on real hardware. :)
> 1 votes

# Answer
# MATL, 42 bytes

```
1thXH_XI`Xx8E70hZ"79HZ}&(DH4M\1>EqI*XIH+XH

```

This uses a 70×16 screen and character `O`. If you wait for a few bounces you'll see the ball hitting a corner.

**Try at MATL Online!**

Screen size can be easily modified in the code. The relevant part is `8E70`, which pushes `8`, doubles it, and pushes `70`. For example, for a 80×25 screen replace by `5W80`, which pushes `5`, squares it, and pushes `80` (or replace by `25 80`, but that requires one more byte).

Also, adding `tD` at the end of the code shows the current position in real time (vertical, then horizontal, `1 1` is upper left). As an example, for a `80×18` screen,

```
1thXH_XI`Xx9E80hZ"79HZ}&(DH4M\1>EqI*XIH+XHtD

```

**Try it too!**

### Explanation

This uses an infinite loop. Position is kept in clipboard `H` as a 1×2 vector, and direction is kept in clipboard `I` as a 1×2 vector with entries `1` or `-1`.

Each iteration clears the screen, defines a matrix of spaces, writes an `O` at the relevant position, and displays it. Then the position and directio need to be updated.

Position is `1`-based, and thus the edges of the screen are `1` and the maximum screen size. So if position modulo screen size gives `0` or `1` in either the first or second components, which means we have reached a vertical or horizontal edge respectively, that component of the direction vector is negated. After that, the new direction is added to the current position to obtain the new position.
> 1 votes

# Answer
Here's the ZX Spectrum listing.

```
  10 FOR n=0 to 7
  20 READ a: POKE USR "a"+n, a
  30 NEXT n
  40 DATA 60,126,243,251,255,255,126,60
  50 LET x=10:LET y=10:LET vx=1: LET vy=1
  60 PRINT AT y,x;"\a"
  70 IF x<1 OR x>30 THEN LET vx=-vx
  80 IF y<1 OR x>20 THEN LET vy=-vy
  90 LET x=x+vx: LET y=y+vy
 100 PRINT AT y-vy,x-vx;" ": GO TO 60

```
> 1 votes

# Answer
# CHIP-8, ~~36~~ ~~34~~ 28 bytes

```
FF29 'LDF I,vF //load digit sprite for the value of vF (should be 0)

4000 'SNE v0,0 //if x is 0...
6201 'LD v2,1 //set x velocity to 1
403C 'SNE v0,3C //if x is 3C...
62FF 'LD v2,FF //set x velocity to -1
4100 'SNE v1,0 //if y is 0...
6301 'LD v3,1 //set y velocity to 1
411B 'SNE v1,1B //if y is 1B...
63FF 'LD v3,FF //set y velocity to -1

D015 'DRW v0,v1,5 //draw sprite
D015 'DRW v0,v1,5 //draw sprite again to clear it.
8024 'ADD v0,v2 //add x velocity to x
8134 'ADD v1,v3 //add y velocity to y

1202 'JMP 202 //jump to second instruction

```

No fancy tricks here...

Requires an interpreter that draws sprites correctly (only one sprite can be drawn per frame, which slows down the program enough for you to be able to see it).

Low quality video
> 1 votes

# Answer
# Lua (LÖVE 2D), 130 bytes

```
x,y,a,b=0,0,1,1
function love.draw()a=(x<0 or x>800)and-a or a
b=(y<0 or y>600)and-b or b
x=x+a
y=y+b
love.graphics.points(x,y)end

```

Lua is not the best language when it comes to code golf, but here you go! A few points worth mentioning:

* The default canvas size is 800 x 600. It can be changed in the configuration file, but I didn't see any size restrictions, so I left it as is.
* `love.draw()` is LÖVE's drawing function and it has a predetermined name. Alternative LÖVE functions that could be used would be `love.update(dt)` and `love.run()` -- the first being longer, in bytes, and the latter being shorter, yes, but without a built-in infinite loop. Thus, `draw()` seems to be our best bet here.
* The above version uses `love.graphics.points` to draw the ball. Although shorter, I am not sure it is allowed. Here is a GIF of how it runs:

As you can see (or perhaps can't), there is a single pixel moving on the screen. While that saves up bytes, it's not the most satisfying of results.

So I've made an **alternative 131 bytes solution**:

```
x,y,a,b=0,0,1,1
function love.draw()a=(x<0 or x>795)and-a or a
b=(y<0 or y>595)and-b or b
x=x+a
y=y+b
love.graphics.print(0,x,y)end

```

This one uses `love.graphics.print` -- which prints text -- and a `0` as a ball, making it much more visible and appealing.
> 1 votes

# Answer
## PostScript (GhostScript), 259 bytes

I don't think PostScript was built for animation... improvements welcome!

```
[/x{4}/y{196}/X{2}/Y{-2}/b{x y 4 currentgray add 0 360 arc fill}/p{/x x X add def}/q{/y y Y add def}/g{setgray}>>begin[/PageSize[320 200]>>setpagedevice{1 g
b p q
x 316 gt x 4 lt or{/X X -1 mul def}if
y 196 gt y 4 lt or{/Y Y -1 mul def}if
0 g b flushpage}loop

```

Needs GhostScript for `flushpage`.

(It runs smoother when the screen recorder isn't also running.)
> 1 votes

# Answer
# Commodore C64 BASIC - 75 71 tokenised BASIC bytes, 77 73 characters with keyword abbreviations

The following answer is taken from the YouTube channel 8-BIT Show and Tell, so Robin Harbron deserves the credit, along with credit to the YouTube channel JosipRetroBits.

```
 0?"{CLEAR}":DEFFNA(B)=ABS(T-INT(T/B)*B-B/2):POKE1024+FNA(48)*40+FNA(78),81:T=T+1:GOTO

```

### Older solution

```
 0?"{CLEAR}":DEFFNA(B)=ABS(T-INT(T/B)*B-B/2):Z=1024+FNA(48)*40+FNA(78):POKEZ,81:T=T+1:GOTO

```

The listing is above one logical (Commodore C64) line in Commodore BASIC, so it must be typed with keyword abbreviations, as in the screen shot below.

A full explanation of what is going on is linked above.
> 1 votes

# Answer
# ZX Spectrum BASIC - 179 bytes

Here it is just condensed a little bit. It's 179 bytes with the ball graphics included

```
  10 LET a=10: LET b=10: LET c=1: LET d=-1: FOR e=0 TO 7: READ f: POKE USR "a"+e, f: NEXT e
  20 DATA 60, 126,243,251,255,255,126,60
  30 PRINT AT b,a;"\a"
  40 IF a<1 OR a>30 THEN LET c=-c
  50 IF b<1 OR b>20 THEN LET d=-d
  60 LET a=a+c: LET b=b+d: PRINT AT b-d, a-c;" ": GO TO 30

```
> 0 votes

---
Tags: code-golf, animation
---


title: Write the Half-Reactions

text:
# Question
Title: Write the Half-Reactions
A redox reaction is a chemical reaction in which elements transfer electrons. One element loses electrons, while another gains electrons. *Oxidation* is the process where an element loses electrons, and *reduction* is the process where an element gains electrons. Since electrons have a negative charge, the oxidation number of an atom/ion changes during redox.

Quick refresher: oxidation number is the one in the top-right corner of a chemical symbol (default 0), number of moles is the number to the left of the symbol (default 1), and the number of atoms is in the bottom right (again, default 1). The total atoms of an element in a symbol is the product of the moles and the atoms. The number of atoms of an atom/ion does not affect its charge.

A *half-reaction* shows either the oxidation or reduction portion of a redox reaction, including the electrons gained or lost.

A reduction half-reaction shows an atom or an ion *gaining* one or more electrons while its oxidation number *decreases*. Example: Na+1 \+ 1e- → Na0

An oxidation half-reaction shows an atom or an ion *losing* one or more electrons while its oxidation number *increases*. Example: Na0 → Na+1 \+ 1e-

For the purposes of this challenge, you will only need to deal with redox reactions containing exactly two elements.

Every redox reaction has one half-reaction for the oxidation and one for the reduction. Here's how to write them:

| Step | Example |
| --- | --- |
| 0. Start with a redox reaction. | Zn + Br2 → Zn2+ \+ Br- |
| 1. Break it into two partial half-reactions. | Zn0 → Zn2+
Br20 → Br- |
| 2. Balance the number of atoms on each side of the reactions, if necessary. | Zn0 → Zn2+
Br**2**0**2**Br- |
| 3. Add electrons (e-) to balance the charge on each side of the reactions. | Zn0 → Zn2+ \+ **2e-**
Br20 \+ **e-** → 2Br- |
| 4. Balance the number of electrons gained and lost by changing the coefficients (LCM of electrons from each) | Zn0 → Zn2+ \+ 2e-
**2**Br20 \+ **2**e-**4**Br- |
| 5. Determine which reaction is the reduction, and which is the oxidation. | Zn0 → Zn2+ \+ 2e- **(Oxidation)**
2Br20 \+ 2e- → 4Br- **(Reduction)** |

Your task is, given a redox reaction, output its oxidation half-reaction and its reduction half-reaction. Input and output format is flexible; For example, you could take chemical symbols as a tuple of `[name: string, moles: number = 1, atoms: number = 1, oxidation: number = 0]`, and a list of these for each side of the equation. Your output should indicate somehow which reaction is for the reduction and which is for the oxidation, e.g. by putting the oxidation first and reduction second.

## Test cases

Cr + Fe2+ → Cr3+ \+ Fe

Oxidation: 2Cr0 → 2Cr3+ \+ 6e-
Reduction: 3Fe2+ \+ 6e- → 3Fe0

Pb + Ag+ → Pb2+ \+ Ag

Oxidation: Pb0 → Pb2+ \+ 2e-
Reduction: 2Ag+ \+ 2e- → 2Ag0

Fe3+ \+ Al → Fe2+ \+ Al3+

Oxidation: Al0 → Al3+ \+ 3e-
Reduction: 3Fe3+ \+ 3e- → 3Fe2+

Zn + Br2 → Zn2+ \+ Br-

Oxidization: Zn0 → Zn2+ \+ 2e-
Reduction: 2Br20 \+ 2e- → 4Br-

# Answer
# Mathematica v13.0+ ~~310~~ 300 Bytes

Yeah, there's *almost* a built-in function for that...

```
Module[{b=Sort/@ReactionBalance[#][[1]]},k=Keys@b;v=Values@b;r=Keys@k;p=Keys@v;n=#["NetCharge"]#&/@#2/.#1&;c=n[k,r]-n[v,p];e=Superscript["e","-"];Table[If[c[[i]]>0,{"Reduction:",r[[i]](r[[i]]/.k)+c[[i]]e->p[[i]](p[[i]]/.v)},{"Oxidation:",r[[i]](r[[i]]/.k)->-c[[i]]e+p[[i]](p[[i]]/.v)}],{i,Tr[1^r]}]]&

```

**E:** -8 bytes by introducing sub-function `n`, -2 bytes by replacing `Length[r]` with `Tr[1^r]`

**Explanation**

New in v13.0, Mathematica features built-in functions to parse, balance, and otherwise analyze chemical reactions along with entities for elements. The four test reactions can be entered as simple strings:

```
test1 = "Cr + Fe^2+ -> Cr^3+ + Fe";
test2 = "Pb + Ag^+ -> Pb^2+ + Ag";
test3 = "Fe^3+ + Al -> Fe^2+ + Al^3+";
test4 = "Zn + Br2 -> Zn^2+ + Br^-";

```

Applying the function `Sort/@ReactionBalance[#][[1]]&` does most of the heavy stoichiometric lifting (which we store to `b` for "balanced reaction") and yields the following formatted output:

The remainder of my bodges are grappling with this custom datatype, while lamenting that there isn't a built in function for determining the half-reactions nor Lewis acids/bases. We store the elements & charge states for the reactants (`k=Keys@b;` and `r=Keys@k;`) and products (`v=Values@b;` and `p=Keys@v;`). We next do some kludges to determine the charge gained or lost by each element: `n=#["NetCharge"]#&/@#2/.#1&;c=n[k,r]-n[v,p];`, where we have used the `"NetCharge"` property to determine an element's ionic state (e.g., "Fe" vs "Fe^2+").

We store the nicely formatted string `e=SuperScript["e","-"];` for electrons, because we definitely aren't making par on this hole of code golf. (N.B., Mathematica does have an entity for electrons, `Entity["Particle","Electron"]`, but it doesn't play well with our later equations nor the `ChemicalReaction` data type.) Finally, we congeal all information into a horrific function to display the appropriately balanced half-reactions:

```
Table[
    If[c[[i]]>0,
        {"Reduction:",r[[i]](r[[i]]/.k)+c[[i]]e->p[[i]](p[[i]]/.v)},
        {"Oxidation:",r[[i]](r[[i]]/.k)->-c[[i]]e+p[[i]](p[[i]]/.v)}
    ],
{i,Length[r]}]

```

This outputs an array (list of lists) of the half-reactions, with the first entry being the string "Oxidation:" or "Reduction:", as shown for the four test cases:

This code could certainly be golfed down below 300 bytes (to perhaps ~250ish) with standard Mathematica tricks (e.g., ~~`Tr[1^r]` instead of `Length[r]`~~, ~~remove redundancies for `c`~~, try to remove redundant logic within the `Table[...If[...`, and so forth), but it all gets rather ugly. Similarly, we could forsake Mathematica's custom `ChemicalReaction` wrapper and operate on our own specified input and output formats, but that's not as fun (for me).

As a final note, my function works fine so long as all reagents and products are single elements, but falters against more complex reactions, e.g., `"(Cr(N2H4CO)6)4(Cr(CN)6)3+KMnO4+H2SO4 -> K2Cr2O7+MnSO4+CO2+KNO3+K2SO4+H2O"`, even though `ReactionBalance` can parse and balance it:
> 5 votes

# Answer
# Python, 293 bytes

```
def f(a,b,c,d):a[1]*=c[2];c[1]*=a[2];b[1]*=d[2];d[1]*=b[2];i,j=abs(a[3]*a[1]-c[3]*c[1]),abs(b[3]*b[1]-d[3]*d[1]);n=math.lcm(i,j);a[1],c[1],b[1],d[1]=a[1]*n//i,c[1]*n//i,b[1]*n//j,d[1]*n//j;r,o=[[a,c],[b,d]][::1-2*(a[3]<c[3])];return[[o[0]],[o[1],e:=["e",n,1,-1]]],[[r[0],e],[r[1]]]
import math

```

Attempt This Online!

I suspect this could be golfed much much further, but I can't be bothered trying to right now.

Takes 4 inputs, the two reactants and the two products, in the format described in the question. Outputs two lists in the order oxidation, reduction. Each output list is a half-equation in the form `[[<REACTANTS>],[<PRODUCTS>]]`. The link above includes some pretty print to make it easy to read and check. More readable version:

```
def f(a,b,c,d):
    # Correct number of molecules on each side of the equation
    a[1]*=c[2]
    c[1]*=a[2]
    b[1]*=d[2]
    d[1]*=b[2]

    # Find the charge difference of each half equation
    i=abs(a[3]*a[1]*a[2]-c[3]*c[1]*c[2])
    j=abs(b[3]*b[1]*b[2]-d[3]*d[1]*d[2])

    # Find the LCM of the charges
    # This gives the required number of electrons
    num_electrons = math.lcm(i, j)

    # Balance equations so both sides have equal electrons
    a[1]=a[1]*num_electrons//i
    c[1]=c[1]*num_electrons//i
    b[1]=b[1]*num_electrons//j
    d[1]=d[1]*num_electrons//j

    # Work out which side is oxidation and which is reduction
    reduction,oxidation=[[a,c],[b,d]][::1-2*(a[3]<c[3])]

    # The electron molecule/s
    electrons = ["e", num_electrons, 1, -1]

    # The two half equations
    oxidation_output = [[oxidation[0]],[oxidation[1],electrons]]
    reduction_output = [[reduction[0],electrons],[reduction[1]]]

    return oxidation_output, reduction_output

```
> 3 votes

---
Tags: code-golf, chemistry
---


# Question
Title: Find the index of the matching parentheses for each character
The challenge is simple, find the matching parentheses for every one of the parentheses in a given string input

E.g.

```
()()() -> [1, 0, 3, 2, 5, 4]

```

Always start with the ending parentheses index before the starting parentheses, which is why `()` becomes `[1,0]`, not `[0,1]`, unless the parentheses is stacked e.g. `(())`, where the position of the parentheses must match the index so `(())` is `[3, 2, 1, 0]`

## Test Cases:

```
() -> [1, 0]
()(()) -> [1, 0, 5, 4, 3, 2]
()()() -> [1, 0, 3, 2, 5, 4]
((())) -> [5, 4, 3, 2, 1, 0]
(()(())) -> [7, 2, 1, 6, 5, 4, 3, 0]

```

You may output the indexes in the form of a list, or in the form of a string representation if so, but the output indexes must be distinguishable from each other e.g. `1 0`

You are allowed to use 0-index or 1-indexed lists/arrays.

**This is so shortest bytes wins!**

# Answer
# BQN, 37 bytesSBCS

```
{⌽˘⌾(∘‿2⊸⥊)¨⌾(((1⊸≠++`)¯1⋆-@)⊸⊔)⊒˜}

```

Run online!

`(1⊸≠++`)¯1⋆-@` generates a depth map for the brackets. Coupled with Under, we can group the indices by depths, and reverse the grouping to get back the original array shape.

`⌽˘⌾(∘‿2⊸⥊)¨` reverses each pair of bracket indices, putting them in the correct place.

-1 and -4 with ovs' help.
> 7 votes

# Answer
# x86-64 machine code, 21 bytes

```
5A 58 89 0A 8D 51 57 AB FF C1 45 31 C9 AC 84 C0 7B EE 75 F1 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as an array of 32-bit integers; and the address of the input, as a null-terminated byte string, in RSI.

In assembly:

```
.global f
rp: pop rdx           # (Right parenthesis) Pop the matching left parenthesis's
                      #   corresponding output address into RDX.
    pop rax           # Pop its index into RAX.
    mov [rdx], ecx    # Put the current index at the popped address.
    .byte 0x8D        # Subsumes the next two instructions into 'lea edx, [rcx+0x57]'.
lp: push rcx        # (Left parenthesis) Push the index onto the stack.
    push rdi        # Push the corresponding output address onto the stack.
    stosd             # Store EAX at [RDI] and advance the pointer.
    inc ecx           # Increment the index.
    .byte 0x45        # REX.RB prefix byte; changes the next instruction to 'xor r9, r9'.
f:  xor ecx, ecx    # (Start here.) Set ECX to 0 (index in string).
    lodsb             # Load a character of the string into AL, advancing the pointer.
    test al, al       # Set the flags based on that character.
    jpo rp            # Jump if it has an odd number if 1 bits (for a right parenthesis).
    jnz lp            # Jump if it is nonzero (for a left parenthesis).
    ret               # Return (for the null terminator).

```
> 8 votes

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

```
a=>a.map((c,i)=>a[a[i]=a.lastIndexOf(c>'('&&-1)]=i)

```

Try it online!

Input an array of characters. Output by modify the array in-place.
> 6 votes

# Answer
# Python3, 75 bytes

```
def f(a,*s,i=-1):
 for c in a:
  i+=1;s+=i,
  if"("<c:*s,a[i],_=s;a[a[i]]=i

```

Try it online!

-2 thx to @KevinCruijessen

-6 thx to @ovs

-10 thx to @loopywalt

-6 thx to @ovs

-4 thx to @loopywalt

## Other solutions:

## Python3, 76 bytes

```
def f(a,s=[]):
 for*s[:0],c in enumerate(a):
  if"("<c:i,v,*_=a[v],a[i],*s=s

```

Try it online!
> 5 votes

# Answer
# Haskell, 112 bytes

```
g(a:x)|a>'('=1|w<-g x=1+w+g(drop w x)
a#b=succ<$>a!map(-1+)b
('(':x)!s=g x:x#(0:s)
(_:x)!(a:s)=a:x#s
_!w=w
(![])

```

Try it online!

With some comments:

```
-- Get the 1-based index of the first unmatched ')'
g :: [Char] -> Int
g(a:x)|a>'('=1|w<-g x=1+w+g(drop w x)

-- Common part of the two cases in (!); updates the indices
(#) :: [Char] -> [Int] -> [Int]
a#b=succ<$>a!map(-1+)b

-- Main function, iterates through the string
(!) :: [Char] -> [Int] -> [Int]
-- '(' are replaced by the result of g on the remaining string
('(':x)!s=g x:x#(0:s)
-- ')' are replaced by the index of the matching '(' (stored in the right argument)
(_:x)!(a:s)=a:x#s
_!w=w

h :: [Char] -> [Int]
h=(![])

```
> 5 votes

# Answer
# Haskell, 94 bytes

```
snd.([]%).zip[0..]
z%((i,c):x)|c<')',(j:k,a)<-(i:z)%x=(k,j:a)|v:w<-z=([i],[v])<>w%x
z%e=mempty

```

Try it online!
> 5 votes

# Answer
# Python, 93 bytes

```
def f(x):
 d=c=0
 for y in x:c-=y<')';x[d]=c;x[k:=x.index(c)]=d;x[d]=[c,k][k<d];c+=y>'(';d+=1

```

Attempt This Online!

Takes a list of characters and modifies it in-place.

#### How?

Simply walks the list from left to right. Tracks the bracketing depth (uses negative numbers, so we can unambiguously overwrite them with indices later). Whenever we encounter a level for the second time swap indices with first occurrence.
> 4 votes

# Answer
# 05AB1E, ~~19~~ 17 bytes

```
'(QvyiNëN‚ˆ]¯vyÂǝ

```

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
v          # Loop over the characters `y` of the (implicit) input-list:
 y'(Qi    '#  If the current character is a ")":
      N    #   Push the current loop-index
     ë     #  Else:
      N‚   #   Pair the top value on the stack with the current loop-index
        ˆ  #   Pop and add this index-pair to the global array
]          # Close both the if-statement and loop
 ¯         # Push the global array of index-pairs
  v        # Loop over each pair of indices:
   yÂ      #  Bifurcate the current pair; short for Duplicate & Reverse copy
     ǝ     #  Insert the values at the indices in the list
           #  (which will use the implicit input-list the first iteration,
           #  and modifies it further every iteration)
           # (after which the list is output implicitly as result)

```
> 3 votes

# Answer
# Pari/GP, 61 bytes

-1 byte thanks to @DialFrost.

```
s->for(i=j=1,#a=s,if(")">s[i],s[j]=i;j++,a[a[i]=s[j--]]=i));a

```

Try it online!
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~144~~ 136 bytes

```
	I =INPUT
	M =BAL | ''
N	I POS(X) LEN(1) . B @X	:F(END)
	B ")"	:F(L)
	I @O '(' M B POS(X) 	:(O)
L	I POS(X) M @O ')'
O	OUTPUT =O	:(N)
END

```

Try it online!

```
	I =INPUT			;* Read input
	M =BAL | ''			;* Alias: M is BAL (the shortest, non-null balanced string) or the empty string
N	I POS(X) LEN(1) . B @X	:F(END)	;* extract the next character of I as B, and store the position after B as X
	B ")"	:F(L)			;* If B matches ")", goto next line, else goto L
	I				;* In I, match:
	  @O				;* the position before the match as O
	     '(' M B			;* "(", a balanced string (or nothing), and ")"
		     POS(X) 	:(O)	;* ending at position X, then goto O
L	I POS(X) M @O ')'		;* In I, match, starting at position X, a balanced string, storing position as O, followed by ")"
O	OUTPUT =O	:(N)		;* Output O and goto N
END

```
> 2 votes

# Answer
# Perl 5, 82 bytes

```
sub f{($_,$i)=(@_,0);/\((?R)*\)/?(reverse($i..$i-1+($l=length$&)),f($',$i+$l)):()}

```

Try it online!
> 2 votes

# Answer
# APL+WIN, 42 bytes

Prompts for input string. Index origin = 1

```
(,⌽((.5×⍴n),2)⍴n)[⍋n←⍋+\(~n)-¯1↓0,n←')'=⎕]

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# x86-16 machine code, 21 bytes

```
00000000: 33db ac3c 2974 0353 eb07 5888 0193 8801  3..<)t.S..X.....
00000010: 9343 e2ee c3                             .C...

```

Listing:

```
33 DB       XOR  BX, BX             ; start index counter at 0
        P_LOOP:
AC          LODSB                   ; AL = next char in input string
3C 29       CMP  AL, ')'            ; is it an end paren?
74 03       JZ   END_PAREN          ; if so, jump to handle
53          PUSH BX                 ; else, push index of left paren to stack
EB 07       JMP  NEXT_PAREN         ; continue loop
        END_PAREN:
58          POP  AX                 ; AL = index of last start paren
88 01       MOV  [DI+BX], AL        ; write to output at current index of input string
93          XCHG AX, BX             ; AL = current index of input string
88 01       MOV  [DI+BX], AL        ; write to output at index of last start paren
93          XCHG AX, BX             ; restore index counter to BX
        NEXT_PAREN:
43          INC  BX                 ; increment counter
E2 EE       LOOP P_LOOP             ; continue string loop
C3          RET

```

Custom calling convention - input string at `[SI]`, length in `CX`, output to buffer at `[DI]`.

Tests with DOS DEBUG:
> 2 votes

# Answer
# Retina 0.8.2, 67 bytes

```
\((?=((\()|(?<-2>.))*(?<=(.+)))|(?<=(.*).((\))|(?<-6>.))*).
$.3$.4

```

Try it online! Link includes test cases. Assumes input is a balanced string of `()`s. Explanation: The first alternation matches a `(`, skips over any balanced `()`s, then captures the resulting index, while the second alternation matches in reverse, skipping back over any balanced `()`s and an implied `(` before capturing the resulting index, then matching an implied `)`. Fortunately `$.` outputs an empty string if the group was not captured at all, so we can just output the length of whichever capture was successful followed by a separator.
> 2 votes

# Answer
# Curry (PAKCS), 55 bytes

```
g .zip[0..]
g[]=[]
g((i,'('):x++(j,')'):y)=j:g x++i:g y

```

Try it online!
> 2 votes

# Answer
# Python3, 124 bytes:

```
import re
def f(s):
 while'('in s:
  s=re.sub('\(\d*\)',lambda x:f'{(S:=x.span())[1]-1}{x.group()[1:-1]}{S[0]}',s)
 return s

```

Try it online!
> 1 votes

# Answer
# Charcoal, 34 bytes

```
≔⟦⟧ηＦθ¿⁼(ι«⊞υＬη⊞η⁰»«§≔η⌈υＬη⊞η⊟υ»Ｉη

```

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

```
≔⟦⟧η

```

Start building up the output list. (I need a second list as I want to use the predefined empty list as a stack.)

```
Ｆθ

```

Loop over the input characters.

```
¿⁼(ι«

```

If this is a `(`, then...

```
⊞υＬη

```

... save the current index to the stack, and...

```
⊞η⁰

```

... push a dummy value to the output list.

```
»«

```

Otherwise, ...

```
§≔η⌈υＬη

```

... replace the latest dummy value with the current index, and...

```
⊞η⊟υ

```

... push its index to the output list, removing it from the stack.

```
»Ｉη

```

Output the final list of indices.
> 1 votes

# Answer
# BQN, 24 bytes

```
(⊢⊔⁼⊢(⊔⊒˜¨×⋈¬⊸×)·+`¬-»)⊐

```

Try it here.

How it works (with example):

1. Calculate the parenthesis depths from a mask of the string.
2. Split the depths into one vector where the indices of open parens are replaced with 0, and one vector where the indices of close parens are 0, such that if you add them together you get back the original depths.
3. Match depths of the open parens in the close paren half of the depth vector, and close parens in the open paren half, without repeats.
4. Use the original mask to combine the two lists of indices back together.

Detailed breakdown:

```
(⊢⊔⁼⊢(⊔⊒˜¨×⋈¬⊸×)·+`¬-»)⊐  #
                       ⊐  # Classify the string to get a mask
(               ·+`¬-»)   # Generate depths of parentheses
    ⊢(    ×⋈¬⊸×)          # Pair mask and it's negation, multiplied by the depths
      ⊔                   # Group depths according to the mask
       ⊒˜                 # Take the progressive index-of
         ¨                #   between corresponding groups and depths
  ⊔⁼                      # Inverse partition to combine results
 ⊢                        #   according to the original mask

```
> 0 votes

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


title: Program your favorite phrase

text:
# Question
Title: Program your favorite phrase
Pick a quote or phrase that is exactly 5 words long, such as `Programming puzzles and code golf!`.

Write a program that, when appended to itself *n* times, outputs the first *n + 1* words of your phrase in order.

For example, if your program code was `MYPROG` and your phrase was `Programming puzzles and code golf!`, running...

* `MYPROG` should output `Programming`
* `MYPROGMYPROG` should output `Programming puzzles`
* `MYPROGMYPROGMYPROG` should output `Programming puzzles and`
* `MYPROGMYPROGMYPROGMYPROG` should output `Programming puzzles and code`
* `MYPROGMYPROGMYPROGMYPROGMYPROG` should output `Programming puzzles and code golf!`

Appending more than 4 times is undefined, your program may do anything.

# Rules

* Your phrase must be grammatical meaningful English. Ideally it should be properly capitalized and punctuated.
* Your phrase may be any length but its entropy, as calculated by http://www.shannonentropy.netmark.pl/, **may not be less than 3.5**.
(Paste in your phrase, hit *Calculate* and look for the last *H(X)*.)
* Your phrase can only contain printable ASCII characters (hex 20 to 7E). Your code can only contain printable ASCII and tabs and newlines.
* Your phrase must contain exactly 5 **unique** words and 4 spaces. All non-spaces count as parts of words. Spaces are the word boundaries. They may not be leading or trailing; there should be one after all but the last word.
* The output should contain one space between words as well. The output at each appending step may contain trailing spaces but not leading spaces.
* Output to stdout. There is no input.

# Scoring

Your score is the length in bytes of your initial un-appended program. (e.g. `MYPROG` scores 6)

As this is code-golf, the lowest score wins.

# Answer
# CJam - 24

```
"TheguywasnotI"Lm3<]S*:L

```

Try it at http://cjam.aditsu.net/

**Explanation:**

`Lm` removes the letters contained in L (initially "") from "TheguywasnotI"
`3<` takes the first 3 letters
`]` collects the contents of the stack in an array
`S*` joins the array using space as a separator
`:L` assigns the resulting string to L (also leaving it on the stack)

### Old version (28 bytes):

```
"He is but a dog."S/W):W=]S*

```

**Explanation:**

`S/` splits by space
`W):W` increments W (initially W = -1)
`=` gets the W'th word
`]` collects the contents of the stack in an array
`S*` joins the array using space as a separator
> 7 votes

# Answer
# Piet (honorary answer)

Snakes its way downwards, running out the right through blue and re-entering through green. Prints out "Fruit flies like a banana."

I used PietCreator to make this, but you can try it out here. Remaking Piet programs is a pain, so I started out at 35x35 and continued that way, meaning that I used a lot more codels than I needed.

## Actual size versions
> 31 votes

# Answer
## Python 66

```
i='i'in dir()and i+1;print("Tfpcfhaialetgny"[i::5],end=" ."[i>3]);

```

Entropy: 3.61635

Ouput:

```
The fat pig can fly.

```

Thanks @JasonS and @grc for the tips on shortening the variable detection part.

**Update:** Do see JasonS' answer for a wicked wraparound trick which pushed this down to 55 bytes. :)
> 12 votes

# Answer
# \>\<\> (42)

Fish are truly the greatest pet. Some people keep bugs as pets due to an incomprehensible lack of logic. This program does its best to reason with such people.

```
!v'?od gub yna nac tahW;'00p!
<<|ov!
voo <

```

Note there this is no trailing newline in the program. The full output is reversed in the first line; the complete phrase is "What can any bug do?" (entropy 3.58418).

Full explanation:

This is one of the more fun \>\<\> programs I've written, since this is the first that uses reflection. The first line is where the meat of the program is.

`!v` is a no-op, as `!` causes the next instruction to be skipped.

`'?od gub yna nac tahW;'` stores the full phrase on the stack (it's backwards because each letter is pushed onto the stack in the order written, so it must be reversed to be popped off nicely).

`00p` is where the real magic starts happening. Note that it didn't just store the phrase, it also stored a `;`. `00p` inserts the top character onto the stack into the program at position (0, 0), so now the first character of the program is a `;`.

The ending `!` skips that semicolon, and moves the cursor onto `v`, which directs the program flow downwards.

From here on out, it's all just printing routines. Since there's no trailing newline, successive appendings of the program simply add the last two lines, in effect, since the first line will be to the right of `voo <`, and thus will never be executed.

At the end, the cursor is directed out the bottom left of the program, and wraps back around to the top left, where the `;` was inserted earlier, ending the program.
> 12 votes

# Answer
# Python 3, 55 (bonus 67)

```
# 55 bytes, H(X)=3.72, Based on bitpwner's 66. "Mix dog and cat fur."
i=0;print("Mdacfionauxgdtr"[i::5],end=" ."[i>3]);i+=1;i

# 67 bytes, H(X)=4.28. "Thanks for supporting Python development."
q=b"qx!%%0077C";a,b,*q=q;print((str(credits)*2)[49:][a:b],end='');q

# 60 bytes, H(X) = 3.51. "Fix the bed old pal"
s="Fixthebedoldpal";a,b,c,*s=s;print(a+b+c,end='. '[s>[]]);s

```

You mean it wraps around?

**OK, some explanation on #2 (spoilers)**

* `credits` is a python builtin that contains text I'd like to use. It's of a special type with a formatted `repr` so that you can just type it in the interactive interpreter and see nice output, so I have to `str()` it. I spent quite a bit of time looking at builtins for this, and "Thanks for supporting Python development" as a phrase was too good to pass up.
* Since there's a lot of text and I only want my 5 words, I want to store the start and end positions of each substring. That's in the bytes at the beginning. `bytes` objects in python3 act like arrays of integers when you use sequence operations on them.
* But the code can contain only printable characters, so I had to find an offset (49) that would make all my position values printable as characters.
* "Thanks" is near the beginning of the string while the other words are nearer the end, which means my position values were too far apart to all be in the printable range. Mulitplying the string by 2 makes another copy of "Thanks" that is nearer to the other words.
* Taking the `[49:]` slice of the string is one fewer source byte than adding 49 to both a and b.
* The construct used in all three answers is `x=<value>;dostuff and increment;x`. The trailing `x` doesn't do anything at all, but when combined with the next copy of the code it turns into `xx=<value>` which prevents the `x` counter from being overwritten.
* `a,b,*q=q` is perfectly normal Python 3 sequence unpacking.
> 9 votes

# Answer
# Python 2 (37)

After Sarah became president of her local Mensa chapter, she became a focus of romantic attention from men looking for an intelligent partner. On every date, Sarah would try to make a personal connection, but the men would just probe her on abstruse philosophical questions. Frustrated that nobody cared about her emotional side, she exclaimed ...

```
i=4;print"mniIMeosQy!t"[i::5],;i-=1;i

```

Output:

```
My
My IQ
My IQ is
My IQ is not
My IQ is not me!

```

The entropy is `H(x)=3.5` exactly.

Credit to Jason S., whose answer I basically used wholesale. The `ii` wraparound trick is wonderful.
> 9 votes

# Answer
# C - 65

Comment abuse :)

```
char*z="Ah, \0the \0good \0ol' \0times!";
for(printf(z);*z++;);//

```

Because of this, the new lines are important and the code should be appended as follows:

```
char *z="Ah, \0the \0good \0ol' \0times!";
for(printf(z);*z++;);//char *z="Ah, \0the \0good \0ol' \0times!";
for(printf(z);*z++;);//...

```
> 9 votes

# Answer
# BBC Basic, 40

Includes one newline. Would be 30 if the keywords could be considered as tokenised instead of ASCII.

I caught my girlfriend sleeping with the milkman, so I dumped her and I am sleeping with her sister out of revenge. `As my ex do I!` (five two-letter "words" with unique characters) wasn't enough entropy, so I added the tongue-out smiley at the end to make the entropy exactly 3.5. After all, in reality I have a fairly normal life, not some weird soap opera plot.

```
  READa$:PRINTa$;" ";
  DATAAs,my,ex,do,I:-P

```

Repeating the program 5 times we get

```
  READa$:PRINTa$;" ";
  DATAAs,my,ex,do,I:-P
  READa$:PRINTa$;" ";
  DATAAs,my,ex,do,I:-P
  READa$:PRINTa$;" ";
  DATAAs,my,ex,do,I:-P
  READa$:PRINTa$;" ";
  DATAAs,my,ex,do,I:-P
  READa$:PRINTa$;" ";
  DATAAs,my,ex,do,I:-P

```

Only the 5 `READ` statements are executed, and the first 5 items of data are read from the first `DATA` statement. the rest of the data is redundant. Output:

```
  (once)
  As
  (5 times)
  As my ex do I:-P

```
> 5 votes

# Answer
# J - 42 char

I could go for a shorter phrase, but why? It wouldn't be my favourite.

```
(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '

```

This works because of J's monad/dyad duality: every verb can be invoked as a monad—with one argument to its right—or as a dyad—with an argument on the left and another on the right.

Consider the following session with the J REPL:

```
   'You multiplied 6 by 9. '
You multiplied 6 by 9.
   'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. '
You multiplied 6 by 9. You multiplied 6 by 9.
   ;: 'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. '   NB. break into words
+---+----------+-+--+--+---+----------+-+--+--+
|You|multiplied|6|by|9.|You|multiplied|6|by|9.|
+---+----------+-+--+--+---+----------+-+--+--+
   (#\) ;: 'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. '             NB. count off
1 2 3 4 5 6 7 8 9 10
   (6 | #\) ;: 'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. '         NB. mod 6
1 2 3 4 5 0 1 2 3 4
   (1 = 6 | #\) ;: 'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. '
1 0 0 0 0 0 1 0 0 0
   (#~ 1 = 6 | #\) ;: 'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. '  NB. select
+---+----------+
|You|multiplied|
+---+----------+
   (#~ 1 = 6 | #\)&.;: 'You multiplied 6 by 9. ' , 'You multiplied 6 by 9. ' NB. undo ;:
You multiplied

```

There, `,` is treated as a dyad, because it is between two arguments, and `(#~1=6|#\)&.;:` is a monad because it has no left argument. So if we had a verb that could act like `,` when dyadic and `(#~1=6|#\)&.;:` when monadic, we'd be set.

As you may have already guessed, such a conjunction exists and it looks like `:`. Monadic `f :g` is equivalent to `f`, and it is equivalent to `g` when dyadic. This solves the problem.

Examples, which you can try for yourself at tryj.tk:

```
   (#~1=6|#\)&.;: :,'You multiplied 6 by 9. '
You
   (#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '
You multiplied
   (#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '
You multiplied 6
   (#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '
You multiplied 6 by
   (#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '(#~1=6|#\)&.;: :,'You multiplied 6 by 9. '
You multiplied 6 by 9.

```

And yes, the nature of the inverse of `;:` makes it so that there are no trailing spaces.

Using `It is by a rope.` as the phrase gives 35 char: `(#~1=6|#\)&.;: :,'It is by a rope.'`. We don't need the trailing space like we do for my sentence, for arcane, `;:`-based reasons.
> 4 votes

# Answer
# CJam, 24 bytes

```
"LwOtmiaKoezs"W):W>5%]S*

```

If run five times, it prints **Liz was OK to me**. Punctuation not included, sorry.

### How it works

```
"LwOtmiaKoezs"  " Push that string. ";
W):W            " Push W (initially -1), increment and save the result in W. ";
>               " Shift that many characters from the string. ";
5%              " Select every fifth character, starting with the first. ";
]S*             " Wrap the stack in an array and join its strings using spaces. ";

```
> 4 votes

# Answer
# Pyth, 32

```
p?kqZ4d@P"It is by a rope."dZ~Z1

```

Phrase: "It is by a rope."

Entropy: 3.5

How it works:

`p` means print with specified separator.

The first argument, `?kqZ4d`, gives the separator. `?kqZ4d` means `k if Z==4 else d`. `k` is `''`, while `d` is `' '`.

The second argument, the value to be printed, is generated by splitting (`P`) on space (`d`), and the indexing into that list (`@`) at `Z`.

Finally, `Z`, which is automatically initialized to 0, is incremented by 1 (`~Z1`).
> 3 votes

# Answer
# Golfscript, 53

This one was fun.

```
{'1'-print}:puts;.'You; are; not; a; duck.'';'/\,=\1+

```

Phrase: "You are not a duck." (which is completely true; entropy 3.5110854081804286)

Explanation:

The stack will start as `''` on the first "run" (since no STDIN is provided). `'1'`s are appended to this to signify how many times the code has been pasted in.

```
{'1'-print}:puts;             # Hacky stuff (see below)
.                             # Stack: '' ''
'You; are; not; a; duck.'';'/ # Initialize the array of words
\,                            # Get the length of the string of '1's (0)
                              # Stack: '' [words] 0
=                             # Stack: '' 'You'
\1+                           # Stack: 'You' '1'

```

Now what happens on the second run:

```
{'1'-print}:puts;             # Hacky stuff (see below)
.                             # Stack: 'You' '1' '1'
'You; are; not; a; duck.'';'/ # Initialize the array of words
\,                            # Get the length of the string of '1's (1)
                              # Stack: 'You' '1' [words] 1
=                             # Stack: 'You' '1' ' are'
\1+                           # Stack: 'You' ' are' '11'

```

And so on.

"But," you're thinking, "how do you get the 1s to not output?" Ah, that's the fun hacky part. Golfscript implements `puts` (which is called when the program ends) like this:

```
{print n print}:puts;

```

I simply changed it to

```
{'1'-print}:puts;

```

So that the `1`s are suppressed from the final output.
> 3 votes

# Answer
## Ruby, 50

```
puts'The fat pig can fly.'[0..File.size($0)/12-1]#

```

This uses its own length to determine how many of the words to print. Its repeats are otherwise ignored by ending in the comment character, `#`. Phrase borrowed from bitpwner: it's very convenient having a short phrase with the same number of letters in each word.

Since each word+ending is 4 characters, the formula would be, e.g. for 56-length program: `(File.size($0)/56)*4 - 1`, but I can divide ahead of time, `56/4 = 14`, so `File.size($0)/14 - 1`, saving a few characters. `50` isn't a multiple of `4`, but `12` is close enough for the range needed.
> 2 votes

# Answer
# Chip, 165+3 = 168 bytes

+3 for flag `-w`

```
| ,z `Z`Z  `Z
| |ZZZ>Z>ZZZ>ZZZZ
>((((((((((((((((
|)-)))-)-)))-))))g
|)d)xx-x-)xx-))x)e
||b+))-x-x))-x)xc
|`v))xa(-x(x-((^d
|*`.))d| b | b
|Z~<b( |~Zf|
>~T| | |   |

```

"I won a red suit" (3.5) (I actually haven't won any such thing) (...yet)

Note the trailing newline, so the concatenated copy appears below the existing code.

Try it online! (the original)
Try it online! (the original, plus all four copies)

This is a bit of a tangled mess. It turned out that the trickiest bit was the termination condition. (My first iteration printed the word(s), followed by an endless stream of null bytes...).

### How it works

First the phrase:
12 unique characters + 4 spaces = exactly 3.5 entropies.

And the code:
Each copy prints the first word, then tells the copy below to print the next word. If there is only one instance, there is no second copy, so nothing except the first word is printed.

If there are two copies, both will print the first word simultaneously (the bytes are OR'd together so it's fine), then only the second copy will print the second word.

If all five copies are present, all will print the first word, etc, etc, and the fifth copy will print the last word by itself.

The termination circuit will terminate the program as soon as all copies are not actively printing.
> 2 votes

# Answer
# Ruby, 63

```
+1;puts"See Dick and Jane run!"[/(.*?( |!)){#$.}/]if($.+=1)==$.

```
> 1 votes

# Answer
## Perl, 37

```
print qw(My IQ is not me!)[$i++].' ';

```

Similar to what comperendinous had, but taking advantage of perl's qw to save a few more characters.
> 1 votes

# Answer
# Rebmu message length + 27

Were we to go with "My IQ is not me!" that would be 43. But I support this message:

```
uV?'s[S[{The}{rebellion}{against}{software}{complexity.}]]proTKsPROsp

```

Equivalent Rebol/Red:

```
unless value? 's [
    s: [{The}{rebellion}{against}{software}{complexity.}]
]

print/only take s
print/only space

```

Rebol has 3 basic conditionals: IF, EITHER, and UNLESS. UNLESS is equivalent to IF NOT but can be more clear: *"Always do the following UNLESS this condition happens to be true."*

In this case the condition is that we test is to see if the symbol S has been given a value in the current context. We have to use a quote on it, because attempting to use an unquoted S in a conditional expression would evaluate it and possibly raise an error. *(`value?` doesn't quote its parameter by default because you might want to have which symbol you are checking be in a variable, e.g. `sym: 's` then `if value? sym [...]` would actually check if S was defined, not SYM)*

Only the first paste of the program will assign the series of strings to S. Successive pastes will take a string from the head of the series and pass it to PRINT/ONLY which will print its argument without adding a line feed.

*(Note: PRINT/ONLY is a suggested replacement way of saying PRIN, which is being considered in Rebol 3 and Red; a print replacement is now being tested in Rebmu.)*
> 1 votes

# Answer
# AHK, 44 bytes

```
i++
Send % SubStr("He is an OK ex",i*3-2,3)

```

Note the newline at the end. The only clever thing here is that the string is all 3-letter words so we don't have to split anything. Instead, we just pull a substring based on `i`. Output is to the active screen as if it was typed on the keyboard.
> 1 votes

# Answer
# Pxem, 0 bytes: content + 170 bytes: filename.

H(X) = 3.57662

* Filename: `.o.c.c.zXXOnepigcannotfly.a.o.o.o`
* Content is empty.

Try it online!

## How it works

* First `.o` pops to output, if any
* `.c.c.zXXOnepigcannotfly.a` is done if and only if stack is empty.
* `.o.o.o` to pop top three to output.
* A space at last to push a space.
> 1 votes

# Answer
# Batch 160 bytes

H(X) = 3.61437

```
@Set s=Get out by Six pm.
@Set/ai+=0&Set "n=0"&Set "_=%s: ="&Cmd/Von/C "if !n!==!i! Echo(!_!"&Set/An+=1&Cmd/Von/C"if !n!!i!==44 Echo(pm."&Set "_=%"
@Set/ai+=1

```
* Split string on whitespace , match split instance count `n` with execution instance count `i` to output word.
* As a result of substring parsing, the 5th instance will never match during substring modification, so a 0 index is used and the final 'word' of the phrase is output on the 5 instance by matching `i = n = 4`.

Note: requires a fresh cmd instance to execute between runs when appending the code, as otherwise variable values will persist and affect the output - Alternately, execute the following command in cmd.exe to reset the variables: `set /a i=n=0`
> 1 votes

# Answer
# Japt `-S`, 17 bytes

Includes unprintables between the backticks.

```
`âK0dÊŠ…`ò3 ¯°T)

```

Test it, repeated 5 times

```
`...`ò3 ¯°T)
`...`            :Compressed string "thecatandhishat"
     ò3          :Partitions of length 3
        ¯        :Slice from index 0 to
         °T      :  Prefix increment T, initially 0
           )     :End slice
                 :Implicit output joined with spaces

```
> 1 votes

# Answer
## Perl, 43 ~~56~~

```
print substr'Mine was not Red 5!',4*$i++,4;

```

I accept that I can't win this one. My original attempt explains why:

```
@a=('This',' code',' is',' too',' long.');print$a[$i++];

```
> 0 votes

# Answer
## Javascript (53)

I took the text from aditsu as I'm not doing anything fancy with the text, so that the words chosen are somewhat irrelevant for the solution (except for byte count).

```
var i=i|0;alert("He 0is 0but 0a 0dog".split(0)[i++]);

```

Does `alert` count in this case? *Edit:* Reading the rules it probably doesn't as I'm not joining the strings with spaces. I'll add spaces to make it fair.

Also note that the expensive `var` is actually relevant in this case.
> 0 votes

# Answer
## Lua, 77

A pretty simple solution:

```
i=(i or 0)+1;io.write((i==1 and""or" ")..("Thebigfoxwasup."):sub(3*i-2,3*i))

```

(H(X)=4.23)
> 0 votes

# Answer
## Javascript, 138

```
g=this;clearTimeout(g.t);g.i|=0;i++;g.t=setTimeout(
    function(){console.log(["I'll","sleep","when","I'm","dead."].slice(0,i).join(' '))},0);

```

(the additional newline is added for readability only)

Prints `I'll sleep when I'm dead`. Uses a timer to make sure the output is only printed once
> 0 votes

# Answer
# Pure Bash, 51 bytes

```
a=(All you need is Love!)
printf "${i:+ }${a[i++]}"

```

H(X) = 3.59447

This could be golfed down a bit more by poaching one of the shorter phrases, but I'm happy to stick with Descartes' Lennon's most famous quote. (Sorry @Descartes, but all words need to be unique).

### Output:

```
$ ./phrase.sh
All$ cat phrase.sh phrase.sh phrase.sh > phrase3.sh
$ chmod +x phrase3.sh
$ ./phrase3.sh
All you need$
$ cat phrase.sh phrase.sh phrase.sh phrase.sh phrase.sh > phrase.sh
$ chmod +x phrase5.sh
$ ./phrase5.sh
All you need is Love!$

```

Takes care to insert spaces between words, but no leading or trailing spaces.

Relies on the fact that in bash, undefined variables, when expanded as strings have the value "", but when expanded arithmetically have the value 0.
> 0 votes

# Answer
# PHP 89 78 char

Its a little verbose, and most definitely won't win, but it was fun anyway. Here's what I came up with

Phrase:

`code golf is pretty fun`

Entropy = 3.82791

Code:

```
<?
$i=(isset($i)?$i+1:0);
$w=["code","golf","is","really","fun"];
echo $w[$i].";

```

Golfed:

```
<?$i=(isset($i)?$i+1:0);$w=["code","golf","is","really","fun"];echo $w[$i].

```
> 0 votes

# Answer
# Python3 - 122 bytes

## Open the pod bay doors \[HAL\]

I guess I'll earn some nerd cred with this one. If only the question would allow one more word...

What my program does is takes the filename (p.py is the base) and checks how many times the base name is iterated. It then takes slices from a string `n` times. `n` being the number of `p`s in the filename.

```
import sys,re
for i in range(len(re.findall(re.compile('p'),sys.argv[0]))):print('Otpbdphoaoeedyon   r    s'[i::5],end='')

```

---

```
~ $ python p.py
Open

~ $ python pp.py
Open the

~ $ python ppp.py
Open the pod

~ $ python pppp.py
Open the pod bay

~ $ python ppppp.py
Open the pod bay doors

```

The benefit of the regex is that the program can be called whatever you like and it will still work (providing you change the basename in the code): my original program was called golfed.py.
> 0 votes

# Answer
# 05AB1E, 21 bytes (Noncompeting)

```
“€Œ‰‹€‡Øš‹É.“ª#¾è¼?ð?

```

Try it online!

Uses:

```
This works for literally anything.
H(x) = 4.02086

```

### Explanation

```
“€Œ‰‹€‡Øš‹É.“ª#¾è¼?ð?
“€Œ‰‹€‡Øš‹É.“ª        # Pushes "This works for literally anything."
              #       # Split on spaces
               ¾è     # get element at index of counter_variable (default 0)
                 ¼    # Increment the counter_variable
                  ?   # Print the selected element
                   ð? # Prints a space

```
> 0 votes

# Answer
# Stax, 24

```
`nH+~mJp@Z_Iy.5!`j|d:/dJ

```

Run and debug it

Quote: Some animals are more equal.
> 0 votes

# Answer
# SmileBASIC, 54 bytes

```
DATA"Does"," anybody"," have"," a"," key?
READ W$?W$;

```

I would've prefered "The sand can be eaten." but that fails the entropy test somehow. Of course I could've picked a shorter phrase but that's boring.

The `READ` keyword reads a value from `DATA` and stores it in a variable. Using `READ` again will get the next item, and so on.
> 0 votes

# Answer
# Pyth, 27 bytes

```
p+@c"Andso,themanis."3Zd=hZ

```

Once, twice, thrice, four times, and five times. Appending after this begins to repeat the phrase.
> 0 votes

# Answer
# Vyxal , 18 bytes

```
`λλ⇩İλ¬×ḟɾ∷`3ẇ¥i&›

```

Try it Online!

Try it Online!Try it Online!

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

```
`λλ⇩İλ¬×ḟɾ∷`       # `thecogandFunJoe`
            3ẇ     # Split into chunks of 3
              ¥i   # Index the register into this
                &› # Increment the register
                   # (ṡ flag) print stack  joined on spaces

```
> 0 votes

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