title: Is this hexagon symmetric?

text:
# Question
Title: Is this hexagon symmetric?
**TLDR: This is the hexagonal version of Is this square symmetrical?**

Given a hexagonal grid, decide if it is symmetric.

The shape of the grid is a regular hexagon. Each cell in the grid has two possible states.

Let's only consider reflections and rotations. Here are all the possible symmetries:

* Reflection symmetry, where the axis is the perpendicular bisector of an edge (there are 3 possible such axes):

Smaller examples in ASCII art:

```
   . . . .         . . * .         * . * .
  . * . * .       * . * * .       . . . . *
 * . . . . *     * * . . . .     . * . . . .
* * . . . * *   * * * * . * .   * . . . . . *
 . . * * . .     . * * . * *     . . . . * .
  . . * . .       . * * . .       * . . . .
   * . . *         * * * .         . * . *

```
* Reflection symmetry, where the axis is a diagonal (there are 3 possible such axes):

Smaller examples in ASCII art:

```
   * . * *         . . * *         * * . *
  * * . * .       . * . * .       . * . . .
 . . . . . .     * . . . . .     * . . . . *
* . . . . . .   * * . . . * .   * * . * . * *
 . . . . . .     . . . . * *     . . . . . .
  * * . * .       . * * . .       . . . * *
   * . * *         . * . .         * . . *

```
* 60° rotational symmetry:

A smaller example in ASCII art:

```
   * * . *
  . * . * *
 * . . . . .
* * . * . * *
 . . . . . *
  * * . * .
   * . * *

```
* 120° rotational symmetry:

A smaller example in ASCII art:

```
   * . . .
  . . * . *
 * . . . . .
. . . . . . *
 . * . . * .
  . . . . .
   * . * .

```
* 180° rotational symmetry:

A smaller example in ASCII art:

```
   . . . .
  * . * . .
 . . * * . .
* . . . . . *
 . . * * . .
  . . * . *
   . . . .

```

### Input

A hexagonal grid, in any reasonable format. You may choose the two distinct values for the two states in the input. When taking input as an 2d array, you may use one of the two states or a third value for padding.

Some example inputs (Taken from Bubbler's HexaGoL challenge):

* ASCII art:

```
  . . .
 * . . *
* . * * *
 * * * .
  * . .

```
* List of rows:

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

```
* 2d array, skewed to the right (with zero padding):

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

```
* 2d array, skewed to the left (with `2`'s as padding):

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

```
* Flatten array, with an integer that indicates the size:

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

```

### Output

A value representing whether the hexagonal grid is symmetric. You can choose to

* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

This is , so the shortest code in bytes wins.

### Testcases

Here I use 2d arrays skewed to the left with zero padding.

**Truthy:**

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

```

**Falsy:**

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

```

# Answer
> 8 votes
# Python NumPy, 92 bytes (@Neil)

```
def f(l,*o):
 for a in[l>0]*6:l.T[::-1][a[::-1]]=l[a];o+=str(l),str(l.T)
 return 7>len({*o})
```

Attempt This Online!

## Pure (no NumPy) Python version, 111 bytes

```
lambda l:7>len({l:=((x:=~len(l)//2)and(*(k[(x:=x+1):]+k[:x]for k in i*l[::-1]),)or(*zip(*l),))for i in[0,1]*6})
```

Attempt This Online!

#### Old Python, 128 bytes

```
def f(*l):
 for n in[len(*l)//2]*6:l+=(k:=(*(j[i:]+j[:i]for i,j in enumerate(l[-1][::-1],-n)),)),(*zip(*k),)
 return 7>len({*l})
```

Attempt This Online!

#### Old Python NumPy, 93 bytes

```
def f(l,*o):
 for a in[l>0]*6:l.T[::-1][a[::-1]]=l[a];o+=str(l),str(l.T)
 return 12>len({*o})
```

Attempt This Online!

#### Old Python NumPy, 97 bytes

```
def f(l):
 o={0}
 for a in[l>0]*6:l[::-1][a[::-1]]=l[a];o|={str(l),str(l:=l.T)}
 return 13>len(o)
```

Attempt This Online!

#### Old Python NumPy, 111 bytes

```
def f(l):a=l>0;b=l*0;l=l[a];b[a]=range(len(l));return 12>len({str(l:=l[s])for s in[b.T[a],b[::-1][a[::-1]]]*6})
```

Attempt This Online!

Takes right-skewed zero-padded input with values 1 and 2.

Generates the 12 possible symmetries from two relatively easy to implement reflections, viz. updown and matrix transpose. As their axes subtend an angle of 30° their composition is a 60° rotation. We can therefore apply them alternately and then count the number of distinct patterns.

# Answer
> 6 votes
# Charcoal, ~~61~~ 58 bytes

```
ＷＳ⊞υ⪪ι¹≔⟦⟧θＦ⁶Ｆ²«⊞θ⭆υ⪫λωＵＭυ⎇κ⮌λＥ✂υ⁺⊘Ｌυμ±⁻⊘⊕×³Ｌυμ±¹⊟ν»⊙θ⊖№θι

```

Try it online! Link is to verbose version of code. Takes input as newline-terminated ASCII art but without any spaces and outputs a Charcoal boolean, i.e. `-` for symmetric, nothing if not. Explanation:

```
ＷＳ⊞υ⪪ι¹

```

Input the list of rows.

```
≔⟦⟧θ

```

Start building up the list of rows and reflection.

```
Ｆ⁶Ｆ²«

```

Loop through six rotations and two reflections. (Probably overkill, but I can't make it any shorter by performing less work.)

```
⊞θ⭆υ⪫λω

```

Save the current hexagon to the list.

```
ＵＭυ⎇κ

```

Modify the hexagon in-place, alternating between either...

```
⮌λ

```

... reflecting it along the T-B bisector, or...

```
Ｅ✂υ⁺⊘Ｌυμ±⁻⊘⊕×³Ｌυμ±¹⊟ν

```

... reflecting it along the BL-TR diagonal. Since the combination of these two reflections is a 60° rotation, this eventually covers all possible symmetries.

```
»⊙θ⊖№θι

```

Check the list for duplicates.

The BL-TR diagonal reflection is obtained by taking slices of the hexagon, starting from just the top half, extending each row until the whole hexagon is covered, then shrinking until the last row takes the bottom half of the hexagon. The last character of each row is removed and these characters form the new row of the hexagon.

Previous 61-byte canvas based version:

```
ＷＳ⊞υι≔⟦⟧θＦ³«ＦＬυ«Ｍ✳⁻ι⊗⊕‹⊗κＬυＰ✳⊖ι§υκ»Ｆ²«⊞θ⪫ＫＡω‖»⎚»Ｆ✂θ⊞θ⮌ι⊙θ⊖№θι

```

Try it online! Link is to verbose version of code. Takes input as newline-terminated ASCII art but without any spaces and outputs a Charcoal boolean, i.e. `-` for symmetric, nothing if not. Explanation:

```
ＷＳ⊞υι

```

Input the ASCII art.

```
≔⟦⟧θ

```

Start building up the list of rotations and reflections.

```
Ｆ³«

```

Loop through the rotations of -60°, 0° and 60°.

```
ＦＬυ«

```

Loop though each line of the ASCII art.

```
Ｍ✳⁻ι⊗⊕‹⊗κＬυ

```

Move along the edge of the hexagon.

```
Ｐ✳⊖ι§υκ

```

Output the line of ASCII art.

```
»Ｆ²«

```

Loop through each reflection.

```
⊞θ⪫ＫＡω

```

Serialise the ASCII art back to text and join all of the lines together.

Reflect the ASCII art horizontally.

```
»⎚

```

Clear the canvas ready for the next rotation.

```
»Ｆ✂θ⊞θ⮌ι

```

Append the 180° rotations of the above rotations and reflections to the list.

```
⊙θ⊖№θι

```

Check the list for duplicates.

Here's a 73 byte modification that takes (spaced) ASCII art as input and outputs all 12 rotations and reflections as ASCII art:

```
ＷＳ⊞υ⁻ι ≔⟦⟧θＦ³«ＦＬυ«Ｐ✳⊖ι⪫§υκ… ¬⊖ι¿‹⊗⊕κＬυＭ⊕¬ι✳⁺⁴÷×³ι²Ｍ⊕‹¹ι✳⁻⁻ι¬ι²»Ｆ²«Ｄ‖Ｄ‖↓»⎚

```

Try it online! Link is to verbose version of code. Output is in the following order:

* Rotate 60° clockwise
* Reflect along TL-BR diagonal
* Rotate 120° anticlockwise
* Reflect along BR-TL bisector
* Rotate 0°
* Reflect along T-B bisector
* Rotate 180°
* Reflect along L-R diagonal
* Rotate 60° anticlockwise
* Reflect along BR-TL diagonal
* Rotate 120° clockwise
* Reflect along TL-BR bisector

# Answer
> 5 votes
# Python 3.8 (pre-release), 137 bytes

```
g=lambda h:(*[".".join(r.split(".")[::-1])for r in h],)
f=lambda h,*S:len(S)<8>0<f(g(map("".join,zip(*(t:=h[::-1])))),h,g(t),*S)or h in S

```

Try it online!

The function `f` takes in a tuple of strings representing a left-skewed hexagon. Returns `True` if the hexagon is symmetric, or `False` otherwise.

# Explanation

At each iteration, adds the current hexagon and its vertical flip to the list `S`. Then rotates the hexagon by 60 degrees clockwise, and repeats. Stops when we finds a duplicate hexagon (symmetric), or if `S` gets too big (not symmetric).

#### Skew helper

`g` is a helper function that converts a right-skewed hexagon to a left-skewed one:

```
..ABC      ABC..
.DEFG      DEFG.
HIJKL  ->  HIJKL
MNOP.      .MNOP
QRS..      ..QRS

```

This is done by taking each row `r`, and swapping the empty (`.`) with non-empty positions: `".".join(r.split(".")[::-1])`

#### Rotate a hexagon

To rotate a hexagon: simply rotates the 2D array 90 degrees, then applies `g` to fix the skewness.

```
ABC..          ..HDA        HDA..
DEFG.   rot90  .MIEB   g    MIEB.
HIJKL  ------> QNJFC -----> QNJFC
.MNOP          ROKG.        .ROKG
..QRS          SPL..        ..SPL

```

Rotating a 2D array can be done with `map("".join,zip(*h[::-1]))`

#### Flip a hexagon vertically

Simply flips the 2D array vertically, then applies `g` to fix the skew: `g(h[::-1])`

# Answer
> 0 votes
# Pari/GP, 72 bytes

Based on @loopy walt's Python answer.

```
a->7>#Set([a=if(i%2,matrix(#a,,i,j,a[i,(#a\2+i-j)%#a+1]),a~)|i<-[1..8]])

```

Try it online!

Takes a matrix skewed to the left with zero padding.

---
Tags: code-golf, decision-problem, geometry, hexagonal-grid
---


title: 10 Clickbaits you can't resist

text:
# Question
Title: 10 Clickbaits you can't resist
Write a program/function/script that takes a natural number i from 1 to 10 as input and outputs the URL of the Question with the i th hottest question on the Code Golf Portal

The ordering should be like in https://codegolf.stackexchange.com/?tab=hot. For example:
*input 1*
*output https://codegolf.stackexchange.com/questions/127047/the-spain-license-plates-game*
(at the point of this edit)

There are no strong restrictions to the output, as long as the url can be reasonably retrieved. Valid outputs include strings, console printing etc.

It's Code Golf, so shortest code in Bytes wins.

## Notes

If your program automatically opens a browser with the webpage, it counts as valid output and is totally cool.

If your program does not retrieve the ranking from current information (i.e. hardcoding the links), it is not valid.

The contest ends with the end of June.

As questioned: The indexing must be 1 based, ie: the input 1 must return the the first site of the hottest questions.

### Comment

I hope this question is not too clickbaity, as the stack exchange editor program was mocking me for the title. Originally I planned this challenge with Youtube trends, where it would haven been more fitting.

# Answer
> 1 votes
# PowerShell v5, 83 Bytes

```
(irm api.stackexchange.com/questions?sort=hot`&site=codegolf).Items["$args"-1].Link

```

`irm` is short for `Invoke-RestMethod` which auto-parses the Json, makes life quite easy.

add four bytes (`saps` for `start-process`) for version which opens in browser.

```
saps(irm api.stackexchange.com/questions?sort=hot`&site=codegolf).Items["$args"-1].Link

```

# Answer
> 4 votes
# Python + requests, 128 bytes

```
from requests import*
lambda n:get('http://api.stackexchange.com/questions?sort=hot&site=codegolf').json()['items'][n-1]['link']

```

# Answer
> 3 votes
# Mathematica, 125 bytes

```
b="http://codegolf.stackexchange.com";b<>"/q/"<>StringCases[Import[b<>"?tab=hot","Text"],"ns/"~~a:DigitCharacter..:>a][[3#]]&

```

Anonymous function. Takes no input and returns a string as output. Was going to use the XML feed, but it seems to follow a different ordering than on the page.

# Answer
> 3 votes
# Python 3, 221 bytes

```
from urllib.request import*
import zlib, json
lambda n:json.loads(zlib.decompress(urlopen('http://api.stackexchange.com/questions?sort=hot&site=codegolf').read(),16+zlib.MAX_WBITS),encoding='utf-8')['items'][n-1]['link']

```

Based off of ovs answer. Also, thanks to Oluwafemi Sule for helping me with an issue I had.

# Answer
> 3 votes
# Python 2.7, 195 bytes

```
from urllib import*
import zlib, json
lambda n:json.loads(zlib.decompress(urlopen('http://api.stackexchange.com/questions?sort=hot&site=codegolf').read(),16+zlib.MAX_WBITS))['items'][n-1]['link']

```

This is same answer by Dair, but using Python 2

# Answer
> 2 votes
# Stratos, 28 bytes

```
"-1"+
f"¹⁵s²&sort=hot"r"⁷s"@

```

Explanation:

```
"-1"+                    Decrement the input, and store it.
f"¹⁵s²&sort=hot"         Fetch the contents of the URL api.stackexchange.com/questions?site=codegolf&sort=hot.
                r"⁷s"    Get the array named "items"
                     @   Get the nth element, where n is retrieved from storage.

```

Try it!

# Answer
> 1 votes
# JavaScript (ES6), 106 bytes

Returns a Promise containing the JSON object for the desired question, which includes the link.

```
n=>fetch`//api.stackexchange.com/questions?sort=hot&site=codegolf`.then(r=>r.json()).then(j=>j.items[--n])

```
* Sacrificed 2 bytes allowing for 1-indexing.

---

# Try it

```
f=
n=>fetch`//api.stackexchange.com/questions?sort=hot&site=codegolf`.then(r=>r.json()).then(j=>j.items[--n])
oninput=_=>f(+i.value).then(console.log)
f(i.value=1).then(console.log)
```

```
<input id=i type=number>
```

# Answer
> 1 votes
# 05AB1E \+ `json`, 85 bytes

```
<’¸¸.Â‚‹º.ŒŒ/…é?€¼=ƒËŠˆ&Šœ=…ß’.w„\"D„\\s‚‡’(EnÆá.€› (JSON.deƒË!"ÿ")["‚Õ"],ÿ)["ƒÚ"]’.E

```

---
Tags: code-golf, internet, stack-exchange-api
---


title: Probability breaking sequences

text:
# Question
Title: Probability breaking sequences
If we have a finite list of elements we can determine the probability of any one element being drawn at random as the number of times it occurs divided by the total number of elements in the list.

For example if the list is `[2,3,2,4]` the probability of drawing `2` is \\$\frac 1 2\\$ since there are \\$2\\$ `2`s and \\$4\\$ elements total.

For an infinite sequence we can't use this method. Instead what we can do is look at every prefix of the sequence determine the probability using the above method and then see if the limit of the probabilities converges. This looks like

$$ P(x, s\_i) = \displaystyle\lim\_{n\rightarrow\infty} \dfrac{\left|\left\\{s\_m\mid m\<n,s\_m=x\right\\}\right|}{n} $$

For example if we have the sequence which alternates between `0` and `1`, `[0,1,0,1,0,1...`, then the probability of drawing a `0` is \\$\frac 1 2\\$.

Now this is neat but sometimes the limit just doesn't converge, and so the probability of an element being drawn is undefined.

Your task will be to implement a sequence where for *every* positive integer its probability is undefined. This means that no matter what you pick this limit must not converge. It also means just as a side effect that every positive integer must appear an infinite number of times. Otherwise the probability would converge to \\$0\\$.

You may implement any sequence you wish as long as it fulfills the above. Your sequence should output non-negative integers. Zero is permitted to appear in the sequence but is not required to.

This challenge uses the defaults for sequence IO which can be found here.

This is so the goal is to minimize your source code with answers being scored in bytes.

# Answer
# x86 32-bit machine code, 7 bytes

```
0F BD C1 0F BC C0 C3

```

Try it online!

Following the `fastcall` calling convention, this takes the 1-indexed `n` in ECX and returns the `n`th value in EAX.

In assembly:

```
.global f
f:
    bsr eax, ecx
    bsf eax, eax
    ret

```

This produces blocks of size 1, 2, 4, 8, 16, ... of the same number, so that each block raises its number's proportion to more than half. `bsr` (find highest position of a 1 bit) is used to obtain the 0-indexed block number.

The values used for the blocks are (0), 0, 1, 0, 2, 0, 1, 0, 3, ...; these values are produced by `bsf` (find lowest position of a 1 bit) on the block number. (The result of `bsf` is officially undefined for a value of 0, but on at least some systems it consistently leaves the destination register unchanged, producing 0 for block 0.)
> 8 votes

# Answer
# Python 2, 24 bytes

```
lambda n:`n`.find("1")+1
```

Attempt This Online!

This is heavily based on @xnor's idea in the comments. It returns the (1-based) index of the most significant decimal "1" and 0 if there is none.

Why does it work?

for any cutoff 10^k the fraction of numbers below it that have the first "1" at position n (n\<k) is asymptotically the same, in particular, it is bounded below by a positive number. But between 10^k and 2x10^k there are no such numbers, meaning that frequency will eventually fall to half its value (and then rise again) which is incompatible with convergence.

The case k=1 must be dealt with separately (easy) and k=0 is exempt by OP.

# Python, 36 bytes

```
lambda n:int(bin(len(bin(n)))[3:],2)
```

Attempt This Online!

Takes an index and returns the corresponding value. Numbers are first mapped to the length of their binary representation. That way whatever this finally maps to is elevated to a probability of roughly 0.5. As a simple way to make sure every number comes back eventually, we take again the binary representation and use the most significant bit for modulo. In other words we remove it and all leading zeros that may be exposed.

The test code first shows the first 1000 items and then the unique values of the first 1000 blocks.
> 8 votes

# Answer
# Python 3, 41 bytes

```
j=1
while j:j+=1;print([str(j)[1:]]*2**j)

```

Try it online!

Here, we increment `j` and strip the leading digit, to get a sequence where every number appears infinitely often. Let's call the stripped number `k`. Then we output `2**j` copies of `k`. This has the property that the probability of `k` jumps up to 50%, when we ouput `k`, then decreseas by half after every iteration. This means that the probability of `k` doesn't converge.

The probability jumps occur because \\$2^j\>\displaystyle\sum\_{n=1}^{j-1}2^n\\$

The IO format is a bit rough, to say the least. The output is a non-digit separated list of numbers, which may have leading zeros.

# Python 3, 48 bytes

```
j=10
while j:j+=1;print(*[int(str(j)[1:])]*2**j)

```

Try it online!

Same idea, except the output looks a bit nicer. Numbers don't have leading zeros and the output is whitespace separated.

# Python 3, 39 bytes

```
j=2
while j:j+=1;print([~-2**j%j]*2**j)

```

Try it online!

This is based on a conjecture that \\$2^n\mod n\\$ will take all values, except 1, infinitely often. To fix the missing \\$1\\$, we can compute \\$2^n-1\mod n\\$, and now \\$0\\$ will be the missing value.
> 3 votes

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

```
n=>parseInt(10+Math.log(n),2)

```

Try it online!

Like m90's idea, output each number for a time, making it go up to parseInt(k,2), which every number happen for infinite times(`10012xxxx` for 9, etc.)
> 1 votes

---
Tags: code-golf, sequence, open-ended-function
---


title: Blinking twelve

text:
# Question
Title: Blinking twelve
Many electronic devices, specially old ones, will show a blinking `12:00` when the time has not been set. The purpose of this challenge is to recreate this.

Specifically, the task is to **display `12:00` and `--:--` alternatively in an infinite loop**.

The **period** should be 1 second, divided evenly in two periods of 0.5 seconds. Here "1 second" and "evenly" can be interpreted loosely. For example, it is acceptable if the code pauses for 0.5 seconds between displaying the strings, even if the resulting period will then be a little higher than 1 second. An initial pause before displaying the first string is acceptable.

Each new string can be displayed either by **replacing the former string** or **in a new line**. Trailing whitespace is allowed, except that if each new string is on a different line there should be no empty lines between consecutive strings.

Shortest code in bytes wins.

# Answer
# Jelly, 20 bytes

```
.“12:00“--:--”ṄœS¥€ß

```

## How it works

```
.“12:00“--:--”ṄœS¥€ß  Main link. No arguments.

.                     Set the return value to 0.5.
 “12:00“--:--”        Yield ["12:00", "--:--"].
                 ¥    Combine the two links to the left into a dyadic chain.
              Ṅ       Print the left argument.
               œS     Sleep as many seconds as the right argument specifies.
                  €   Map the created dyadic chain over the string array, with
                      right argument equal to the return value, i.e., 0.5.
                   ß  Recursive call the main link.

```
> 5 votes

# Answer
## HTML/CSS, ~~131~~ ~~108~~ ~~106~~ 101 + ~~18~~ 17 = ~~149~~ ~~126~~ ~~125~~ ~~123~~ 118 bytes

```
a{background:#FFF;margin:-5ch;animation:a 1s steps(2,start)infinite}@keyframes a{to{visibility:hidden
```

```
<tt>--:--<a>12:00
```

Edit: Saved 23 bytes thanks to @insertusernamehere. Saved 1 byte by switching from `<pre>` to `<tt>`. Saved 2 bytes thanks to @darrylyeo. Saved 5 bytes thanks to @DBS.
> 34 votes

# Answer
# Shell and `pv`, 26 bytes

This use `yes` standard tool and `pv` *Shell pipeline element to meter data passing through*

```
yes '12:00
--:--'|pv -qlL2

```
> 16 votes

# Answer
# Octave, ~~63~~ ~~62~~ ~~61~~ 55 bytes

```
c='--:--00:21';while c=flip(c)disp(c(1:5));pause(.5)end

```

Saved two bytes thanks to Tom Carpenter! Using a single string instead of two strings in a cell array was shorter.

**Explanation:**

```
c='--:--00:21';  % A string where the 5 first characters are --:-- or 12:00 when reversed
while c=flip(c)  % A string is always considered true in Octave, so this will loop forever
                 % while flipping the order of the string each time
 disp(c(1:5)     % display the 5 first characters of the string c
 pause(.5)       % Pause 0.5 second
end              % End loop

```

A few bytes saved because Octave doesn't require a colon or semicolon between `flip(c)` and `disp()`, and between `pause(.5)` and `end`.
> 15 votes

# Answer
# Python2, ~~80~~ ~~75~~ ~~73~~ ~~69~~ ~~67~~ 66 bytes

```
import time
n=0
while[time.sleep(.5)]:print"1-2-::0-0-"[n::2];n^=1

```

~~I noticed that my string magic got a little longer than picking the string from an array.~~ Nevermind, figured it out.

**Explanation**:

* I set a counter **n** to 0, which will be toggled between 0 and 1.
* I loop endlessly with the loop `while 1`.
* I create a string `1-2-::0-0-`, which contains the string `12:00` and `--:--` interlapped.

+ Starting from the index 0 with a step of 2, we get: `12:00`
    + Starting from the index 1 with a step of 2, we get: `--:--`
* I use **n** to make the repeated sequence **0**, **1**, **0**, **1**, **0**... which will be the starting index of the string.

+ Using `n^=1`, in each loop, we get that sequence. `^` being the XOR-operator.
    + If **n** == 0 --\> `n^=1` results in 1
    + If **n** == 1 --\> `n^=1` results in 0
* I print the string, and sleep (`.5` -\> `0.5`) seconds.

@FlipTack saved 4 bytes! --\> Put the loop in one line.

@Rod saved 2 bytes! --\> `n+=1` to `n^=1`, thus `n%2` to `n`.

@xnor saved a byte! --\> `while 1` --\> `while[time.sleep(.5)]`.
> 15 votes

# Answer
### bash, ~~58 56 45~~ 41 bytes

New version 2022, (not very system friendly), but...

```
bash <(yes "read -t.5 -p"{--:--,12:00}\;)

```

or with *newline*: 45

```
bash <(yes "read -t.5 -p'
"{--:--,12:00}"';")

```

or with *carrier return*: 47

```
bash <(yes "read -t.5 -p$'\r"{--:--,12:00}"';")

```

~~saved 3 byte by suppressing `--` after `set` as 1st arg is a number.~~

~~```
set 12:00 --:--;for((a=1;;a=3-a)){ echo ${!a};sleep .5;}

```
Saved 16 byte by using @DigitalTrauma's syntax:
```
f()(echo $1;sleep .5);f 12:00;f --:--;exec $0

```~~

Then loosing 5 bytes because of zeppelin's comment.

This could not be tested on command line. As we involve `$0`, this must be written into a script to run.

### Divert

With a little preparation, this could become nice (**412 bytes**):

```
set -- "         ▗▖
▗▄▄▖▗▄▄▖ ▝▘ ▗▄▄▖▗▄▄▖
         ▗▖
         ▝▘         " " ▟▌ ▟▀▜▖ ▗▖ ▗▛▙ ▗▛▙
 ▐▌  ▗▟▘ ▝▘ █▗▐▌█▗▐▌
 ▐▌ ▗▛▗▖ ▗▖ ▜▖▟▘▜▖▟▘
▝▀▀▘▀▀▀▘ ▝▘  ▀▘  ▀▘ "
r=`tput cup 0`
clear;for((a=1;;a=3-a)){ printf "$r${!a}";sleep .5;}

```

Or even same two lines but with:

```
set -- '

      HM!          .o#HMMMMM#o.                 .o#MMMMH#\\         .d#MMMMH#\\
    _HMMi         ?MMH*"""`"MMMb               dMMH"""`*MMH,      dMMH"""`*MMH.
##HMMMMMi        |MMP"       9MML             ?MMP      `MMM.    dMM?      `MMM.
`""`"9MM|        dMM!        -MMR     HMH}   .MMM        |MM}   .MMH        |MM|
     |MM|         "`         JMMT     dHH}   |MM|         MMM   |MM|        -MMM
     |MM!                 .,HMM*             |MM|         MMM.  ]MM|         MMM
     |MMi              _o#MMH*"              |MM|         MMM   {MM|         MMM
     |MMi           .dHMM#""                 |MM|         MMM"  {MM|        .MMM
     |MMi         .HMM*"                     `MM6        ,MMR   |MM}        |MMF
     |MMi        ,MMP"                        9MM,       dMM|    HMM,       dMM"
     {MMi        MMM?\\o,\\\\\\\\\\\\\\\\,     q##+    `HMM\\    .dMM?     `HMH\\    .dMM?
     |MM|       :MMMMMMMMMMMMMMM[     HMMk     `*HMM##MMM#"       `*HMM##MMMP"
      "`          "     ` ` ` `                   """"`""            """"""    ' '

                                      MHM|
                                      HHH|

               ______.  ._______.            ________.  ._______.
               MMMMMM:  {MMMMMMM|            &MMMMMMM:  |MMMMMMM[

                                      ###|
                                      MMM|
                                                                               '

```
> 11 votes

# Answer
# , ~~31~~ ~~30~~ ~~27~~ ~~25~~ 24 bytes

*Saved 5 bytes thanks to @nmjcman101 by swapping the order of `12:00` and `--:--` so that `k` can be removed any by removing `ò` so that it could be added implicitly at the end*

*Saved 1 byte thanks to @DJMcMayhem by putting both `12:00` and `--:--` in one line*

```
i12:00--:--<ESC>bDòVp:sl500m

```

Old Solution:

```
i12:00<ESC>ò:sl500m
Óä/-
:sl500m
uò

```

`<ESC>` is `0x1b`

Hexdump:

```
00000000: 6931 323a 3030 2d2d 3a2d 2d1b 6244 f256  i12:00--:--.bD.V
00000010: 703a 736c 3530 306d                      p:sl500m

```

### Explanation

```
i12:00--:--<ESC>   inserts 12:00\n--:--
bD                 go to the beginning of --:-- and delete it
ò                  recursively do:
 Vp                 select line and paste (effectively doing a replace)
 :sl500m            sleep for 500 milliseconds
                   the last ò is added implicitly at the end

```

### Gif (outdated)

**Note:** I have highlighting turned on
> 11 votes

# Answer
# JavaScript, 59 bytes

```
y=1;setInterval('console.log(["12:00","--:--"][y^=1])',500)
```

**Explanation**

`setInterval('...',500)` sets an interval to execute code in the string every 500 milliseconds, or 1/2 a second.

`y=1` sets a variable, `y`, to 1 initially. That way, the first thing that is printed is `12:00` because `y` is used to access the array.

`console.log(...)` logs whatever to the console, in this either `12:00` or `--:--`.

`["12:00","--:--"][y^=1]` creates an array with strings containing both states. Then, `y` is used to access one of elements. Finally, `^=`, or XOR compound operator does `y = y ^ 1`. This just inverts the bit because `1 ^ 1` is 0, and `0 ^ 1` is 1, similar to what @TuukkaX did. This way, the string logged alternates between the two elements in the array and thus creates the blinking effect.
> 11 votes

# Answer
## Perl, 49 bytes

```
{select$,,$,,$,,0.5;say$|--?"12:00":"--:--";redo}

```

Perl's `sleep` can't sleep for duration bellow 1 sec, hence the use of `select undef, undef, undef, .5` (golfed by replacing `undef` with `$,`) to sleep .5 second.
Other interesting thing: `$|` can only hold `0` or `1`. So `$|--` just toggles its value, from `0` to `1`.
And finally, `{... ;redo}` acts like an infinite loop.
> 9 votes

# Answer
# Noodel, 16 bytes

```
--:-- 12:00ḷçėḍh

```

*Noodel* is still very much a work in progress. Just trying to get my feet wet with a couple of challenges.

Try it:)

### How It Works

```
--:--            # Creates the string literal "--:--" and places i into the front of the pipe.
                 # Space is a NOP command to separate the string literals.
      12:00      # Creates the string literal "12:00" and places it into the front of the pipe.
           ḷ     # Loop the following code unconditionally.
            ç    # Clear the screen and print a copy of what is in the pipe.
             ė   # Take what is in the front of the pipe and put it into the back.
              ḍh # Delay for half a second.

```

---

Here is a code snippet:)

```
<div id="noodel" code="--:-- 12:00ḷçėḍh" input="" cols="10" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 7 votes

# Answer
# \*\>\<\>, ~~43~~ 42 bytes

```
<v":1200----"
S>@5dov>~r@@}r5
1&}o:&<^!?:-

```

Try it here!

I feel like I should be able to make this shorter, I have a couple ideas to try ... Basically this makes a stack of `:1200----`. It isolates the `:` and flips the stack, inserting the `:` in the middle of either `----` or `1200` (depending on whichever is at the end of the stack).

I should also note that the only \*\>\<\> instruction this uses is `S` (sleep), otherwise this is a proper \>\<\> program.

Update: Saved 1 byte by shifting the `:` to the right instead of protecting it with a register.

## Explanation

### Initialisation

```
<v":1200----"

```

Here we build the stack we'll be using for the life of the program.

```
<              move the IP left
  ":1200----"  push ":1200----" to the stack
 v             move the IP down into "output time"

```

### Output time

```
 >@5dov
1&}o:&<^!?:-

```

This is the section where the time is actually outputted. First 5 is pushed to the stack so the loop below knows to run 5 times.

```
Initialisation:

 >@5dov

 >       move the IP right
  @      move the ":" back two spaces in the stack
   5     push 5 to the stack (let's call this `i`)
    do   output carriage return
      v  move IP down into "loop"

Loop:

1&}o:&<^!?:-

      <       move the IP left
     &        place i onto the register
  }o:         output a character and shift the stack left
 &            place i back onto the stack
1          -  decrement i by 1
       ^!?:   if i == 0, exit to "recover and swap"

```

### Recover and swap

```
S      >~r@@}r5

```

Here we recover the `:` from the position it results in after the output, and we end up with a reversed stack. This actually exits into "output time" nicely, causing an infinite loop.

```
       >         move the IP right
        ~        remove trailing i from stack
         r@@     reverse the stack and move ":" to the front
            }r   reverse the stack again, keeping ":" on the front
S             5  sleep for 500ms

```

---

### 45 byte solution

```
<v[5"12:00"1
d/S5
o/!?l
v>]?v
 00.>0"--:--"5[

```

Try it here!

This one is also basically a \>\<\> program.

I really thought it'd be able to save some bytes with this approach. This quite simply outputs `12:00`, then `--:--`. I save bytes by reusing the output routine `o/!?l` (I even reuse that mirror as both entry and exit). I utilise multiple stacks to store the state (has output `12` or `--`), and select which state I should output with `v>]?v`.

Explanations coming soon! (1/2)
> 6 votes

# Answer
## HTML/CSS (Chrome only), 80 + 4 = 84 bytes

```
tt:after{content:"--:--";animation:a 1s infinite}@keyframes a{to{content:"12:00"
```

```
<tt>
```

**Edit**: The "content" attribute is not *animatable* by the CSS specification, but is on Chrome desktop browser.
> 6 votes

# Answer
## QBIC, ~~37~~ 33 bytes

```
{sleep 01?@12:00`┘sleep 01?@--:--

```

QBasic unfortunately can only sleep for whole seconds. I'll see about devising a method to allow for more flexibility soon. I've input 1 as `01` to simulate `.5`.

Explanation:

```
{         Starts DO loop
sleep 01  Sleeps for 1 second
?@12:00`  Creates A$, sets value to "12:00" and prints A$
┘         Newline: a string literal doesn't break the line, so we need a newline to
          control the compiled QBasic syntax
          <Rinse and repeat for "--:--">
          <DO-LOOP implicitly closed by QBIC>

```

In older builds of QBIC, `$` and  (space) were reserved characters. Calling a QBasic function that needed spaces (like `sleep x`) or `$` (`left$(..)`) required a code literal:

```
'QBASIC CODE`

```

Code in a code literal block is passed directly to QBasic without being parsed by QBIC. By offloading functions from those symbols (`$` became `'`, and newlines are now  (alt-217) instead of ) the symbols are no longer seen by QBIC as special chars and simply passed on. The same is effectively true for the lowercase alphabet: it's used to represent numeric variables in both QBIC and QBasic and are left unchanged. Using QBasic functionality that is not implemented in QBIC (like `SLEEP`) is therefor simply a matter of not using QBIC reserved chars. This is made easier with the recent changes in the command symbols.
> 5 votes

# Answer
# LibreLogo, 100 bytes (Non-Competing)

**Code:**

```
ht point fontsize 99 repeat [ cs sleep 500 if repcount % 2 [ label '12:00' ] else [ label '--:--' ]]

```

**Explanation:**

```
ht                            ; Hide Turtle (Unnecessary... Added for visual clarity)
point                         ; Draw a point with size and color of the pen
fontsize 99                   ; Font Size = 99 pt (Unnecessary... Added for visual clarity)
repeat [                      ; Endless Loop
    cs                        ; Clear Screen
    sleep 500                 ; Wait for 500 ms
    if repcount % 2 [         ; If the Repetition Count is Even...
        label '12:00'         ; Draw '12:00'
    ]
    else [                    ; Otherwise...
        label '--:--'         ; Draw '--:--'
    ]
]

```

**Result:**
> 5 votes

# Answer
# JavaScript, ~~77~~ ~~76~~ 72 bytes

```
setInterval('l=console.log,l("12:00"),setTimeout("l(`--:--`)",500)',1e3)

```

Thanks to Kritixi Lithos for 1 byte and L. Serne for 4 bytes!
> 4 votes

# Answer
# Python 2, ~~88~~ ~~85~~ ~~73~~ 71 bytes

```
import time
c="--:--00:21"
while 1:print c[:5];c=c[::-1];time.sleep(.5)

```

Try it here!

By borrowing Stewie Griffin's idea of flipping the list, the program was made possible. Ungolfed version with explanation:

```
import time                      # Import time module
c = "--:--00:21"                 # String with two values
while 1:                         # Infinite Loop
    print c[::5]                 # Print the first 5 chars in string
    c = c[::-1]                  # Flip the string
    time.sleep(.5)               # Wait 0.5 seconds

```

Thanks @FlipTack for saving 14 bytes!
> 4 votes

# Answer
# PHP, 51 50 47

```
for(;;usleep(5e5))echo$i++%2?"--:--
":"12:00
";

```

1 byte saved due to manatwork and another 3 saved by insertusernamehere. Thanks!
> 4 votes

# Answer
## Pyth, 23 bytes

```
#?=!Z"12:00""--:--".d.5

```

In pseudocode:

```
                Z = 0
#               while 1:
 ?=!Z               if ( Z = not Z ):
     "12:00"            print("12:00")
                    else:
     "--:--"            print("--:--")
 .d.5               sleep(0.5)

```

Uses preinitialized variable `Z` as the flip-flop, and inverts its state every time `if` tries to check the condition.
> 3 votes

# Answer
# Mathematica, 38 bytes

```
Dynamic@If[Clock[]>.5,"12:00","--:--"]

```

**Explanation**

```
Clock[]

```

Outputs a clock variable that cycles continuously from 0 to 1 every second.

```
If[Clock[]>.5,"12:00","--:--"]

```

If the clock variable is greater than .5, output "12:00." If not, output "--:--".

```
Dynamic@ ...

```

Make the program dynamic (constantly updating)
> 3 votes

# Answer
# Perl 6,  ~~48 41~~  34 bytes

```
loop {print "\r",<--:-- 12:00>[$_=!$_];sleep .5}

```

```
loop {put <--:-- 12:00>[$_=!$_];sleep .5}

```

```
sleep .put/2 for |<12:00 --:-->xx*

```
> 3 votes

# Answer
# GNU sed, 39 bytes

EDITS:

* Swapped *sleep* and *i12:00* (to make source code look a bit nicer)

**Golfed**

```
s/^/sleep .5/
h
i12:00
e
i--:--
x
e
G
D

```

**Explained**

```
s/^/sleep .5/   #Put 'sleep .5' to the pattern space
h               #Copy pattern space to hold space
i12:00          #Print "12:00" (insert before a line)
e               #Execute command that is found in pattern space
i--:--          #Print "--:--"
x               #Exchange the contents of the hold and pattern spaces
e               #Execute command that is found in pattern space

G               #Append a newline to the contents of the pattern
                #space, and then append the contents of the hold
                #space to that of the pattern space.

D               #Delete text in the pattern space up to the
                #first newline, and restart cycle with the
                #resultant pattern space, without reading a new
                #line of input.

```

Try It Online !
> 3 votes

# Answer
# dc (bash), 37 bytes

```
[12:00][--:--][[rp!sleep .5]xlax]dsax

```

This works by pushing the two strings "12:00" and "--:--" on the stack and then repeatedly swapping the values, printing the item at the top of the stack, and sleeping half a second.

To run this, you can save it in a file and then type

> dc *filename*

or you can run it directly from the bash command line by typing

> dc \<\<\<'\[12:00\]\[--:--\]\[\[rp!sleep .5\]xlax\]dsax'
> 3 votes

# Answer
## ruby, 47 42 bytes

No ruby answer yet, so here is my first try:

```
%w{12:00 --:--}.cycle{|a|puts a;sleep 0.5}

```
> 3 votes

# Answer
# Vim, 32 keystrokes

```
qq:sl500m<CR>S12:00<Esc>:<UP><CR>S--:--<Esc>@qq@q

```
> 3 votes

# Answer
# **Python 3, 75 bytes**

```
import time
x=['12:00','--:--']
for i in x:x+=[i];print(i);time.sleep(.5)

```
> 3 votes

# Answer
# Jelly, 22 bytes

```
®‘©ị“12:00“--:--”ṄœS.ß

```

Doesn't work on TIO. Getting Jelly to run on Android with QPython3 was also a fun experience.

### Explanation

```
®‘©ị“12:00“--:--”ṄœS.ß    Main link. No arguments.
®                         Read the register. Initially 0.
 ‘                        Increment.
  ©                       Save to the register.
   ị                      Get the n'th (wrapping) item of...
    “12:00“--:--”         ["12:00", "--:--"]
                 Ṅ        Print the string and a newline.
                  œS      Sleep for...
                    .     ...0.5 seconds. (. is an alias for 0.5)
                     ß    Call this link again.

```
> 2 votes

# Answer
# Javascript, 57 55

```
setInterval('console.log(++i%2?"12:00":"--:--")',i=500)

```

2 bytes saved thanks to ETHproductions
> 2 votes

# Answer
# Javascript (in browser), ~~174~~ ~~160~~ ~~159~~ ~~122~~ ~~112~~ ~~111~~ ~~109~~ ~~107~~ 66 (91) bytes

I've taked of `pre` because using monotyped font is not part of requirement, so my new count is **66**. Some chars are added to use monospaced font but as this is not needed, I won't count this **25** more chars.

Thanks to ETHproductions for saving 14 bytes,

to Kritixi Lithos for saving 1 byte,

to manatwork for saving ~~1~~ **3** byte,

to Christoph for saving two more bytes and

to myself for saving 37 bytes by using `[..][b^=1]` instead of `setTimeout`... and 10 more by replacing `function(){..}` by double-quotes...

```
setInterval("document.body.innerHTML=++b%2?'12:00':'--:--'",b=500)
```

```
body{font-family:Courier}
```

... worse:

## From 66 to *something more*...

... but for fun, in the spirit of a blinking display:

```
SVG="http://www.w3.org/2000/svg";XLNK="http://www.w3.org/1999/xlink";
s=["1200","----"];p=0;function d(n){for(i=n.length;i>0;i--) {
  document.getElementById('n'+i).setAttribute('class','n'+n[i-1])}
  document.getElementById('sz').setAttribute('class','n'+n[0])}
setInterval("p=1-p;d(s[p])",500);
```

```
#svg2 { --c: #FF6;stroke:#432;stroke-width:12;stroke-linecap:round;stroke-linejoin:round; stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none; } path.b { fill:#543;stroke:none; } .blue     { --c: #68F; } .green    { --c: #6F8; } .red      { --c: #F88; } .dec rect  { stroke: var(--c); } .n1 #B { stroke: var(--c); }  .n1 #C { stroke: var(--c); } .n2 #A { stroke: var(--c); }  .n2 #B { stroke: var(--c); } .n2 #D { stroke: var(--c); }  .n2 #E { stroke: var(--c); } .n2 #G { stroke: var(--c); }  .n3 #A { stroke: var(--c); } .n3 #B { stroke: var(--c); }  .n3 #C { stroke: var(--c); } .n3 #D { stroke: var(--c); }  .n3 #G { stroke: var(--c); } .n4 #B { stroke: var(--c); }  .n4 #C { stroke: var(--c); } .n4 #F { stroke: var(--c); }  .n4 #G { stroke: var(--c); } .n5 #A { stroke: var(--c); }  .n5 #C { stroke: var(--c); } .n5 #D { stroke: var(--c); }  .n5 #F { stroke: var(--c); } .n5 #G { stroke: var(--c); } .n6 #A { stroke: var(--c); }  .n6 #C { stroke: var(--c); } .n6 #D { stroke: var(--c); }  .n6 #E { stroke: var(--c); } .n6 #F { stroke: var(--c); }  .n6 #G { stroke: var(--c); } .n7 #A { stroke: var(--c); }  .n7 #B { stroke: var(--c); } .n7 #C { stroke: var(--c); } .n8 #A { stroke: var(--c); }  .n8 #B { stroke: var(--c); } .n8 #C { stroke: var(--c); }  .n8 #D { stroke: var(--c); } .n8 #E { stroke: var(--c); }  .n8 #F { stroke: var(--c); } .n8 #G { stroke: var(--c); } .n9 #A { stroke: var(--c); }  .n9 #B { stroke: var(--c); } .n9 #C { stroke: var(--c); }  .n9 #D { stroke: var(--c); } .n9 #F { stroke: var(--c); }  .n9 #G { stroke: var(--c); } .n0 #A { stroke: var(--c); }  .n0 #B { stroke: var(--c); } .n0 #C { stroke: var(--c); }  .n0 #D { stroke: var(--c); } .n0 #E { stroke: var(--c); }  .n0 #F { stroke: var(--c); } .n11 #B { stroke: var(--c); } .n11 #C { stroke: var(--c); } .n11 #E { stroke: var(--c); } .n11 #F { stroke: var(--c); } .nA #A { stroke: var(--c); }  .nA #B { stroke: var(--c); } .nA #C { stroke: var(--c); }  .nA #E { stroke: var(--c); } .nA #F { stroke: var(--c); }  .nA #G { stroke: var(--c); } .nB #C { stroke: var(--c); }  .nB #D { stroke: var(--c); } .nB #E { stroke: var(--c); }  .nB #F { stroke: var(--c); } .nB #G { stroke: var(--c); } .nC #A { stroke: var(--c); }  .nC #D { stroke: var(--c); } .nC #E { stroke: var(--c); }  .nC #F { stroke: var(--c); } .nD #B { stroke: var(--c); }  .nD #C { stroke: var(--c); } .nD #D { stroke: var(--c); }  .nD #E { stroke: var(--c); } .nD #G { stroke: var(--c); } .nE #A { stroke: var(--c); }  .nE #D { stroke: var(--c); } .nE #E { stroke: var(--c); }  .nE #F { stroke: var(--c); } .nE #G { stroke: var(--c); } .nF #A { stroke: var(--c); }  .nF #E { stroke: var(--c); } .nF #F { stroke: var(--c); }  .nF #G { stroke: var(--c); } .nR #E { stroke: var(--c); }  .nR #G { stroke: var(--c); } .nO #C { stroke: var(--c); }  .nO #D { stroke: var(--c); } .nO #E { stroke: var(--c); }  .nO #G { stroke: var(--c); } .n- #G { stroke: var(--c); }  .n1 #y { stroke: var(--c); } .n1 #z { stroke: var(--c); }
```

```
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 645 230" id="svg2"> <defs id="dfs4"><g id="n"><path d="M 15,5 155,5 145,225 5,225 z" class="b"/> <path id="A" d="M 45,15 125, 15"/><path id="B" d="M 135,25 125,105"/><path id="C" d="M 125,125 115,205"/><path id="D" d="M 25,215 105,215"/><path id="E" d="M 25,125 15,205"/><path id="F" d="M 35,25 25,105"/><path id="G" d="M 35,115 115,115"/><rect id="P" width="5" height="5" ry="2.5" x="130" y="205"/></g><g id="s"><path d="M 10,5 35,5 25,225 0,225 z" id="a" class="b"/><rect id="y" width="5" height="5" ry="2.5" x="13.5" y="145"/><rect id="z" width="5" x="17" height="5" ry="2.5" y="75"/></g></defs><use id="n1" xlink:href="#n" /><use id="n2" xlink:href="#n" transform="translate(150,0)" /><use xlink:href="#s" id="sz" transform="translate(305,0)"/><use id="n3" transform="translate(335,0)" xlink:href="#n" /><use id="n4" xlink:href="#n" transform="translate(485,0)" />
</svg>
```
> 2 votes

# Answer
### Postscript ~~225~~ 214

For fun only! Don't send this to a real printer!!

```
/Courier findfont 9 scalefont setfont{usertime 500 mod 5 lt{newpath 9 9 moveto 1 setgray 99 setlinewidth 99 99 lineto stroke 0 setgray}if newpath 9 9 moveto usertime 999 mod 500 lt{(--:--)}{(12:00)}ifelse show}loop

```

Try it:

```
gs -c '/Courier findfont 9 scalefont setfont{usertime 500 mod 5 lt{newpath 9 9 moveto 1 setgray 99 setlinewidth 99 99 lineto stroke 0 setgray}if newpath 9 9 moveto usertime 999 mod 500 lt{(--:--)}{(12:00)}ifelse show}loop'

```

or

```
cat <<eops >/tmp/blinkingTwelve.ps
%!
/Courier findfont
9 scalefont
setfont
{
  usertime 500 mod 5 lt {
    newpath
    9 9 moveto
    1 setgray
    99 setlinewidth
    99 99 lineto
    stroke
    0 setgray
  } if
  newpath
  9 9 moveto
  usertime 999 mod 500 lt {
    (--:--)
  } {
    (12:00)
  } ifelse
  show
} loop
eops

```

then

```
gs /tmp/blinkingTwelve.ps
gv /tmp/blinkingTwelve.ps

```

But **don't try to open this** with more sophisticated viewer and **care about desktop thumbnailer**!
> 2 votes

# Answer
## QBasic (QB64) ~~55~~ 53 Bytes

```
A$="12:00
B$="--:--
DO
?A$
_DELAY .5
SWAP A$,B$
LOOP

```

Saved 2 bytes as newline appears to terminate the string definitions.

SWAP makes all the difference. For vanilla QBASIC replace `_DELAY` with `SLEEP S` where `S` is an integer in seconds, but then the frequency is wrong.
> 2 votes

# Answer
# Q/KDB+, 61 Bytes

```
s:("12:00";"--:--")
b:1b
.z.ts:{b::not b;show s[b]}
\t 500

```

Explanation:

```
s:("12:00";"--:--")

```

Assign the values we wish to show in a list.

```
b:1b

```

Assign a boolean variable to flip between 0 and 1 easily.

```
.z.ts:{b::not b;show s[b]}

```

This is a KDB+ function which is invoked in set intervals by the timer function (\t) http://code.kx.com/wiki/Reference/dotzdotts
This executes the code inside the curly braces when \t is set. Show the value in s and then flipping the value of b between 0 and 1.

```
\t 500

```

Effectively calls .z.ts every 500ms.
> 2 votes

# Answer
# Windows PowerShell, ~~46~~ 55 bytes

```
function a{sleep -m 500;cls};for(){"12:00";a;"--:--";a}

```

### Original Code:

```
a{sleep -m 500;cls};for(){"12:00";a;"--:--";a}
^ this won't work on other PCs. No idea why.

```
> 2 votes

# Answer
## QuickBASIC, 167 bites (yummy)

```
a%=VAL(RIGHT$(STR$(TIMER*100),2))
b%=a%+50
IF b%>99THEN b%=b%-99
DO
c%=VAL(RIGHT$(STR$(TIMER*100),2))
IF c%=a% THEN PRINT"--:--"
IF c%=b% THEN PRINT"12:00"
LOOP

```

I was never going to win anyways. QB doesn't have a floor(), and also doesn't have a function to sleep for *x* milliseconds. Therefore, this works by grabbing the floating point portion of the TIMER (returns seconds elapsed since midnight, plus a fraction of the current second expressed as a two-digit decimal). We then add a loop-around "50 units" to it to determine when the phase should switch from "--:--" to "12:00", and use the original TIMER decimal for the switch from "12:00" to "--:--".

Finally, even running this complied in QB4.5, in DOSBox on a rather powerful machine will skip beats. That's because QB really isn't fast enough to perform the DO-LOOP and evaluations inside of the MS we're doing the comparison in. Would need a box from the FUTURE!

Anyway, I now look 100, and I made every American University student happy since they probably have an answer for their Comp Sci class -- since they're still teaching this...
> 2 votes

# Answer
# Clojure, ~~79~~ 62 bytes

## V2

-17 bytes by changing from an awful indexing loop to looping over an infinite list.

Creates an infinite list of `"12:00"` and `"--:--"` repeating over and over again, then uses `doseq` to constantly pull the next message, and print it.

```
(doseq[m(cycle["12:00""--:--"])](Thread/sleep 500)(println m))

```

## V1

```
(loop[i 0](Thread/sleep 500)(println(["12:00""--:--"]i))(recur(if(= 0 i)1 0))))

```

I couldn't think of a good way to compact the "12:00" and "--:--" constants, so I had to just hard code them.

Ungolfed:

```
(loop [i 0] ; Track which sign we showed last
    (Thread/sleep 500)
    (println (["12:00" "--:--"] i)) ; Index the vector to get the string to print
    (recur (if (= 0 i)1 0))) ; Swap the index, and loop again

```
> 2 votes

# Answer
# Pushy, 22 bytes (non-competing)

```
`--:`wO`12:0`&["500oWF

```

This answer makes use of the two stacks, by flipping between them, printing the characters in turn:

```
`--:`    \ Push these characters to stack 1
 w       \ Mirror around center, yielding "--:--"
 O       \ On the second stack...
 `12:0`  \ Push these characters
 &       \ Duplicate the last (for :00)

 [        \ Infinitely:
  "       \   Print the current stack
  500oW   \   Wait 500 milliseconds
  F       \   Swap stacks
          \ (Implicit end loop)

```

The `oW` command is part of a set of experimental commands that postdate the challenge, making this answer non-competing.
> 2 votes

# Answer
# Powershell, ~~46~~ 45 bytes

*-1 byte, thanks @AdmBorkBork*

```
for(){('12:00','--:--')[$i++%2]
sleep -m 500}

```
> 2 votes

# Answer
# C# (.NET Core), ~~138~~ ~~131~~ 127 bytes

```
class H{static int Main(){for(int n=1;;System.Threading.Thread.Sleep(500))System.Console.WriteLine((n^=1)>0?"--:--":"12:00");}}

```

Try it online!

Simple one-liner code.

---

# C# (.NET Core), 127 bytes

```
class H{static int Main(){for(int n=1;;System.Threading.Thread.Sleep(500))System.Console.Write((n^=1)>0?"\r--:--":"\r12:00");}}

```

Try it online!

This code has same length with the code above, it does replace previous line.

---

-7 bytes by using for loops.
-4 bytes by using ternary operator.
> 2 votes

# Answer
# Java, ~~152~~ 151 bytes (Thanks @AlexRacer)

```
public class c{public static void main(String[] a)throws Exception{int i=1;while(i>0){System.out.println(i++%2<1?"--:--":"12:00");Thread.sleep(500);}}}

```

Try it here! * (this compiler prints only once a second, couldn't find a better one)
> 1 votes

# Answer
## Haskell, 79 bytes

```
import System.Posix.Unistd
m=(>>usleep 500000).putStrLn
g=m"12:00">>m"--:--">>g

```

`m` is a helper function that waits half a second before printing its argument. The main function `g` calls `m "12:00"`, then `m "--:--"` and then itself again.
> 1 votes

# Answer
# S.I.L.O.S, 61 bytes

```
lbla
def p printLine
p 12:00
wait 500
p --:--
wait 500
GOTO a

```

Try it online!

Unfortunately TIO will just do nothing forever, as it waits until execution to print this. But, if you are eager to test, you can use the GitHub link.
> 1 votes

# Answer
## Arduino CC, 79 bytes

```
void loop(){Serial.print("12:00");delay(500);Serial.print("--:--");delay(500);}

```

I have no experience with C/C++, so I don't really know how I can golf this.
> 1 votes

# Answer
## Processing, 69 bytes

```
void draw(){println("12:00");delay(500);println("--:--");delay(500);}

```
> 1 votes

# Answer
# Python 2, 68 Bytes

```
import time
while 1:
 for i in'12:00','--:--':print i;time.sleep(.5)

```
> 1 votes

# Answer
# Dyalog APL, ~~35~~ ~~31~~ 30 bytes

Full program.

```
{⌽⍵⊣⎕←5↑⍵⊣⎕DL÷2}⍣≡'12:00--:--'

```

`'12:00--:--'` a string

`{`...`}⍣≡` Repeatedly apply the below anonymous function until two successive results are identical (i.e. never)

`÷2` reciprocal of two (one half)

`⎕DL` **D**e**l**ay that many seconds (returns elapsed time)

discard that in favor of

the argument

`5↑` take the first five characters

`⎕←` display with newline

discard that in favor of

`⌽⍵` reverse argument (implicitly returned)
> 1 votes

# Answer
# C, 77 bytes

```
#import<windows.h>
i;f(){for(;;i^=1)Sleep(83*printf(i?"\r--:--":"\r12:00"));}

```
> 1 votes

# Answer
## R  ~~69~~   ~~65~~  61 bytes

~~`y=1;while(1){cat('\r',c('12:00','--:--')[y]);Sys.sleep(.5);y=(y==1)+1}`~~

~~`while(1){cat('\r12:00');Sys.sleep(.5);cat('\r--:--');Sys.sleep(.5)}`~~

`f=Sys.sleep;while(1){cat('\r12:00');f(.5);cat('\r--:--');f(.5)}`

First time using the `f = blah_function()` trick, and it saved a few bytes. Used `\r` to replace existing string.

Fairly simple implementation:

```
f = Sys.sleep;      #store function for repeated usage
while(1){
    cat('\r12:00'); #print 12
    f(.5);          #sleep
    cat('\r--:--'); #print --
    f(.5)           #sleep again
}

```
> 1 votes

# Answer
# GameMaker Language, 47 bytes

```
a="12:00"if 9<c mod 20a="--:--"draw_text(0,0,a)

```

(Assuming a room speed of 20 fps)
> 1 votes

# Answer
# Scala, 100 bytes

```
object C extends App{var p=1>2;while(2>1){p= !p;println(if(p)"12:00"else"--:--");Thread.sleep(500)}}

```
> 1 votes

# Answer
# ForceLang, 79 bytes

```
def d datetime.wait 500
def w io.writeln
label 1
w "12:00"
d
w "--:--"
d
goto 1

```

---

And here's a version in 125 bytes that actually clears the screen each time and blinks:

```
set z string.char 8
def d datetime.wait 500
set z z+z+z+z+z
label 1
io.write "12:00"
d
io.write z+"--:--"
d
io.write z
goto 1

```
> 1 votes

# Answer
# tcl, 49

```
while 1 {lmap x 12:00\ --:-- {puts $x;after 500}}

```

Can be tried on https://goo.gl/8gXPzC

Thanks to people on tcl IRC channel.

~~tcl, 51
```
while 1 {puts 12:00;after 500;puts --:--;after 500}

```~~

~~Can be tried on https://goo.gl/Hb3sHq~~
> 1 votes

# Answer
## HTML + CSS, 147, 148 142 Bytes

```
*{font-family:Courier;left 0;background-color:white;position:absolute}@keyframes d{0%,49%{left:0}50%,to{left:-10em}}a{animation:d 1s infinite}
```

```
12:00<a>--:--
```

## Explanation:

Basically, this uses two HTML elements: A text node containing `12:00` and an `<a>` tag containing `--:--`.

The selector in the CSS applies to both elements, giving both absolute positioning `0` to the left. This allows both elements to overlap. Then, I gave both elements a monospace font, making each take up equal widths. Finally, I set the background color to white, making sure that the `<a>` tag hides the text it overlaps.

Then, I use an animation to move the `<a>` tag offscreen every .5 seconds. To do this, the animation lasts one second, and shows the tag for the first 49%, then hides it for the last 50%.

Oh - finally, `Courier` is shorter than `monospace`, saving 3 bytes, but it might not work in all browsers/operating systems.

### Update: +1 Byte

Turns out that Monaco isn't on everyone's computer. changed to using `Courier` instead at the expense of a byte.

### Update: -6 Bytes

Forgot to remove a bit of whitespace. Oops.

## Non minified code:

```
* {
  position: absolute;
  left: 0;
  font-family: Courier;
  background-color: white;
}
@keyframes d {
  0%, 49% {
    left: 0
  }
  50%, to {
    left: -10em
  }
}
a{animation: d 1s infinite}
```

```
12:00<a>--:--
```
> 1 votes

# Answer
# Excel VBA (Win, Excel 32 bit Only), 97 Bytes

**In a module:**

Because VBA's `Application.Wait()` method cannot handle input for time periods of less than one second, a declaration of the kernel32 `sleep` method is used for the 500 ms wait period.

```
Declare Sub Sleep Lib "kernel32" (ByVal s&)

```

*Note:* 64-bit versions of VBA (VB7) require a `PtrSafe` tag after the `Declare` tag~~, and changing the `ByVal s&` call to `ByVal s as LongPtr`~~.

**In the vbe immediates window:**

```
Do:DoEvents:?"12:00":Sleep 500:?"--:--":Sleep 500:Loop

```
> 1 votes

# Answer
# PHP, 48 bytes

```
for(;;usleep(5e5))echo($n^=1)?"
12:00":"
--:--";

```

Run with `-nr`.

Replace instead of multiple lines with `\r` instead of `\n` (+2 bytes):

```
for(;;usleep(5e5))echo($n^=1)?"\r12:00":"\r--:--";

```
> 1 votes

# Answer
# REXX, ~~60~~, 54 bytes

```
d.='--:--'
d.1='12:00'
a=1
do b=0
  sleep(.5)
  a=\a
  say d.a
  end

```

(Indented for readability)

Edit: Turns out that the most naïve solution is even shorter:

```
do b=0
say '12:00'
sleep(.5)
say '--:--'
sleep(.5)
end

```

Tested with Regina REXX interpreter; some older implementations may not have the `Delay` function at all, or it may only support whole seconds.
> 1 votes

# Answer
# \*\>\<\>, 30 bytes

```
cn"00:"ooo5Sdo"--:--"ooooo5Sdo

```

Online test.

I feel this is much simpler and more different than redstarcoder's algorithm, and thus I posted it as separate.

Replaces output in-place.
> 1 votes

# Answer
# Lua, 94 bytes

Unfortunately Lua has no built-in sleep function, so a loop is necessary.

```
x=1 z=os.clock while 1 do x=-x print(x<0 and"12:00"or"--:--") y=z()+.5 repeat until z()>y end

```

As a bonus, here's a Windows only one which is 109 bytes and which clears the screen each time:

```
x=1 z=os.clock while 1 do x=-x print(x<0 and"12:00"or"--:--") y=z()+.5 repeat until z()>y os.execute"cls"end

```
> 1 votes

# Answer
# Python 2, 92 bytes

```
import time
t=0
while 1:u=t%2;v='--'*u;w=1-u;print v+'12'*w+':'+v+'00'*w;t+=1;time.sleep(.5)

```

Try it online!

## Explanation

```
import time                                   Import the time module
t=0                                           Set a counter, 't', to 0
while 1:                                      Trigger an infinite loop
    u = t%2                                   Let 'u' be the remainder of t/2. This will alternate between 0 and 1
    w = 1 - u                                 Let 'w' be the opposite of u
    v = '--'*u                                Python lets the repetition of strings by multiplying them by an int. Here we are either mulitplying by 1 (no effect) or 0 (turns it to an empty string)
    print v + '12'*w + ':' + v + '00'*w       Concatonating 4 strings and printing them. We are using string multiplication again on the '12' and '00'
    t += 1                                    Increment the counter variable
    time.sleep(0.5)                           Wait half a second

```
> 1 votes

# Answer
# 8th, ~~62~~ ~~58~~ 51 bytes

```
: p . cr .5 sleep ; : f "12:00" p "--:--" p recurse ;

```

When invoked, the word `f` will display blinking twelve according the "new line" format. This code leverages "tail-call elimination" implemented in 8th.

The following code (95 bytes long) will let word `f` display blinking twelve according the "replacing the former string" format:

```
: p 0 0 con:gotoxy con:print ;
: f con:cls repeat "12:00" p .5 sleep "--:--" p .5 sleep again ;

```
> 1 votes

# Answer
# SmileBASIC, 35 bytes

```
WAIT 30?"12:00
WAIT 30?"--:--
EXEC.

```

`WAIT` times are in frames (1/60 second), and `EXEC.` restarts the program (equivilant to `EXEC 0` which runs the code that's in slot 0)

Version that clears the screen and adds 6 bytes:

```
WAIT 30CLS?"12:00
WAIT 30CLS?"--:--
EXEC.

```
> 1 votes

# Answer
## PKod, 26 bytes

PKod is an esoteric language that only has one accessible variable

**Code:**

```
l12=:o00yyl=-oo=:o=-ooyy<

Explanation:
l - if first char in code, print any NOP chars found
12 - two NOP chars to print
=: - set variable as :
00 - two more NOP chars
o - print variable's corresponding ascii char
y - wait 0.25 seconds
l - if not first char in code, clear the console
=-oo - set variable as - and print twice
< - go back to the start of the code

```
> 1 votes

# Answer
# 05AB1E, ~~23~~ ~~20~~ 19 bytes

```
"12:00"…--:û[s=₄;.W

```

Try it online.

**Explanation:**

```
"12:00"            # Push string "12:00"
       …--:        # Push string "--:"
           û       # Palindromize it to "--:--"
[                  # Loop indefinitely:
 s                 #  Swap the two values on the stack
  =                #  Print the top with trailing newline (without popping)
   ₄;              #  Push 1000 halved: 500
     .W            #  Sleep that many ms

```

`"12:00"` could alternatively be `Žmy3'::` for the same byte-count.
> 1 votes

# Answer
# C (clang), 51 bytes

```
f(i){puts(i?"12:00":"--:--");usleep(500000);f(!i);}

```

Try it online!
> 1 votes

# Answer
# Dart, 103 bytes

```
import'dart:io';f({i=1}){while(i>0){print(i++%2>0?"12:00":"--:--");sleep(Duration(milliseconds:500));}}

```

Try it online!

Sometimes I hate how verbose and strongly typed Dart has to be :D
> 1 votes

# Answer
# Japt, 27 bytes

```
500t@ßÃOq"12:00--:--"ò5 gT°

```

Try it

```
500t@ßÃ                         :Run the programme again in 500ms
       Oq                       :Clear the output
         "12:00--:--"ò5         :Split the string "12:00--:--" into chunks of length 5
                        gT°     :Get the element at index T (initially 0), postfix incremented

```
> 1 votes

# Answer
# GNU AWK, (until version 5.0.1), 64 bytes

This piece of code prints the strings on a new line. Only works in GNU AWK up to version 5.0.1, while the `time` extension (module) was not obsolete.

```
@load"time";BEGIN{for(;;){sleep(.5);print++t%2?"12:00":"--:--"}}

```

## Clearing the screen with `clear` command (80 bytes)

This example uses the `clear` command, not native to Awk.

```
@load"time";BEGIN{for(;;){sleep(.5);system("clear");print++t%2?"12:00":"--:--"}}

```

## Clearing the screen with `\33[H\33[2J\33[3J` (85 bytes)

But don't despair if there is no command to clear the screen on your system. Just hard code it. `\33` is the ASCII for Escape in octal.

```
@load"time";BEGIN{for(;;){sleep(.5);print"\33[H\33[2J\33[3J"(++t%2?"12:00":"--:--")}}

```
> 1 votes

# Answer
# QBasic, 51 bytes

```
LOCATE 1
IF TIMER*2MOD 2THEN?"12:00"ELSE?"--:--
RUN

```

Try it at Archive.org (but note that it's an infinite loop, so there's no way to exit the program besides closing/refreshing your browser).

Displays both strings on the top line of the screen. If you're using actual QBasic rather than QB64, you'll notice that the program doesn't clear the screen first, so there may be other junk present as well. This issue can be fixed at a cost of 8 bytes: add `CLS:DO:` at the beginning of the program and change `RUN` to `LOOP`.

### Explanation

Waiting for a fraction of a second is hard in QBasic, as other answers have mentioned, since the built-in `SLEEP` command only takes integers. However, `TIMER` (which represents the number of seconds since midnight) is a floating-point value. Whenever its fractional part is less than .5, we'll print `--:--`, and whenever its fractional part is greater than .5, we'll print `12:00`. Conveniently, the `MOD` operator truncates to integer, so we can use `TIMER * 2 MOD 2` and get values of `0` and `1`.

This approach prints many, many times per second, but most of the time it's printing the same value over itself, so nothing changes.

Ungolfed and commented:

```
LOCATE 1                  ' Move the cursor to the top row
IF TIMER * 2 MOD 2 THEN   ' Alternates between 0 and 1 with a period of 1 second
  PRINT "12:00"
ELSE
  PRINT "--:--"
END IF
RUN                       ' Restart the program

```
> 1 votes

# Answer
# Stax, ~~22~~ 20 bytes

```
å√Φ←mp═╠╗⌐fâêÇY)♀╗}%

```

Run and debug it
> 1 votes

# Answer
# 05AB1E, 19 bytes

```
…--:ûŽmy3'::[=s₄;.W

```

Try it online! Outputs each string on a new line.
> 1 votes

# Answer
## under construction, I missed the 1 second delay

## awk, ~~35~~34 bytes (+11 for `12:00 --:--`)

```
{for(;++i;i=i%2)print$(i)"\033[A"}

```

`for` loop alternates `i`'s value between 1 and 2. `echo` feeds the values to the program into fields `$1`and `$2`, we then `print $(i)`. Try it:

```
$ echo 12:00 --:-- | awk '{for(;++i;i=i%2)print$(i)"\033[A"}'

```

**Edit**: Thanks for the ANSI tip to @F.Hauri.
> 0 votes

# Answer
## C 79 Bytes

```
f(){while(1){printf("\n12:00");usleep(500000);printf("\n--:--");usleep(500000);}}

```

so the main would look like `int main(){ f(); return 0;}`
> 0 votes

# Answer
# Python 3, 78 bytes

```
import time;x=0
while 1:x=not x;print("12:00--:--"[x*5:x*5+5]);time.sleep(0.5)

```

Try it online!
> 0 votes

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


title: Squishy vectors

text:
# Question
Title: Squishy vectors
If we have a list of integers we can "squish" one of them by:

* decrementing it
* replacing adjacent values with its new value

For example in this list:

```
[1,2,8,3,6]

```

If we squish the `8` we get:

```
[1,7,7,7,6]

```

The question is:

**Given a starting array, what is the largest we can make its sum by repeatedly squishing values?**

For example if we are given:

```
[1,5,1,1,9,1]

```

Here the starting sum is `18` but if we squish the `5` or the `9` it will go up. Squishing anything else will make it go down so we will squish them.

```
[4,4,4,8,8,8]

```

Now the sum is `36`, but it can still go up, if we squish the left-most `8` it will increase to `37`.

```
[4,4,7,7,7,8]

```

We can squish the left-most `7` but it won't change the sum. If we go back and try some other things we will find that the best sum possible is in fact `37`.

So the answer here is `37`.

## Task

Given a list of two or more positive integers as input give the maximum sum that can be attained by repeated squishing.

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

## Test cases

```
[2,2,2] -> 6
[4,5] -> 9
[4,6] -> 10
[4,4,6] -> 14
[4,6,5] -> 15
[1,1,9] -> 21
[1,1,1,9] -> 25
[1,8,1,9,1] -> 38
[1,10] -> 18
[1,5,1,1,9,1] -> 37
[9,1,1,1] -> 25
[3,6,7,8,1] -> 31

```

# Answer
> 6 votes
# JavaScript (ES6),  ~~77~~  76 bytes

*Saved 1 byte thanks to @tsh*

```
f=(a,s=0)=>Math.max(...a.map((p,i)=>(s+=p,--p)&&f(a.map(q=>i*i--<2?p:q))),s)

```

Try it online! (some test cases removed)

Faster version with a cache (87 bytes, solving all test cases almost instantly)

### Commented

```
f = (                 // f is a recursive function taking:
  a,                  //   a[] = input array
  s = 0               //   s = sum of the array, computed in the main loop
) =>                  //
Math.max(             // return the maximum of ...
  ...a.map((p, i) =>  //   for each value p at position i in a[]:
    (                 //
      s += p,         //     update the sum
      --p             //     decrement p
    ) &&              //     if p is not equal to 0:
    f(                //       do a recursive call:
      a.map(q =>      //         pass a new array where the items a[i-1],
        i * i-- < 2 ? //         a[i] and a[i+1] are set to p and
          p           //         everything else is left unchanged
        :             //         we do this by testing i² < 2 and
          q           //         decrementing i after each iteration
      )               //
    )                 //       end of recursive call
  ),                  //   end of map()
  s                   //   add the sum of the current array
)                     // end of Math.max()

```

# Answer
> 6 votes
# MATL, ~~37~~ 35 bytes

```
ftnqZ^!"G@!"tt@)q@3:H-+GfX&(]]v!sX>

```

Brute force approach. It tries all possible sequences of up to *n*−1 squishes, where *n* is the length of the input. This is sufficient, because at that point all numbers will be equal and further squishing will decrease the sum.

Try it online! Or verify all test cases except the longest one.

### How it works

```
ftnqZ^     % Cartesian power of [1 2 ... n] with exponent n-1, where n is input length
!"         % For each Cartesian tuple
  G        %   Push input
  @!"      %   For each number k in the current tuple
    t      %     Duplicate the partially squished input array (*)
    t@)q   %     Push its k-th entry minus 1 (**)
    @3:H-+ %     Push [k-1 k k+1]
    GfX&   %     Intersection with [1 2 ... n]. This handles the edges (***)
    (      %     Write (**) at entries (***) of (*)
  ]        %   End
]          % End
v          % Vertically concatenate all partially (or totally) squished arrays
!s         % Sum of each array
X>         % Maximum. Implicit display

```

# Answer
> 5 votes
# 05AB1E, 20 bytes

```
ā<ZиæεvDyè<2Ý<y+ǝ]Oà

```

Brute-force approach, so pretty slow the larger the input-list is.

Try it online or verify the shortest few test cases.

**Explanation:**

```
ā                 # Push a list in the range [1,input-length]
 <                # Decrease each by 1 to make the range [0,length)
  Z               # Push the maximum/length-1 (without popping the list)
   и              # Repeat the list that many times
    æ             # Get the powerset of this list
     ε            # Map over each inner list:
      v           #  Foreach over each index `y`:
       D          #   Duplicate the current list
                  #   (which will be the implicit input in the first iteration)
        yè        #   Pop the copy, and get its `y`'th value
          <       #   Decrease it by 1
           2Ý     #   Push list [0,1,2]
             <    #   Decrease each to [-1,0,1]
              y+  #   Add `y` to each: [y-1,y,y+1]
                ǝ #   Insert the value-1 at these indices
                  #   (ignoring those that are out of bounds)
     ]            # Close both the inner loop and outer map
      O           # Sum each inner list
       à          # Pop and push the maximum
                  # (which is output implicitly as result)

```

`2Ý<y+` could alternatively be `y<y>Ÿ` or `y<DÌŸ` for the same byte-count.

# Answer
> 5 votes
# , ~~116~~ 103 bytes

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

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

```
function(v)max(combn(rep(0:l,l),l<-sum(v|1),function(x){for(i in x)if(i)v[i-1:-1]=v[i]-1;sum(v[1:l])}))

```

Try it online!

Explanation outline:

1. Generate all possible sequences of indices to squish (`0` indicating "skip") - of length equal to length of input; possibly with duplicates, which don't matter.
2. Use `combn`'s `FUN` to apply on each one the squishings in a `for` loop.
3. During squishing, luckily we need to account only for the overflowing indices on the right (writing to index `0` is a no-op), hence the indexing in `sum(v[1:l])`.
4. Take `max` of all of the possible sums.

# Answer
> 4 votes
# Jelly, 22 bytes

Yowch, it took quite some effort circumventing Jelly's, usually useful, modular indexing nature!

```
J;-ṗLị@’¥’r‘RƇƲ}¦ƒ€⁸§Ṁ

```

A monadic Link accepting a list of positive integers that yields the maximal sum reachable (only revisiting previously squashed indices if better for the golf).

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

### How?

```
J;-ṗLị@’¥’r‘RƇƲ}¦ƒ€⁸§Ṁ - Link: list of integers, A
J                      - range of length of A -> [1,2,...,length(A)]
  -                    - literal -1
 ;                     - concatenate -> [1,2,...,length(A),-1] -> our alphabet
    L                  - length of A
   ṗ                   - Cartesian power (all words of length length(A) with our alphabet)
                  €    - for each word
                   ⁸   - ...using A as the right argument:
                 ƒ     -   reduce [A]+word by:
                ¦      -     sparse application
               }       -     ...to indices: using the right argument (next integer of word):
              Ʋ        -       last four links as a monad - f(I=integer):
         ’             -         decrement I
           ‘           -         increment I
          r            -         inclusive range -> [I-1, I, I+1]
             Ƈ         -         filer keep those (of [I-1, I, I+1]) for which:
            R          -           range (truthy for positive integers)
        ¥              -     ...apply: last two links as a dyad - f(current state, I):
      @                -       with swapped arguments:
     ị                 -         index into -> our squish value
       ’               -       decrement
                    §  - sums
                     Ṁ - maximum

```

# Answer
> 3 votes
# Python 3, 105 bytes

```
f=lambda l,i=0:0<sum(l[i:])and max(f((l[:i][:-1]+[l[i]-1]*(3-(i<1))+l[i+2:])[:len(l)]),f(l,i+1))or sum(l)

```

Try it online!

The squishing is surprisingly annoying, due to one-off errors near the edges. Bruteforce solution, which stops only when non-positive numbers have been encountered.

The function calls itself two times. Once with the index `i` squished, and once with `i` incremented (but the list remains unsquished). The maximum of those calls are returned.

There are two edge cases, one is when `i` is outside the list, and another one when we feel enough squishing has been done. We can check for both cases with `0<sum(l[i:])`. When this becomes less than one it can be for two reasons. One is that `i` is equal to the length of the list, which means that the sum of the empty list is taken (which is zero). Another possibility is that the elements of `l` are so squished that some of them are zero or even negative. Clearly at this point we have done more than enough squishing and can stop.

# Python 3, 171 bytes

```
L={};g=lambda l,i:0<sum(l[i:])and max(f((l[:i][:-1]+[l[i]-1]*(3-(i<1))+l[i+2:])[:len(l)]),f(l,i+1))or sum(l)
def f(l,i=0):L[(i,*l)]=L.get((i,*l))or g(l,i);return L[(i,*l)]

```

Try it online!

Just a memoized version of the first submission. Is able to calculate all testcases in reasonable time.

# Answer
> 3 votes
# Python3, 505 bytes:

```
S=sum
M=max
def f(n):
 if any(i>1 for i in n):
  yield n;d={}
  for i in range(len(n)):
   if n[i]>1:
    k,j=n[:],0
    k[i]-=1
    if i:k[i-1]=k[i];j+=1
    if i+1<len(k):k[i+1]=k[i];j+=1
    d[j]=d.get(j,[])+[(n[i],k)]
  if 2 in d:
   T=[],[]
   for _,y in sorted(d[2],key=lambda x:x[0],reverse=True):
    T[S(y)>S(n)].append(y)
   for i in T[1]:yield from f(i)
   if T[0]:yield from f(M(T[0],key=S))
   if M([t for t,_ in d[2]])==M(n):return
  if 1 in d:
   yield from f(M(d[1],key=lambda x:x[0])[1])

```

Try it online!

A bit of optimization to produce all the test case results quickly.

---

# Python3, 392 bytes:

@AnttiP has very cleverly taken my original solution above and has condensed it down, and although slower due to its leveraging of speculative execution, it is much shorter:

```
S=sum
M=max
def f(n):
 if M(n)<2:return
 yield n;d,T=[[]]*3,[[],[]]
 for i in range(len(n)):
  k=n[:];j=i>0;k[i]-=1;k[i-j]=k[i]
  if k[i+1:]:k[i+1]=k[i];j+=1
  if n[i]>1:d[j]+=[(n[i],k)]
 for i in[T[S(y)>S(n)].append(y)for _,y in sorted(d[2])[::-1]]and T[1]:yield from f(i)
 if T[0]:yield from f(M(T[0],key=S))
 if d[2]and M([t for t,_ in d[2]])==M(n):return
 if d[1]:yield from f(M(d[1])[1])

```

Try it online!

# Answer
> 2 votes
# Charcoal, 47 bytes

```
Ｆ⊖ΦＥＸ⊕ＬθＬθ↨ι⊕Ｌθ⌊ι«≔⮌θηＦιＵＭη⎇‹¹↔⁻μκλ⊖§ηκ⊞υΣη»Ｉ⌈υ

```

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

```
Ｆ⊖ΦＥＸ⊕ＬθＬθ↨ι⊕Ｌθ⌊ι«

```

Generate all possible squishing sequences of length up to the length of the input.

```
≔⮌θη

```

Make a copy of the input.

```
ＦιＵＭη⎇‹¹↔⁻μκλ⊖§ηκ

```

Perform all of the squishing steps.

```
⊞υΣη

```

Save the sum of the result.

```
»Ｉ⌈υ

```

Output the maximum sum.

# Answer
> 2 votes
# Perl 5 List::Util, 112 bytes

```
sub f{my$s=sum@_;max$s,map f(@$_),grep{$s-2<sum@$_}map{@a=(0,@_,0);@a[$_..$_+2]=($_[$_]-1)x3;[@a[1..@_]]}0..$#_}

```

Try it online!

# Answer
> 2 votes
# Python 3.8 (pre-release), 103 bytes

Thanks to Kevin Cruijssen for -2 bytes!

it's not a lambda!

Pretty self-explanatory, pads with zero to avoid edge cases while copying x to y, squashes a digit in y by assignment, recurses if the digit is not less than 0. The sum is calculated on the input vector to each call and updated if any recursive call returns a larger result. This sum (`s`) is returned after trying all the digits.

```
def f(x):
 s=sum(y:=[0,*x,i:=0])
 for v in x:y[i:i+3]=[v-1]*3;s=max(s,v<0 or f(y[1:-1]));i+=1
 return s

```

Try it online!

# Answer
> 2 votes
# Brachylog, ~~40~~ ~~39~~ 33 bytes

*-1 thanks to Unrelated String; -6 thanks to Fatalize*

```
~b~k{{~c₃↺{Ṫ∋₁-₁ℕgj₃}ʰ↻c↰|}bk+}ᶠ⌉

```

Try it online!

Brute force solution. *V e r y s l o w*. For testing purposes, I suggest changing  to `ℕ₁`, which helps significantly (but still not enough to solve most of the test cases in less than 60 seconds).

### Explanation

This solution comes in layers, like an onion. Also like an onion, working on it made me want to cry.

```
~b              "Unbehead" the input list, prepending an uninitialized variable
  ~k            Do the same at the other end ("unknife")
    {...}ᶠ      Find all ways to satisfy this predicate (see next section)
          ⌉     Take the maximum

{...}           Apply this predicate (see next section)
     bk         Remove the first and last elements of the resulting list
       +        Sum

|               EITHER return the list unchanged, OR:
 ~c₃            Partition the list into three sublists
    ↺           Rotate so that the middle sublist is at the beginning
     {...}ʰ     Apply this predicate (see next section) to that sublist
           ↻    Rotate so that the middle sublist is back in the middle
            c   Concatenate back together
             ↰  Call the current predicate recursively on the result

Ṫ               The sublist must be a three-element list
 ∋₁             Get the element at index 1
   -₁           Subtract 1
     ℕ          Assert that this is a nonnegative integer
      g         Wrap it in a singleton list
       j₃       Join three copies of that list into a single 3-element list

```

# Answer
> 1 votes
# Python, 157 bytes

```
f=lambda l:max([f((l[:max(i-1,0)]+[v-1]*(3-(0==i%(len(l)-1)))+l[i+2:])*((i>0 and v>l[i-1]+1)or(i<len(l)-1 and v>l[i+1]+1)))for i,v in enumerate(l)]+[sum(l)])

```

Try it online!

Finds all the moves that would result in at least 1 element increasing value, then recursively tests those moves and returns the maximum value achieved or the original value.

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


# Question
Title: Acyclic orientations of an n-dimensional cube
The goal of this challenge is to check and extend the OEIS sequence A334248: Number of distinct acyclic orientations of the edges of an n-dimensional cube.

Take an n-dimensional cube (if n=1, this is a line; if n=2, a square; if n=3, a cube; if n=4, a hypercube/tesseract; etc), and give a direction to all of its edges so that no cycles are formed. The terms of the sequence are the number of (rotationally and reflectively) distinct orientations that can be obtained.

## Example

For n=2, there are 14 ways to assign directions to the edges of a square with no cycles formed:

However, only three of these are distinct if they are rotated and reflected:

So when n=2, the answer is 3.

---

The winner of this challenge will be the program that calculates the most terms when run on my computer (Ubuntu, 64GB RAM) in one hour. If there is a tie, the program that computes the terms in the shortest time will be the winner.

# Answer
# Wolfram Language (Mathematica), n = 4, \<1 second on my computer

```
(* Elements of the hyperoctahedral group,represented by matrices *)
HyperoctahedralGroup[n_] :=
  Join @@ Table[
    Permute[IdentityMatrix@n, perm]*sign, {perm,
     Permutations@Range@n}, {sign, Tuples[{1, -1}, n]}];

(* Action of group elements on a vertex of the hypercube,
where each vertex is represented by an integer from 1 to 2^n *)
ActOn[n_, g_, v_] :=
  FromDigits[(1 + (IntegerDigits[v - 1, 2, n]*2 - 1) . g)/2, 2] + 1;

(* Orbits of vertices under such action *)
Orbits[n_, g_] :=
  ConnectedComponents@Table[v <-> ActOn[n, g, v], {v, 2^n}];

(* Whether any orbit contains adjacent vertices *)
OrbitConatinsAdjacentVertices[edges_, orbits_] :=
  Or @@ Or @@@ Outer[SubsetQ, orbits, edges, 1];

(* Merging vertices in each orbit into a single vertex *)
MergeVertices[edges_, orbits_] :=
  Graph@DeleteDuplicates[
    Sort /@ (edges /. (Alternatives@##2 -> #1 & @@@ orbits))];

(* Number of acyclic orientations fixed by some group element *)
InvariantAcyclicOrientations[n_, edges_, g_] :=
  With[{orbits = Orbits[n, g]},
   If[OrbitConatinsAdjacentVertices[edges, orbits], 0,
    Abs[ChromaticPolynomial[MergeVertices[edges, orbits], -1]]]];

(* OEIS sequence A334248 *)
A334248[n_] :=
  With[{edges = List @@@ EdgeList@HypercubeGraph@n},
   Sum[InvariantAcyclicOrientations[n, edges, g], {g,
      HyperoctahedralGroup[n]}]/(2^n*n!)];

Do[Print[n -> A334248[n]], {n, 1, 4}]

```

Try it online!

Not really optimized. Takes less than 1 seconds on my computer to calculate the first four terms, but takes forever for the fifth term. It seems that Mathematica cannot compute the chromatic polynomial of `HypercubeGraph[5]` in a reasonable time.

Based on Peter Kagey's deleted answer (which did not consider rotations and reflections), and uses Burnside's lemma.
> 6 votes

---
Tags: combinatorics, fastest-code, counting
---


title: From code to golf (Robbers' thread)

text:
# Question
Title: From code to golf (Robbers' thread)
*This is a challenge, the cops' thread is here*

You can change the word `code` into `golf` by changing a letter at a time in four steps:

```
CODE
COLE
COLD
GOLD
GOLF

```

Today, we’ll be doing the same thing with programs.

Your challenge is to crack an answer on the cops' thread. Cops will create a series of programs in which the first prints `code`, the last prints `golf` and the rest print distinct English words such that each program can be derived from the previous by changing a single character of its code.

For example, if the program `abcde` outputs `code` in a certain language, and the program `abcdf` outputs `potato`, then changing that `e` to an `f` is a valid step.

And if the program `aqcdf` outputs `golf`, then `abcde` -\> `abcdf` -\> `aqcdf` is a valid chain in which you change a character twice.

The cops will only share the `code` program and the number of changes, your challenge is to figure out the rest. Once you discover their whole program chain, their answer is cracked.

Cops may output in any casing - `coDe`, `Code`, `CODe` etc.

The dictionary used is `/dict/words`, which I've put in a gist for convenience.

## Scoring

The user with the most cracks wins the cops challenge.

# Answer
# Vyxal, cracks emanresu A’s answer

```
«ƛ↔ƒ
`ƛ↔ƒ
`ƛ₅ƒ
`»₅ƒ

```

Try it Online!

Note: The final two characters in each line in the linked program is just so that each one can be ran alongside one another; they aren’t required for the individual programs.

The first change is changing the first character, which changes the compressed string into a dictionary compressed string. From this point on, because of the way that dictionary compression works in Vyxal, the final character in the string is ignored.

The next two changes are simply changing to the dictionary entry for `golf`. What’s convenient about using the dictionary is that most of it is made up of English words, so I didn’t have to worry much about how I changed those two characters, as long as I changed them to the correct characters.

I’m guessing the intended solution was probably more clever than just switching to dictionary compression, but I saw that the option was available and decided to take advantage of it.
> 3 votes

# Answer
# Python 2, cracks Fmbalbuena's cop in two steps, not including start and end

\[Start for reference\]

```
golf="code"
goof="cold"
print golf

```

Step 1

```
golf="code"
golf="cold"
print golf

```

Step 2

```
golf="code"
golf="gold"
print golf

```

\[End\]

```
golf="code"
golf="golf"
print golf

```
> 3 votes

# Answer
# Pari/GP, cracks alephalpha's answer

Well someone has to do it...

One step:remove the comma.

```
go="co";lf="de";print(go,lf)

go="co";lf="de";print(go lf)

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 2 steps, cracks alephalpha's second answer

first spacify the first comma to output gode

```
g=c;f=e;l=d;print(g o,l,f)

```

then the last for golf

```
g=c;f=e;l=d;print(g o,l f)

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), cracks @Arnauld's answer

Didn't include `~` in my search originally which meant I got it in 7 programs...

```
_=>(0x63044+185882).toString(36), // coda
_=>(0xd3044+185882).toString(36), // mice
_=>(0xd3044+~85882).toString(36), // gond
_=>(0xd3004+~85882).toString(36), // golf

```

Try it online!

Used this program combined with `grep`ing the dictionary to refine the results and then guesswork on which paths felt more likely to head towards `golf`!
> 2 votes

# Answer
# !@#$%^&\*()\_+, 3 steps, cracks @Fmbalbuena's answer

Using the list provided in the question:

* `3130<202(^+@)`: code
* `3138<202(^+@)`: cole
* `2138<202(^+@)`: cold
* `2138<242(^+@)`: gold
* `2338<242(^+@)`: golf
> 2 votes

# Answer
# Charcoal, Cracks @Neil's answer
> 1 votes

# Answer
# Python 3, cracks Fmbalbuena's answer

```
golf="code"
try:exec("print( golf )")
except:print("a")

```

```
golf="code"
try:exec("print( golf')")
except:print("a")

```

```
golf="code"
try:exec("print('golf')")
except:print("a")

```

Adding the first `'` causes the `exec` to error, which goes to the except and prints `a`. After that, you can add the second `'`, which changes the contents of the `exec` to `print('golf')`, which outputs the target.
> 1 votes

---
Tags: code-challenge, cops-and-robbers
---


title: Longest infinite loop in 5 states

text:
# Question
Title: Longest infinite loop in 5 states
## Challenge Statement

The goal of this challenge is to build the 5 state *Infinite Time Turing Machine* that takes the longest to halt. Since Infinite Time Turing Machines can run for infinite time your score will be a "transfinite ordinal".

That's the challenge statement, but if you don't what all this means or want to dig into the details the rest of this challenge is some definitions and an example to help you. If there is something you don't understand or that isn't explained feel free to leave a comment.

## Turing Machines

For clarity we will define the Turing machines as used for this problem. This is going to be rather formal. If you are familiar with Turing machines this is a *single-tape*, *binary* Turing machine, without an explicit halt state, and with the possibility of a *no shift* move. But for the sake of absolute clarity here is how we will define a classical Turing machine and its execution:

A Turing machine consists of a \\$3\\$-Tuple containing the following:

* \\$Q\\$: A finite non-empty set of states.
* \\$q\_s : Q\\$: The initial state.
* \\$\delta : Q\times \\{0,1\\} \nrightarrow Q\times \\{0,1\\}\times\\{1, 0, -1\\}\\$: A partial transition function, which maps a state and a binary symbol, to a state, a binary symbol and a direction (left, right or no movement).

During execution of a specific Turing machine the machine has a *condition* which is a \\$3\\$-Tuple of the following:

* \\$\xi\_\alpha : \mathbb{Z}\rightarrow \\{0,1\\}\\$: The *tape* represented by a function from an integer to a binary symbol.
* \\$k\_\alpha :\mathbb{Z}\\$: The location of the read head.
* \\$q\_\alpha : Q\\$: The current state.

For a Turing machine the *transition* function takes the condition of a machine at step \\$\alpha\\$ and tells us the state of the machine at step \\$\alpha + 1\\$. This is done using the transition function \\$\delta\\$. We call the function \\$\delta\\$ with the current state and the symbol under the read head:

\\$ \delta\left(q\_\alpha, \xi\_\alpha\left(k\_\alpha\right)\right) \\$

If this does not yield a result, then we consider the machine to have *halted* at step \\$\alpha\\$, and the condition remains the same. If it does yield a result \\$\left(q\_\delta, s\_\delta, m\_\delta\right)\\$ then the new state at \\$\alpha+1\\$ is as follows:

* \\$\xi\_{\alpha+1}(k) = \begin{cases}s\_\delta & k = k\_\alpha \\ \xi\_\alpha(k) & k \neq k\_\alpha\end{cases}\\$ (That is the tape replaces the symbol at the read head with the symbol given by \\$\delta\\$)
* \\$k\_{\alpha+1} = k\_\alpha+m\_\delta\\$ (That is the read head moves left right or not at all)
* \\$q\_{\alpha+1} = q\_\delta\\$ (That is the new state is the state given by \\$\delta\\$)

Additionally we define the condition of the machine at time \\$0\\$.

* \\$\xi\_0(k)=0\\$ (Tape is all zeros to start)
* \\$k\_0=0\\$ (Read head starts a zero)
* \\$q\_0=q\_s\\$ (Start in the initial state)

And thus by induction the state of a Turing machine is defined for all steps corresponding to a natural number.

## Infinite Ordinals

In this section I will introduce the concept of transfinite ordinals in a somewhat informal context. If you would like to look up a more formal definition this explanation is based of of the Von Neumann definition of ordinals.

In most contexts when talking about the order of events we use natural numbers. We can assign numbers to events such that events with smaller numbers happen earlier. However in this challenge we will care about events that happen after an infinite number of prior events, and for this natural numbers fail. So we will introduce *infinite ordinals*.

To do this we will use a special function \\$g\\$. The \\$g\\$ function takes a set of numbers and gives us the smallest number greater than all the numbers in that set. For a finite set of natural numbers this is just the maximum plus 1. However this function is not defined on natural numbers alone. For example what is \\$g(\mathbb{N})\\$, or the smallest number greater than all naturals. To create our ordinals we say

* \\$0\\$ exists and is an ordinal.
* If \\$X\\$ is a set of ordinals then \\$g(X)\\$ exists and is an ordinal.

This gives us the natural numbers (e.g. \\$1 = g(\\{0\\})\\$, \\$2 = g(\\{1\\})\\$ etc.) but also gives us numbers beyond that. For example \\$g(\mathbb{N})\\$, this is the smallest infinite ordinal, and we will call it \\$\omega\\$ for short. And there are ordinals after it, for example \\$g(\\{\omega\\})\\$ which we will call \\$\omega + 1\\$.

We will in general use some math symbols \\$+\\$, \\$\times\\$ etc. in ways that are not defined explicitly. There are precise rules about these operators, but we will just use them as special notation without definition. Hopefully their use should be clear though. Here are a few specific ordinals to help you out:

\\$ \begin{eqnarray} \omega\times 2 &=& \omega+\omega &=& g(\\{\omega + x : x\in \mathbb{N}\\})\\ \omega^2 &=& \omega\times\omega &=& g(\\{\omega \times x + y : x\in \mathbb{N}, y\in \mathbb{N}\\})\\ \omega^3 &=& \omega\times\omega\times\omega &=& g(\\{\omega^2\times x+\omega\times y + z : x\in \mathbb{N}, y\in \mathbb{N}, z\in \mathbb{N}\\})\\ \omega^\omega &=& & & g(\\{\omega^x\times y + z : x\in \mathbb{N}, y\in \mathbb{N}, z \< \omega^x\\})\\ \end{eqnarray} \\$

If an ordinal is not the successor of another ordinal, meaning there is not a next smaller ordinal, we call that ordinal a *limit ordinal*. For example \\$\omega\\$, \\$\omega\times3\\$, and \\$\omega^{\omega\times 2}+\omega^6\times 4\\$ are all limit ordinals. \\$3\\$, \\$\omega\times 5 + 12\\$ and \\$\omega^{\omega^\omega}+1\\$ are not. Some authors will specify further that 0 is not a limit ordinal, we will be explicit about 0 when we talk about limit ordinals to avoid confusion.

## Infinite Time Turing Machines

A classical Turing machine is equipped with a start status, and a way to get from one status to another. This allows you to determine the status of the machine at any finite step.

Infinite time Turing machines extend classical Turing machines to have a defined status non-zero *limit ordinals* as well. That is ordinals as defined above which are not the successor of any previous ordinal. This addition makes the condition of the machine defined at transfinite time as well.

### Formal definition

For this we add an additional object to the machine's definition

* \\$q\_l : Q\\$: The limit state

And we define the condition of the machine at some limit ordinal \\$\lambda\\$ to be

* \\$\xi\_\lambda(k) = \limsup\_{n\rightarrow \lambda} \xi\_n(k)\\$
* \\$k\_n = 0\\$
* \\$q\_n = q\_l\\$

\\$\\$

# Example

Here we have a diagram of a long running 2-state machine:

If we want to calculate how long this takes to halt we can't just throw it into a computer and run it, rather we have to determine it by hand.

To start we follow the machine through it's normal execution. It starts at \\$q\_1\\$ and we can see that from there it *always* moves to \\$q\_2\\$ flipping the cell under the read-write head. So here it turns the cell on. Then since the cell is on it will transition back to \\$q\_1\\$, turning the cell off and moving to the right. This puts us in the exact same condition as the start, except the read-write head has advanced by 1. So it will continue in this loop of flipping on bit on and off and moving to the right endlessly.

Now that we have determined the behavior of the machine for all finite steps we can figure out the state at step \\$\omega\\$. Each cell is on for at most 1 step, before being turned off, and then it is never on again. So the limit supremum of each cell is \\$0\\$, and at step \\$\omega\\$ the tape is entirely empty.

So this means that after \\$\omega\\$ the machine just repeats its exact behavior, the condition at step \\$\omega+n\\$ is the same as the condition at step \\$n\\$. And this persists even after we hit another limit ordinal, \\$\omega+\omega\\$, the tape remains blank and just repeats the same behavior over and over.

So we now have an accurate description of the machine for states of the form \\$\omega\times n + m\\$, and it doesn't halt for any of those steps. It just repeats the same infinite pattern an infinite number of times. So now we can look at the step after all the steps we have described. We take the next limit ordinal:

\\$ g(\\{\omega\times n + m : n\in \mathbb{N}, m \in \mathbb{N}\\}) = \omega\times\omega = \omega^2 \\$

Your first instinct might be that the tape will be completely empty again, since it was empty at every step \\$\omega\times n\\$. However with infinities instincts can be misleading, so we should look at the definitions carefully instead.

In order for a cell to be zero it must converge to zero. Since the only possibilities are zero and one, this means that for each cell there must be some step \\$x\\$ after which that cell is always zero. Previously since each cell was only turned on once that step was just the step after it was turned off.

Now if such a step were to exist for a cell \\$k\\$ it would be of the form \\$\omega\times n + m\\$, however we know that the cell will be turned on again some time during the \\$\omega\times(n+1)\\$ iteration. In fact it will be turned on at exactly step \\$\omega\times(n+1) + 2k + 1\\$.

So no cell (with a non-negative index) will converge to a stable value. Meaning that by the limit supremum all non-negative cells will be on at time \\$\omega^2\\$.

So here we finally get some new behavior. With cell 0 on, the machine transitions to \\$q\_2\\$ turning the cell off, and since \\$q\_2\\$ doesn't have a transition for off cells the machine halts.

This gives us a total of \\$\omega^2+1\\$ steps until halting.

# Answer
# 5 states, \\$\omega^{\omega\cdot2}+\omega\cdot2+1\\$

| State | Tape | Next State | Write | Move |
| --- | --- | --- | --- | --- |
| Init | 0 | Lseek | 1 | Left |
| Init | 1 | Rtest | 0 | Left |
| Lseek | 0 | Rseek | 1 | No |
| Lseek | 1 | Lseek | 1 | Left |
| Rtest | 0 | Halt | - | - |
| Rtest | 1 | Rseek | 0 | Right |
| Rseek | 0 | Lclear | 1 | No |
| Rseek | 1 | Rseek | 0 | Right |
| Lclear | - | Lclear | 0 | Left |

# Visualization

```
# 0
      |
...00000000...
      ▲ Init
...00010000...
     ▲ Lseek
...00110000...
     ▲ Rseek
...00010000...
      ▲ Rseek
...00000000...
       ▲ Rseek
...00001000...
       ▲ Lclear
...00000000...
      ▲ Lclear
.
.
.
# omega
      |
...00000000...
      ▲ Init
.
.
.
# omega*2
      |
...00000000...
      ▲ Init
.
.
.
# omega^2
      |
...00111000...
      ▲ Init
...00101000...
       ▲ Rtest
...00100000...
        ▲ Rseek
...00100100...
        ▲ Lclear
...00100000...
       ▲ Lclear
...00100000...
      ▲ Lclear
...00100000...
     ▲ Lclear
...00000000...
    ▲ Lclear
.
.
.
# omega^3
      |
...00111100...
      ▲ Init
.
.
.
# omega^4
      |
...00111110...
      ▲ Init
.
.
.
# omega^omega
      |
...00111111...
      ▲ Init
...00101111...
       ▲ Rtest
...00100111...
        ▲ Rseek
.
.
.
# omega^omega+omega
      |
...00100000...
      ▲ Init
...00110000...
     ▲ Lseek
...00110000...
    ▲ Lseek
...01110000...
    ▲ Rseek
...00110000...
     ▲ Rseek
...00010000...
      ▲ Rseek
...00000000...
       ▲ Rseek
...00001000...
       ▲ Lclear
...00000000...
      ▲ Lclear
.
.
.
# omega^omega*omega == omega^(omega+1)
       |
...001111111...
       ▲ Init
...001101111...
        ▲ Rtest
.
.
.
# omega^(omega+1) + omega
       |
...001100000...
       ▲ Init
.
.
.
# omega^(omega*2)
       |
...111111111...
       ▲ Init
.
.
.
# omega^(omega*2) + omega
       |
...111100000...
       ▲ Init
...111110000...
      ▲ Lseek
...111110000...
     ▲ Lseek
.
.
.
# omega^(omega*2)+ omega*2
       |
...111110000...
       ▲ Init
...111100000...
        ▲ Rtest
HALT

```

# 4 states, \\$\omega^\omega+\omega+1\\$

| State | Tape | Next State | Write | Move |
| --- | --- | --- | --- | --- |
| Init | 0 | Ltest | 1 | Left |
| Init | 1 | Rseek | 0 | Left |
| Ltest | 0 | Rseek | 1 | Right |
| Ltest | 1 | Halt | - | - |
| Rseek | 0 | Lclear | 1 | No |
| Rseek | 1 | Rseek | 0 | Right |
| Lclear | - | Lclear | 0 | Left |

## Visualization

```
      |
...00000000...
      ▲ Init
...00010000...
     ▲ Ltest
...00110000...
      ▲ Rseek
...00100000...
       ▲ Rseek
...00101000...
       ▲ Lclear
...00100000...
      ▲ Lclear
...00100000...
     ▲ Lclear
...00000000...
    ▲ Lclear
.
.
.
# Omega
      |
...00000000...
      ▲ Init
.
.
.
# Omega*2
      |
...00000000...
      ▲ Init
.
.
.
# Omega*Omega
      |
...00111000...
      ▲ Init
...00101000...
       ▲ Rseek
...00100000...
        ▲ Rseek
...00100100...
        ▲ Lclear
...00100000...
       ▲ Lclear
...00100000...
      ▲ Lclear
...00100000...
     ▲ Lclear
...00000000...
    ▲ Lclear
.
.
.
# Omega*Omega + Omega
      |
...00000000...
      ▲ Init
.
.
.
# Omega*Omega*2
      |
...00111000...
      ▲ Init
.
.
.
# Omega*Omega*3
      |
...00111000...
      ▲ Init
.
.
.
# Omega*Omega*Omega
      |
...00111100...
      ▲ Init
...00101100...
       ▲ Rseek
...00100100...
        ▲ Rseek
...00100000...
         ▲ Rseek
...00100010...
         ▲ Lclear
...00100000...
        ▲ Lclear
...00100000...
       ▲ Lclear
...00100000...
      ▲ Lclear
...00100000...
     ▲ Lclear
...00000000...
    ▲ Lclear
.
.
.
# Omega^Omega
      |
...00111111...
      ▲ Init
...00101111...
       ▲ Rseek
...00100111...
        ▲ Rseek
...00100011...
         ▲ Rseek
...00100001...
          ▲ Rseek
.
.
.
# Omega^Omega + Omega
      |
...00100000...
      ▲ Init
...00100000...
     ▲ Ltest
HALT

```
> 9 votes

---
Tags: code-challenge, busy-beaver
---