# Question
Title: Number of tilings on a triangular board with triangular tiles
## Background

Consider the shape \\$T(n)\\$ consisting of a triangular array of \\$\frac{n(n+1)}{2}\\$ unit regular hexagons:

John Conway proved that \\$n = 12k + 0,2,9,11\\$ if and only if \\$T(n)\\$ can be tiled (i.e. exactly covered without overlapping) with \\$T(2)\\$. At the same time, he also proved that no coloring argument could prove the fact. (Yes, this is yet another Conway challenge.)

## Challenge

Let's define \\$a\_n\\$ as the number of distinct tilings of \\$T(n)\\$ by \\$T(2)\\$. Compute as many terms of \\$a\_n\\$ as possible in 10 minutes.

Reflection and/or rotation of a tiling is considered distinct from itself, unless the two are identical.

The program that prints the largest number of terms wins. In case of tie, the one that prints the last term in shorter time wins.

I have a Windows 10 machine with `Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz` and 32GB RAM, with Ubuntu 18.04 installed in WSL. Please include the instructions to run your code and where it works (Windows or Linux).

## Output format (with test cases)

The submission should print the results infinitely for each \\$n\\$ starting from 0. Each line should include the values of \\$n\\$ and \\$a\_n\\$. Here is first 21 lines of the expected output:

```
0 1
1 0
2 1
3 0
4 0
5 0
6 0
7 0
8 0
9 2
10 0
11 8
12 12
13 0
14 72
15 0
16 0
17 0
18 0
19 0
20 0
21 185328
22 0
23 4736520
24 21617456
25 0
26 912370744
27 0
28 0
29 0
30 0
31 0
32 0

```

Test cases for \\$n \le 20\\$ are generated using a naive Python 3 program. \\$a\_{21}\\$ through \\$a\_{32}\\$ (meaningful highest being \\$a\_{26}\\$) were found using Arnauld's JS submission.

Notably, neither the full sequence `1, 0, 1, 0, 0, 0, ...` nor the stripped-down one `1, 1, 2, 8, 12, 72, ...` is on OEIS yet. ~~As I don't have an OEIS account, I will let anyone interested to post this sequence (both versions) to OEIS (please leave a comment before you do).~~ The sequence of nonzero indices is A072065. **Edit:** The sequence is on A334875, thanks to Lyxal.

## Leaderboard

1. Rust with `rustc -O` by Anders Kaseorg, **Score 44** at **45s**
2. C++ with `g++ -O3` by l4m2, **Score 35** at **7min**
3. Javascript with `node` by Arnauld, **Score 32** at **1.8s**

## Pending

* (none)

# Answer
> 8 votes
# JavaScript (Node.js), N =  ~~22 25~~  32 in ~2 seconds

A recursive search using bit masks and a cache to keep track of patterns whose result is already known.

It doesn't make much sense to try go further in Node. Using a binary matrix is significantly slower and BigInts are even slower. It should rather be ported to a language natively supporting 64-bit integers.

```
'use strict';

let ts = new Date;

for(let n = 0; n <= 32; n++) {
  console.log(
    n.toString().padStart(2) + ' ' +
    solve(n).toString().padStart(10) + ' ' +
    '(' + ((new Date - ts) / 1000).toFixed(2) + ')'
  );
}

function solve(n) {
  // trivial cases
  if(![0, 2, 9, 11].includes(n % 12)) {
    return 0;
  }
  if(n == 0) {
    return 1;
  }

  // We work on a triangle stored as an array of bit masks:
  //   8 7 6 5 4 3 2 1 0 |
  //  -------------------+---  With this format, the tribones
  //   . . . . . . . . A | 0   are turned into the following
  //   . . . . . . . A A | 1   trominos:
  //   . . . . . . B B C | 2
  //   . . . . . D B C C | 3    X O    and    . X
  //   . . . . D D E E F | 4    O .           O O
  //   . . . G H H E F F | 5
  //   . . G G H I I J J | 6   where 'X' is the arbitrary anchor
  //   . K L L M I N J O | 7   point used in this code
  //   K K L M M N N O O | 8
  let a = Array(n).fill(0),
      cache = a.map(_ => new Object);

  // recursive search, starting at (x, y) = (0, 0)
  return (function search(x, y) {
    // if we've reached the last row, make sure it's complete
    if(y == n - 1) {
      if(a[y] == (1 << n) - 1) {
        return 1;
      }
      return 0;
    }

    // if we are beyond the last column, go on with the next row
    if(x < 0) {
      y++;

      // either return the result from the cache right away
      if(cache[y][a[y]] !== undefined) {
        return cache[y][a[y]];
      }
      // or do a full search
      return cache[y][a[y]] = search(y, y);
    }

    // if (x, y) is already set, advance to the next column
    if(a[y] >> x & 1) {
      return search(x - 1, y);
    }

    let res = 0;

    // try to insert X O
    //               O .
    if(x && !(a[y] >> x - 1 & 1)) {
      a[y] ^= 3 << x - 1;
      a[y + 1] ^= 1 << x;
      res += search(x - 2, y);
      a[y] ^= 3 << x - 1;
      a[y + 1] ^= 1 << x;
    }

    // try to insert . X
    //               O O
    if(!(a[y + 1] >> x + 1 & 1)) {
      a[y] ^= 1 << x;
      a[y + 1] ^= 3 << x;
      res += search(x - 1, y);
      a[y] ^= 1 << x;
      a[y + 1] ^= 3 << x;
    }

    return res;
  })(0, 0);
}

```

Try it online!

### Output

```
 0          1 (0.00)
 1          0 (0.00)
 2          1 (0.00)
 3          0 (0.00)
 4          0 (0.00)
 5          0 (0.00)
 6          0 (0.00)
 7          0 (0.00)
 8          0 (0.00)
 9          2 (0.00)
10          0 (0.00)
11          8 (0.00)
12         12 (0.01)
13          0 (0.01)
14         72 (0.01)
15          0 (0.01)
16          0 (0.01)
17          0 (0.01)
18          0 (0.01)
19          0 (0.01)
20          0 (0.01)
21     185328 (0.05)
22          0 (0.05)
23    4736520 (0.24)
24   21617456 (0.60)
25          0 (0.60)
26  912370744 (2.18)
27          0 (2.18)
28          0 (2.18)
29          0 (2.18)
30          0 (2.18)
31          0 (2.18)
32          0 (2.18)

```

# Answer
> 7 votes
# Rust, \\$n \le 44\\$ in 42 seconds

Build with `rustc -O`. Uses about 800 MiB of memory for \\$n = 38\\$, and \\$39 \le n \le 44\\$ are trivial. \\$n = 45\\$ will almost definitely run out of both time and memory on any reasonable system.

It works by dynamic programming where the states are the presence or absence of hexagons at \\$(k - 1, 1), \dotsc, (k - 1, i), (k, i + 1), \dotsc, (k, k)\\$; we advance \\$i\\$ to \\$i + 1\\$ by considering the addition of tribone \\$(k, i + 1), (k - 1, i), (k - 1, i + 1)\\$ or \\$(k, i + 1), (k - 1, i + 1), (k, i + 2)\\$.

```
use std::iter::Peekable;
use std::mem;

struct Merge<Xs: Iterator, Ys: Iterator>(Peekable<Xs>, Peekable<Ys>);

impl<Xs: Iterator<Item = (u64, u128)>, Ys: Iterator<Item = (u64, u128)>> Iterator
    for Merge<Xs, Ys>
{
    type Item = (u64, u128);
    fn next(&mut self) -> Option<(u64, u128)> {
        if let Some(x) = self.0.peek() {
            if let Some(y) = self.1.peek() {
                if x.0 < y.0 {
                    self.0.next()
                } else if x.0 > y.0 {
                    self.1.next()
                } else {
                    let x = self.0.next().unwrap();
                    let y = self.1.next().unwrap();
                    Some((x.0, x.1 + y.1))
                }
            } else {
                self.0.next()
            }
        } else {
            self.1.next()
        }
    }
}

fn main() {
    for n in 0..63 {
        if 0xa05 & 1 << n % 12 == 0 {
            println!("{} 0", n);
        } else {
            let mut count: Vec<(u64, u128)> = vec![(!(!0 << n) << 1, 1)];
            let mut count1 = vec![];

            for k in (1..n + 1).rev() {
                for i in 0..k - 1 {
                    count1.extend(Merge(
                        Merge(
                            count
                                .iter()
                                .filter(|&&(b, _)| !b & 3 << i == 0)
                                .map(|&(b, c)| (b & !(3 << i), c))
                                .peekable(),
                            count
                                .iter()
                                .filter(|&&(b, _)| !b & 6 << i == 0)
                                .map(|&(b, c)| (b & !(6 << i), c))
                                .peekable(),
                        )
                        .peekable(),
                        count
                            .iter()
                            .filter(|&&(b, _)| b & 2 << i == 0)
                            .map(|&(b, c)| (b | 2 << i, c))
                            .peekable(),
                    ));
                    mem::swap(&mut count, &mut count1);
                    count1.clear();
                    if i == 1 {
                        count.retain(|&(b, _)| b & 6 != 2);
                    }
                }
                count.retain(|&(b, _)| b & 1 << k == 0);
            }
            assert_eq!(count.len(), 1);
            assert_eq!(count[0].0, 0);
            println!("{} {}", n, count[0].1);
        }
    }
}

```

Try it online!

(TIO times out after \\$n = 37\\$.)

### Output

```
0 1
1 0
2 1
3 0
4 0
5 0
6 0
7 0
8 0
9 2
10 0
11 8
12 12
13 0
14 72
15 0
16 0
17 0
18 0
19 0
20 0
21 185328
22 0
23 4736520
24 21617456
25 0
26 912370744
27 0
28 0
29 0
30 0
31 0
32 0
33 3688972842502560
34 0
35 717591590174000896
36 9771553571471569856
37 0
38 3177501183165726091520
39 0
40 0
41 0
42 0
43 0
44 0

```

# Answer
> 1 votes
# \\$T(33) = 3688972842502560 \\$

```
> 1 0
> 2 1
> 3 0
> 4 0
> 5 0
> 6 0
> 7 0
> 8 0
> 9 2
> 10 0
> 11 8
> 12 12
> 13 0
> 14 72
> 15 0
> 16 0
> 17 0
> 18 0
> 19 0
> 20 0
> 21 185328
> 22 0
> 23 4736520
> 24 21617456
> 25 0
> 26 912370744
> 27 0
> 28 0
> 29 0
> 30 0
> 31 0
> 32 0
> 33 3688972842502560

Process returned 0 (0x0)   execution time : 71.730 s
Press any key to continue.

```

Code

```
#include <map>
#include <stdio.h>
#include <algorithm>
const int N = 33;
typedef unsigned long long ulong;

#define long ulong

std::map<ulong, long> A, B;
int i; long base;
template<bool last = false>
void bitfsh(ulong j, ulong d) {
    if (!j) {
        if(!last || d==0) B[d] += base;
        return;
    }
    int p = sizeof(ulong)*8-1-__builtin_clzll(j);
    if (d & 2ULL<<p) {
        bitfsh<last> (j ^ 1ULL<<p, d ^ 3ULL<<p);
    }
    if (p && (j & 1ULL<<p-1)) {
        bitfsh<last> (j ^ 3ULL<<p-1, d ^ 1ULL<<p);
    }
}
template<bool last = false>
long run() {
    B.clear();
    for (auto p=A.begin(); p!=A.end(); ++p) {
        ulong j = (*p).first;
        if (j%65536==0) fprintf(stderr, "%d %lld\r", i, j);
        base = (*p).second;
        if(base) bitfsh<last> (j, (1ULL<<i)-1);
    }
    std::swap (A, B);
    fprintf(stderr, "%60c\r", ' ');
    return A[0];
}
const ulong fs = sizeof(long) << N-1;
int main() {
    A[0] = 1;
    for (i=1; i<N; ++i) {
        //fprintf(stderr, "%d\n", i);
        printf ("> %d %llu\n", i, run ());
    }
    printf ("> %d %llu\n", i, run<true> ());
    exit(0);
}

```

# T(45) = 1.9935928828199593078904655e+31

Ran in 31953.963 s on my computer(including state backups), and use approximately 4.5GB disk.

Use @Anders Kaseorg 's solution but with disk as storage. For each \\$k,i\\$ amounts of items can be found here. TIO

---
Tags: sequence, fastest-code, hexagonal-grid, tiling
---


title: Shuffle string of digits

text:
# Question
Title: Shuffle string of digits
## Challenge

You have been given a string of digits 0-9.1 Your task is to shuffle this string, but every index must have a different value than it did before the string was shuffled.

For example:

```
In : 287492
Out: 892247

```

If this is not possible, return `false` or something similar. (`null`, `undefined`, etc.)

```
In : 131
Out: false

```

There is no upper bound on the length of the string, but you can assume you have unlimited computation time.

Your function must pass the following tests:

```
shuffle('2')                   => false
shuffle('88')                  => false
shuffle('794588888')           => false
shuffle('344999')              => for example, '999434'
shuffle('172830560542976539')  => for example, '271038650425697395'

```

**Shortest code wins, and good luck!**

---

1 More specifically, the string would match `/^[0-9]+$/`.

# Answer
# Jelly, 6 bytes

```
Œ!nẠ¥Ƈ

```

**Try it online!**
> 2 votes

# Answer
# K (ngn/k), ~~37~~ 32 bytes

```
{$[|/x=r:x[,/|2 0N#<x]@<<x;0;r]}

```

Try it online!

`{` `}` function with argument `x`

`$[` `;` `;` `]` if-then-else

`<x` "grade" - the sorting permutation for `x`

`<<x` "rankings" - the inverse of the sorting permutation

`2 0N#` split in two halves (or when length is odd - only approximately)

`|` swap the halves

`,/` concatenate

`x[` `]` use as indices in `x`

..`@<<x` use `<<x` as indices in the previous result (`a@b` is alternative syntax for `a[b]`)

`r:` assign to `r` \- the potential result

`x=r` boolean list of which elements of `x` are equal to their counterparts in `r`

`|/` or-reduction, i.e. "any?"
> 6 votes

# Answer
# 05AB1E, 7 bytes

Like the Pyth answer, outputs all possible shuffled strings or digits.

```
œʒø€Ëà_

```

Try it online!

## Explanation

```
œ       Permutations of the input
 ʒ      Filter such that:
  ø        Zipping with the original input
   €Ë      And comparing at corresponding indices
     à_    are all unequal.

```
> 6 votes

# Answer
# Pyth, 9 bytes

```
f.AnVQT.p

```

Try it online!

Outputs all possible strings that meet the criteria given in the question. This results in an empty list for the `false` cases.
> 3 votes

# Answer
# Pyth, 7 bytes

```
-VI#Q.p

```

Try it online!

Takes input as a list of digit-characters. For example:

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

```

Output: all possible derangements, with multiplicity for related characters.

* `.p`: Generate all permutations.
* `#`: Filter on
* `I`: Invariant under
* `-V ... Q`: Removing all characters that are at the same position in the input.
> 3 votes

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

```
e=>[...Array(i=2+e|0)].every(_=>(s=[...q=(--i+'').slice(1)]).some((_,j)=>_==e[j])|s.sort()+''!=[...e].sort()||console.log(q))

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~83~~ 80 bytes

```
lambda l:[p for p in permutations(l)if all(map(cmp,l,p))]
from itertools import*

```

Try it online!

Goes through all permutation of the string, and keeps the ones that are different to the original string at every index.
> 1 votes

# Answer
# PHP, ~~152~~ 141 bytes

```
$a=count_chars($s=$argn,1);rsort($a);$a[0]*2<=strlen($s)?:die;for($s=$t=str_split($s);$s!=array_diff_assoc($s,$t);)shuffle($t);echo join($t);

```

Try it online!

A bit lengthy but it's my first approach, will think more about it later

* displays empty string (exits) if impossible (if the most frequent number occurence is more than half of length of the string)
* uses an array approach and shuffles until it finds a proper result

EDIT: fixed an error in string length var attribution (missing brackets) + improved `while` condition for +1 byte

EDIT2: saved 1 byte, since brackets were mandatory for ternary condition, an `if` is now shorter

EDIT3: saved 11 bytes with the help of this answer by Titus to a closely related question
> 1 votes

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

```
e=>{for(b=a=e.slice().sort(),a=+a.join(""),b=+b.reverse().join("");a<=b;){if(k=(a+"").split("").map(a=>+a),b==k.slice().sort((a,e)=>e-a).join("")&&e.every((a,e)=>a!=+k[e]))return a;a++}}

```

Try it online!

-8 bytes thanks VFDan

# JavaScript (Node.js), 179 bytes

```
e=>{for(b=a=e.slice().sort(),a=+a.join``,b=+b.reverse().join``;a<=b;){if(k=(a+"").split``.map(a=>+a),b==k.slice().sort((a,e)=>e-a).join``&&e.every((a,e)=>a!=+k[e]))return a;a++}}

```

Try it online!
> 1 votes

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


title: Knights and Knaves and Codes

text:
# Question
Title: Knights and Knaves and Codes
In this challenge, your bot has landed on an island with the stereotypical knights and knaves. Knights always tell the truth, and knaves always lie. The objective is to find the correct 32 digit hexadecimal string before anyone else, by asking knights and knaves and trying to trick other bots into giving you answers or accepting fake ones.

## Knights and Knaves

Every bot will be given an array of 48 people, who are the same for all bots. The bots do not know whether any one person is a knight or knave. Each person is assigned two characters of the 32 digit string. Exactly half of all people are knights, and half are knaves: a knight will always give you the correct characters and their indexes within the result string; a knave, however, will give an incorrect character each time along with the correct index. These incorrect characters will always be the same for any one bot, so a knave is indistinguishable from a knight without outside help or some deductive skills. Every character of the string is known by exactly three people, and no person has the same character twice.

## Interacting

In order to find knaves, bots can interact with one another. One bot will request help from another for a specific character of the string, and the second bot can return any character. It is up to the first bot to decide if this character is real or fake, likely by asking for more help and comparing the results.

In order to prevent help-vampire bots, no bot can have more outgoing help requests than twice the number of incoming requests it has answered, plus four.

## Bots

Every bot is assigned a random Unique ID (UID) number each round. This number is used to communicate with other bots, and ranges from 0 to one less than the number of bots. It can request help from another bot using the function `sendRequest(uid, index)`, and read from responses with `readResponses()`, which is formatted as an array/list of objects containing `uid`, `index`, and `char` properties.

Additionally, a bot can view the requests sent to it using `viewRequests()`. Each request is an object containing two properties: `index`, and `uid`. To reply to a request, use the function `replyRequest(uid, index, char)`. There must be a request in `viewRequests()` from that UID asking about the index specified in order for this to work, and `char` must be a hexadecimal character.

Both `sendRequest` and `replyRequest` will output false if something is invalid (UID for `sendRequest`, and no request to reply to for `replyRequest`), and true otherwise.

The bot will receive three arguments as input to its function. The first is an array/list of each knight/knave, with each one represented as an array/list of two objects (`index` and `char` are their properties).

The second argument is the number of bots. UIDs range from zero to one less than this number. Finally, the third argument is an empty object, which the bot can use to store any information it needs.

## Rules

* The bot can be programmed in JavaScript (**heavily recommended**), Python, or any language with functions, strings, numbers, arrays/lists, and objects/dictionaries/hash maps
* All bots will be converted to JavaScript to be run in the controller
* A bot may not read or modify any variables outside of its function arguments and local/function scoped variables it creates
* A bot may not execute any functions declared outside its scope, aside from the four interaction functions (`sendRequest`, `readResponses`, `viewRequest`, and `replyRequest`)
* **Your bot's guess is submitted by return value. If it does not know, it can return null/false/undefined, or a random guess. Each bot has a win count. If multiple bots guess correctly in the same turn, this increments by `1/correctGuesses`**
* Standard Loopholes are prohibited, per the usual
* Controller, Chatroom
* By the way, this is not a dupe. The other questions based around knights and knaves have a very different objective, they are just similar in their topic

# Answer
> 2 votes
# Zero Information Bot

```
function ZeroInformationBot(people, bots, data) {
    if (!data) {
        data = {
            botData: [],
            knaves: [],
            guess: "",
            newKnaves: false,
            attestations: Array(36).fill(0),
            threshold: -5,
        };
    }
    let newResponses = [];
    readResponses().forEach(res => {
        if (!data.botData[res.uid][res.index]){
            newResponses.push(res);
            data.botData[res.uid][res.index] = res.char;
        }
    });
    newResponses.forEach(res => {
        if (people.find(p => (p[0].index == res.index && p[0].char == res.char) || (p[1].index == res.index && p[1].char == res.char))){
            people.forEach((p, i) => {
                if ((p[0].index == res.index && p[0].char == res.char) || (p[1].index == res.index && p[1].char == res.char)) data.attestations[i] += 2;
                if ((p[0].index == res.index && p[0].char != res.char) || (p[1].index == res.index && p[1].char != res.char)) data.attestations[i] -= 1;
                if (data.attestations[i] < -1 && !data.knaves.find(i)) {
                    data.knaves.push(i);
                    data.newKnaves = true;
                }
            });
        }
    });
    viewRequests().forEach(req => {
        if (!data.botData[req.uid]){
            data.botData[req.uid] = Array(36).fill([]);
        } else if (!data.botData[req.uid][req.index]) {
            sendRequest(req.uid, req.index);
            data.botData[req.index] = "-"
        } else if (data.botData[req.uid][req.index] != "-") {
            replyRequest(req.uid, req.index, data.botData[req.uid][req.index]);
        }
    });
    if (!data.newKnaves && data.guess) return data.guess;
    data.newKnaves = false;
    let detected = true;
    let loop = false;
    let possibilities;
    while (detected){
        detected = false;
        possibilities = Array(36).fill(new Set());
        let examined = [], chargroups = [];
        people.forEach((p, i) => {
            if (data.knaves.find(i)) return;
            possibilities[p[0].index].add(p[0].char);
            possibilities[p[1].index].add(p[1].char);
            let first = examined.find(e => e.index == p[0].index && e.char == p[0].char);
            let second = examined.find(e => e.index == p[1].index && e.char == p[1].char);
            if (first && !second){
                chargroups[first.group].push(p[1]);
                examined.push({index: p[1].index, char: p[1].char, group: first.group});
            } else if (!first && second){
                chargroups[second.group].push(p[0]);
                examined.push({index: p[0].index, char: p[0].char, group: second.group});
            } else if (!first && !second){
                examined.push({index: p[0].index, char: p[0].char, group: chargroups.length});
                examined.push({index: p[1].index, char: p[1].char, group: chargroups.length});
                chargroups.push(p);
            } else if (first && second && first.group != second.group){
                chargroups[first.group].push(...chargroups[second.group]);
                examined = examined.map(e => {
                    if (e.group == second.group) e.group = first.group;
                    return e;
                });
                chargroups.splice(second.group, 1);
            }
        });
        possibilities.forEach((p, i) => {
            if (p.size == 1) {
                let char = Array.from(p)[0];
                chargroups.forEach(c => {
                    if (c.find(ch => ch.index == i && ch.char != char)) {
                        people.forEach((person, j) => {
                            if (data.knaves.find(j)) return;
                            // We don't need to check both characters; if one's in the group they both are.
                            if (c.find(ch => ch.index == person[0].index && ch.char == person[0].char)) {
                                data.knaves.push(j);
                                detected = true;
                            }
                        });
                    }
                });
            } else if (p.size == 0) {
                // Uh oh... need to reset.
                data.knaves = [];
                data.attestations.forEach((a, i) => {
                    if (a <= data.threshold) data.knaves.push(i);
                });
                detected = true;
                // Don't get stuck in a loop.
                if (loop) data.threshold--;
                loop = true;
            }
        });
    }
    data.guess = possibilities.map(p => Array.from(p)[0]).join("");
    return data.guess;
}

```

This bot lets out exactly zero information. Whenever it's asked about something, it responds by first asking what that bot thinks, and then it replies with that data.

It counts up the number of times that other bots have given it one of the values of one of the people, and uses that to give a rough confidence score to each person, tentatively marking someone as a knave if they hit -2. If it hits a paradox, it resets who it's considering as a knave, but only automatically re-marks someone as a knave if they have a score of -5 or worse.

Because this bot doesn't aggressively attempt to solve, it's quite possible it'll get stuck on one or two people for a long time; I'm interested in how well it will do. I haven't tested it yet, as it seems the controller is still (slightly) in flux.

# Answer
> 2 votes
# TotallyRandomBot

(Hey, first time posting!)

TotallyRandomBot literally just guesses randomly, (maybe) eventually arriving at the answer through brute force. Keeping true to its random nature, it always replies with a random character when asked for help. Will it find the answer fast? No. Will it eventually find the answer, while throwing others off? Quite possibly.

---

```
function TotallyRandomBot(people, bots, data) {
  // string of length 32
  let guess = "00000000000000000000000000000000";
  let hex = "0123456789ABCDEF";
  if(!data) {
    // starting index
    data = {
      index:0,
      prev_guess:""
    }
  }
  // reply with random char
  viewRequests().forEach(req => {
    replyRequest(req.uid, req.index, hex[Math.random() * 16|0]);
  })
  // assemble guess
  people.forEach(obj => {
    guess[obj.index] = obj.char;
  })
  // change a random char
  if(data) {
    guess[data.index] = hex[Math.random() * 16|0];
    // if we've reached the end
    if (data.index === 31) {
      // start anew
      data.index = -1;
    }
    data.index++;
  }
  // write it to previous guess
  data.prev_guess = guess;
  // cross fingers and guess
  return guess;
}

```

---
Tags: king-of-the-hill
---


title: Build a digital clock in Wireworld

text:
# Question
Title: Build a digital clock in Wireworld
Inspired by this Game of Life question.

Wireworld simulates "electrons" flowing through "wires", simple arrangements of which produce typical logic gate behavior.

I challenge you to build a digital clock in the Wireworld cellular automaton. **Your clock must count upwards from 00:00 to 23:59 in the usual fashion, or to 11:59 with an AM/PM indicator, then reset.**

Your entry should be visibly divided into two parts. **Part A should contain all of the non-display logic, all of the parts involved in incrementing and looping the digits.** Part B will be the display and the logic that drives it. The only connection between these two parts should be 16 wires representing the four digits of the time in BCD (with one optional wire for the AM/PM indicator, and one optional wire for a signal clock line if your signals aren't continuous). **(EDIT: always-zero wires can be omitted)**

**The timing of the clock behavior should be consistent.** The simulation should take the same number of ticks for each of the 1440 transitions between states. Any electrons on the 16 wires should emitted from part A at the same time and start their trip in parallel.

**This is a code-golf competition. Your score is the area of the axis aligned bounding box surrounding part A.**

By analogy, if this were a textual language, your score would be the size of the clock-management function producing four 4-bit outputs, which contains a loop and the logic for 4 counters, not the function that decodes and prints that output.

Your part B can be as large or small as you'd like. It is only required so that the output of your submission can be seen by someone running it, since there is no easy way to simply "debug" outputs from a wireworld circuit. There are multiple BCD-\>7segment circuits available online. Feel free to use whichever one you'd like, or make your own if you need a clocked signal line, and display your AM/PM indicator at some scale similar to the digits.

EDIT: Part B is now optional. If you just have the BCD outputs from your part A, feel free to submit that. It will be more tedious to confirm the clock works, but I can read a row of bits just fine in a paused simulation.

# Answer
# Binary counter clock (score = ~~134×33 = 4422~~ 134×32 = 4288)

As promised 2⅔ years ago. Actual building time from scratch was less than 3 days.

I took inspiration from several sources, but in the end everything is custom made, and no cell is copied from any design by someone else. It makes royal use of the colors of WireWorldMarked (also by me, and supported by default by Golly). The colors are just eye-candy and don't change the rules of WireWorld.

This uses 10 micron technology (electrons spaced 10 gens apart). This makes small loops (memory cells for example) larger, however it allows not only for easier calculations but also compact axis-aligned ROMs and decoders, and it's the maximum throughput of a 'cross' gate. Everything makes use of 'negative' logic, where the presence of electrons is a logical '0' and missing electrons are '1'. In this sense, an OR gate, for example, does A=0 OR b=0 -\> output 0. The sole reason for this is that it makes the binary counters, and in particular, the reset logic, much less complex.

The clock's real-time speed is 480 gens per minute (large green loop) ~~which translates to 0.125s per gen or 8 gens/s. The loop expands the bounding box by 1 in the vertical direction, but with any smaller number the carries propagate too slow and it never displays the correct time.~~ Unfortunately it will never be real-time in Golly because Golly only applies a delay *between* gens, and with a non-negligible duration of calculating a gen, it will run slow if you set the delay to 0.125. In fact, the speed appears to be non-constant and fluctuates by several percents.

**\[edit\]** This is v2 in which I've synchronized the display segments. This way the maximum delay between the final change of the leftmost display and the next change of the rightmost display (between 24:00-\>0:00) is 170 gens. The V1 display update took 500 gens, longer than 480 gens (a 'minute'), oops. I was about to boast how good I am for squeezing a loop of 440 in a box 1 less tall, then choosing 400 gens because it divides a minute nicely, but I wanted a significantly higher number, and was done waiting until someone pointed out "hey why don't you just use a smaller loop and some dividers?". So I used three dividers and a loop of 150 gens for a rate of 1200 gens/min (20Hz). The squeezed loop is still visible in the explanation image below.

High-speed animation at 7200 gens/s (1.2MiB)
Real-time animation of only the display (600KiB)
(animations are of v1 but still give an impression of the clock)

Extra explanations and some dividers before final space-optimizations:

(the gray arrows point to cells in the middle of the machinery which are either present or absent, depending on if that bit should contribute to the reset logic.)

Golly pattern with everything I made until now: Clock (Mark Jeronimus).mc
> 10 votes

# Answer
# Latching Clock

**Score - 53,508** (of which only 36,828 is actively used due to the L-shaped design)

High Quality recording - https://1drv.ms/u/s!ArQEzxH5nQLKhvt\_HHfcqQKo2FODLQ
Golly pattern - https://1drv.ms/u/s!ArQEzxH5nQLKhvwAmwCY-IPiBuBmBw

Guiding Principles -

* Since this was my first time using a cellular automaton I avoided stringing together large premade components. One valid approach I did not take would have been a binary adder starting at zero and continuously adding one to the last output, followed by a binary to BCD converter, display demultiplexer, 7-segment decoder and 7-segment display.
* It should be possible to cold start the clock. I imposed on myself the additional restriction that a single electron head placed at a specific conductor cell should correctly start the clock. I did not want to require careful manual synchronisation of many disparate flip-flops and individual timing elements before beginning the simulation.

# Part I: The Minute Counter

### Mathematics

Counting from 0 to 9 in binary (for the least significant minutes digit) goes as follows -

0 - **0000**
1 - **0001**
2 - **0010**
3 - **0011**
4 - **0100**
5 - **0101**
6 - **0110**
7 - **0111**
8 - **1000**
9 - **1001**

Reading that as columns, the least significant (2^0 units bit stream) goes 01010101, the 2^1 units stream goes 0011001100, the 2^2 units stream goes 0000111100 and the 2^3 units stream goes 0000000011.

The first one's easy - just flip-flip 01 forever. The third is a stream of four 1s, six 0s, phase shifted by six zeros. The fourth is a stream of eight 0s and two 1s.

The second is a bit harder as it's got a nasty asymmetry. However, I notice that (where . is concat operator):

0011001100 . 0011001100 = 0011001100 . NOT(1100110011) = 00110011001100110011 XOR 00000000001111111111 = 5(0011) XOR 00000000001111111111

(Incidentally, as alluded to later, the majority of my clock runs on a 60-beat ticker. The 00000000001111111111 double length wave is where the need for the 120-beat ticker comes in).

### Design

The output streams from top to bottom go Units of Minutes (2^0, 2^1, 2^2, 2^3) then Tens of Minutes (2^0, 2^2, 2^1). Note that the bottom two wires are crossed.

1. 120-beat main clock.
2. Where to place an electron for a cold start. Without any electron tail it splits in two directions but the diode immediately above catches one of these giving a nice cycling electron going around and round the 120-beat loop.
3. 12-beat secondary clock.
4. Coil of conductor + diode starts the secondary 12-beat clock. Words cannot describe how fiddly this little piece was to sync. You have to sync the 120 and 60 beat clocks, then sync in the 12-beat and frequency halver 24-beat pseudo clocks, followed by tying back the 24-beat clock to the 120-beat clock otherwise the XOR gate doesn't work.
5. Phase shift.
6. Flip-flop. A single electron on the input hits the set line first then after a very specific amount of time, hits the reset line giving precisely one pulse in, one pulse out.
7. Adding humps here - on the reset line, increases the delay between set and reset on the flip-flop. Each extra hump gives an extra pulse. The flip-flop below has nine extra humps, so ten pulses between set and reset.
8. XOR gate for my tricky 2^1 units of minutes line.
9. AND-NOT gate and very specific part lengths means each electron pulse which comes past doubles back on itself and annihilates the electron behind. Frequency halver. Creates a 24-beat clock from the 12-beat secondary source.
10. 60-beat secondary clock, which actually does most of the work. It's just easier to start a fast clock from a slower one, so the slowest clock (120-beats) is the master, even though it's barely used. The 60-beat clock is the heart of this thing.
11. Feedback wire which carries electrons only when the 60-beat clock is ticking. It's used in conjunction with an AND-NOT gate to stop the clock being restarted repeatedly from the 120-beat master. Otherwise many horrible things happen & Ctrl-Z is saviour.
12. The diode where the 60-beat clock is started from.
13. This whole device is a flip flop, AND gate, and AND-NOT gate combined. It gives a latch. One pulse in starts it, one pulse in stops it.
14. Loop of wire to calibrate the latch to 10 pulses on, 10 pulses off for a one in ten pulse input. Without it we get 12 pulses on, 8 pulses off. These ten on ten off latches form the basic components of the ten minute blocks in the same way the 6-micron (1 pulse) flip-flops formed the basic components of the minute units.
15. The cold start initial pulse caused all sorts of problems including being two beats out of phase with the clocks it starts. This messes up the latches. This AND gate catches and disposes of out of sync pulses - in particular the starting pulse.
16. This is a part of the design I somewhat regret in retrospect. It takes an electron, splits it into five and annihilates the five electrons behind, taking 111111 to 100000.
17. This takes an electron and stitches it on the front. Two phases ahead to be precise. It takes 100000 and makes 101000. Combined with part 16 we get 111111 -\> 100000 -\> 101000. In retrospect I wish I'd done 111111 -\> 101010 -\> 101000; it would have achieved the same effect in less space.
18. The above patterns are then pushed into the bottom latch to achieve 20 on, 40 off. This is split, half is phase shifted by 20 units, and then these form the two high order bit streams of the tens of minutes.

# Part II: The Hour Counter

### Explanation

The input to the hour counter is a single electron pulse, once an hour. The first step is to reduce this to a single electron pulse, once every twelve hours. This is achieved using several "latch & catch" primitives.

A "latch" is a 6-micron flip-flop connected to an AND-NOT and an AND gate to give a 6-micron on/off latch. A "catch" takes a continuous stream of electrons as input, allows the first through, then annihilates every other electron behind, until the stream ends at which point the catch resets.

Placing a latch, followed by a catch, in series, results in one electron in -\> turns on the latch, one electron out the other end (rest caught by catch). Then second electron in -\> turns off latch, catch silently resets. Net effect: first electron passes through, second electron is annihilated, and so on and so forth, *irrespective of how long the delay is between those electrons*.

Now chain two "latch & catch" in series, and you have only one in four electrons passing through.

Next, take a third "latch and catch", but this time embed an entire fourth latch and catch on the flip-flop SET line, between the AND-NOT gate and the flip-flop SET. I'll leave you to think about how this works, but this time only one in three electrons passes through, *irrespective of how long the delay is between those electrons*.

Finally, take the one in four electrons, and the one in three, combine them with an AND gate, and only one in twelve electrons pass through. This whole section is the messy squiggle of paths to the top left of the hour counter below.

Next, take the electron every twelve hours and split back into one every hour, but output each onto a different conductor wire. This is achieved using the long coiled conductor with thirteen exit points.

Take these electrons - one an hour down different conductors, and hit a flip-flop SET line. The RESET line on that same flip flop is then hit by the next hour's conductor, giving sixty pulses down each wire per hour.

Finally - take these pulses and pass them into seven and a half bytes of ROM (Read-Only Memory) to output the correct BCD bitstreams. See here for a more detailed explanation of WireWorld ROM: http://www.quinapalus.com/wires6.html

### Design

1. One electron per hour input.
2. First latch.
3. First catch.
4. "Latch & catch" embedded on an outer "latch & catch" SET line.
5. AND gate.
6. AM/PM latch (turned on/off once every twelve hours).
7. Each loop of wire is 6x60=360 units long.
8. Flip/Flop turned on its side to create a smaller profile.
9. Seven and a half bytes of ROM.

# Notes

1. Due to its one electron per minute, 6-micron design, run the simulation at six generations per minute (one generation every 10 seconds) for a real-time clock.
2. The AM/PM line is high (1) for AM, low (0) for PM. This might seem a slightly unusual way round to choose, but there is justification. During a cold start of the clock, the AM/PM line is naturally low (0) initially. As soon as the AM/PM line is pulled high (1), this indicates that the count has begun at 12:00AM. All output before this point should be disregarded, all output after this point is considered meaningful.

# Useful Links
> 42 votes

# Answer
## Delay line memory - 51 x 2880 = 146880

Zoomed out:

Output comes out the top of each loop.

I put all the states directly on the wire with this lua, letting `golly` step the electrons forward between bits so we don't have to follow the wire with a cursor.

I used this naive method to set a bar and crash course wireworld, golly and lua.

```
local g = golly()

local minutes_in_day = 1440 -- 60x24
local interval = 4 -- how often to send electrons

local function bcd4(num)
    num=math.floor(num)
    local t={}
    for b=4,1,-1 do
        t[b]=math.floor(math.fmod(num,2))
        num=(num-t[b])/2
    end
    return table.concat(t)
end

local function makewire(x,y1,y2)
    for y1=1,y2 do g.setcell(x,y1,3) end
end

local function makeloop(x,y,size)
    local len = size/2 - 1
    makewire(x,y+1,len); makewire(x+2,y+1,len) -- main wires
    g.setcell(x+1,y,3); g.setcell(x+1,y+len,3) -- endcape
end

local function paint(x,y,pattern)
    for v in string.gmatch(pattern,".") do
        if v=="1" then g.setcell(x, y, 1); g.setcell(x, y-1, 2) end
        x = x + 4
    end
    g.show(pattern);g.update() -- slows things down but more interesting to watch
    for i=1,interval do g.step() end
end

for x=0,63,4 do makeloop(x,0,minutes_in_day * interval) end

for hour = 0,23 do
      for minute = 0,59 do
         paint( 0, 2, bcd4(hour/10) .. bcd4(hour%10) .. bcd4(minute/10) .. bcd4(minute%10) )
      end
end

```

For testing I added these top wires and watched their tips.

Here's the script to collect the 4 sets of 4 wire BCD to eyeball.

```
-- watches 16 wires spaced 4 apart starting at (0,-4)
local ticks = 1440 -- set to match the length of your 24 hour loop
local g = golly()
local output = ""
local nums = {  ["0000"] = "0", ["0001"] = "1", ["0010"] = "2", ["0011"] = "3", ["0100"] = "4",
                ["0101"] = "5", ["0110"] = "6", ["0111"] = "7", ["1000"] = "8", ["1001"] = "9",
                ["1010"] = "A", ["1011"] = "B", ["1100"] = "C", ["1101"] = "D", ["1110"] = "E",
                ["1111"] = "F" } -- full set in case we have errors (i did)

for i=0,ticks,1 do
   local text = ""
   for i=0,48,16 do -- set your X here, change the 0 and 48
       local word = ""
       for j=0,15,4 do
            local bit = g.getcell(i+j,-4) -- set your Y here, change -4
            if bit == 0 or bit == 3 then word = word .. "0" else word = word .. "1" end
       end
       text = text .. nums[word]
   end
   g.show(text); output = output..' '..text
   g.update(); g.step();g.step();g.step();g.step()
end
g.note(output)

```

*Final answer requires pruning the always-zero lines and routing the rest to their correct BCD inputs.*
> 5 votes

---
Tags: code-golf, graphical-output, cellular-automata
---


title: I hate broccoli!

text:
# Question
Title: I hate broccoli!
My mom really wants me to eat broccoli, but I hate it and never want to eat it. Mom wants to trick me so she cuts it into small pieces, puts it in a salad and mixes it. Help me find out if the salad contains broccoli!

**Input:**

Array of mixed letters of all the ingredients. For a single broccoli ingredient it could be:

```
[c,o,r,b,l,c,i,o]

```

**Output:**

Boolean or other convienient output allowing to distinguish if a salad contains broccoli or not.

**Rules:**

* all possible ingredients are `onion`, `broccoli`, `celery` and `beans`
* input array is always formed of mixing valid ingredients (meaning that it can be always decoded back to the original ingredients array)
* input array cannot be decoded into more than one valid ingredient combination
* each ingredient can occur 0 or more times in the salad

**Sample test cases:**

`true` stands for a salad with broccoli

```
[c,o,r,b,l,c,i,o] //true
[o,b,n,o,i,i,e,l,n,a,o,r,n,s,b,o,c,c] //true
[l,c,b,r,r,o,r,c,i,i,c,o,c,b,o,c,c,b,i,o,l,o,l,o] //true

[] //false
[o,n,i,o,n] //false
[b,n,s,i,a,o,n,b,a,s,e,e,n,o,n] //false
[b,r,o,c,c,o,l,i,e,y,e,r,l,a,e,e,n,s,y] //false
[e,n,s,o,e,n,i,o,a,o,o,e,n,n,e,l,n,l,e,o,e,r,c,l,o,y,i,r,y,r,y,b,e,l,n,n,c,c,r,c,e,y,i,e] //false

```

**This is so the shortest code in bytes wins!**

# Answer
# Python 2, ~~34~~ 32 bytes

-2 bytes thanks to @dingledooper

```
lambda a:cmp(*map(a.count,'bs'))

```

Try it online!

Returns `1` for true, `0` for false
> 39 votes

# Answer
# , 14 bytes

```
[:=/1#.'cy'=/]

```

Try it online!

*Idea of invariant based on letter counts from mathjunkie's clever answer -- be sure to upvote him.*

* 0 for contains broccoli
* 1 for not

Tests if the number `c`s is equal to the number of `y`s. This will only be true when no broccoli is present.
> 17 votes

# Answer
# perl -ple, 14 bytes

```
$_=y-y---y-c--

```

Try it online!

Prints 0 if no broccoli is present, something else if there is.
> 16 votes

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
„bsS¢Ë

```

-1 byte by reversing the output: will output `0` if it contains broccoli and `1` if not.

Try it online or verify all test cases.

**6 bytes** alternative which outputs `1` if it contains broccoli and `0` if not:

```
AS¢üÊн

```

Try it online or verify all test cases.

**Explanation:**

```
„bs     # Push string "bs"
   S    # Convert it to a character-list: ["b","s"]
    ¢   # Count each in the (implicit) input
     Ë  # Check if the counts are the same for both letters (1 if truthy; 0 if falsey)
        # (after which it is output implicitly as result)

A       # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz"
 S      # Convert it to a character-list: ["a","b","c",...,"z"]
  ¢     # Count each in the (implicit) input-list
   ü    # For each overlapping pair of counts:
    Ê   #  Check that they are not equal to one another (1 if truthy; 0 if falsey)
     н  # Pop and only leave the first check (for letters 'a' and 'b')
        # (after which it is output implicitly as result)

```

If the amount of `b` and `s`/`a` are the same, it means the input only contains `beans` and no `broccoli`.
> 8 votes

# Answer
# MATLAB/Octave, 26 bytes

```
@(b)b&&diff(sum(b'=='cl'))

```

Try it online!

Credit to @mathjunkie's answer for the idea. Interestingly comparing `c` and `l` counts also works because `celery` has one of each, but `broccoli` has a different number.

MATLAB likes to expand `==` into 2D arrays if the inputs are vectors in differing orientations. However this doesn't work with empty arrays. Fortunately empty is false in MATLAB and non-empty with any non-zero elements is true, so we can simply use the input as a logical true-false to capture that case.
> 8 votes

# Answer
# APL (Dyalog Classic), ~~19~~ 12 bytes

```
>/+/↑'cl'=⊂⍞

```

Try it online!

Note that you have to add `⎕←` to the beginning for it to output. Originally created with **ngn/apl**.

```
>/+/↑'cl'=⊂⍞
            ⍞ ⍝ get input
     'cl'=⊂   ⍝ make two packed vectors: characters equal to c and l
  +/↑         ⍝ turn into two row matrix and add (to get number of 'c's and 'l's
>/            ⍝ Are there more 'c's than 'l's?

```

returns broccoli: 1, no broccoli: 0
> 5 votes

# Answer
# JavaScript (ES6),  ~~33~~  32 bytes

*Saved 1 byte by not forcing a Boolean value, as suggested by @SteveBennett*

Takes a string and returns *undefined* (falsy) for a broccoli-free salad (yummy!) or a string (truthy) otherwise (yuck!).

```
s=>s.split`b`[s.split`s`.length]

```

Try it online!
> 5 votes

# Answer
# JavaScript (SpiderMonkey), 32 bytes

```
s=>s.map(c=>++this[c],r=y=0)|r>y

```

Try it online!

# JavaScript (Node.js), 37 bytes

```
s=>s.map(c=>n+=~~{r:1,y:-1}[c],n=0)|n

```

Try it online!
> 4 votes

# Answer
# Charcoal, 7 bytes

```
›№θb№θs

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean; `-` for broccoli, nothing for none. Explanation:

```
 №θb    Number of `b`s in input
›       Exceeeds
    №θs Number of `s`s in input
        Implicitly print

```
> 4 votes

# Answer
# K (oK), 11 bytes

**Solution:**

```
</+/"sb"=/:

```

Try it online!

**Explanation:**

Shamelessly stolen "more s' than b's" logic from mathjunkie:

```
</+/"sb"=/: / the solution
    "sb"=/: / "sb" equal (=) each-right (/:)
  +/        / sum
</          / s less than b? (aka no brocoli?)

```
> 4 votes

# Answer
# Zsh, 22 characters

```
((${#1//a}==${#1//b}))

```

Expects the ingredients as a single command line parameter.
Sets the exit code to 1 for broccoli alert and 0 for no broccoli.

(Just to keep the exit code semantics of 0 = Ok / non-0 = error. Using `<` for comparison would save 1 character but reverse the result's encoding.)

Sample run:

```
manatwork@manatwork ~ % . ./broccoli-detector.zsh obnoiielnaornsbocc
manatwork@manatwork ~ % echo $?
1
manatwork@manatwork ~ % . ./broccoli-detector.zsh broccolieyerlaeensy
manatwork@manatwork ~ % echo $?
0

```

Try it online! / Try all test cases online!
> 4 votes

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

```
ċⱮ⁾abE

```

A monadic Link accepting a list of characters which yields `0` if the salad contains broccoli and `1` if not.

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

### How?

Tests whether the number of `'b'`s (in both 'broccoli' & 'beans') is equal to the number of `'a'`s (in only 'beans').

```
ċⱮ⁾abE - Link: list
 Ɱ     - map across...
  ⁾ab  - ...what: list of characters = ['a', 'b']
ċ      - ...applying: count
     E - all equal?

```
> 3 votes

# Answer
# Retina 0.8.2, 18 bytes

```
+`[^bs]|bs|sb

1`b

```

Try it online! Link includes test cases. Explanation:

```
+`[^bs]|bs|sb

```

Delete everything that's not a `b` or an `s`, plus any remaining `bs` or `sb` pairs that result from bean salad.

```
1`b

```

Check whether there is any broccoli.
> 3 votes

# Answer
# Java (JDK), 41 bytes

```
s->s.reduce(0,(a,c)->c<98?a-1:c<99?a+1:a)

```

Try it online!

Uses a `chars()`-Stream as input, returns any strictly positive value if it contains brocoli.

## Credits

* -5 bytes thanks to Elgirhath by comparing `b` to `a` instead of `b` to `s`, and by allowing any positive value instead of a strict boolean.
> 3 votes

# Answer
# asm2bf, 73 bytes

Try it online!

Takes input on stdin as a string; outputs either `ASCII(0x00)` or `ASCII(0x01)`.

```
@l
in r1
ceqr1,.b
cadr2,1
ceqr1,.s
cadr3,1
jnzr1,1
gt r2,r3
outr2

```

Commented code:

```
; Essentially, our game plan is to compare amount of `b' and `s' occurences.
; Start a new label
@loop
; Read a character from stdin, put it in r1.
  in r1
; If r1 = 'b' (note the way of expressing a character constant), set
; the condition flag.
  ceq r1,.b
; If the condition flag is set, add 1 to r2
  cadd r2,1
; If r1 = 's', set the condition flag. Otherwise, clear it.
  ceq r1,.s
; If the condition flag is set, add 1 to r3
  cadd r3,1
; If r1 is bigger than zero, we didn't hit eof yet, so continue reading.
; Note: The golfed version is based on a certain property beyond explaining.
; It's related to the way how labels work under the hood.
  jnz r1,%l
; The loop finished.
; Compare r2 and r3 (the accumulators).
gt r2,r3
; Display the result
out r2

```
> 3 votes

# Answer
# Japt, 6 bytes

Takes input as a string with reversed output.

```
èÕ¶Uèc

```

Try it \- includes all test cases, footer negates the output for easier testing
> 2 votes

# Answer
# C (gcc), ~~57~~ \\$\cdots\\$ ~~53~~ 52 bytes

Saved 3 bytes thanks to l4m2!!!

Saved a byte thanks to Arnauld!!!

```
a;f(char*s){for(a=0;*s;++s)a+=*s-99?*s>120:-1;a=!a;}

```

Try it online!

Takes a string as input and returns a \\$1\\$ for edible and a \\$0\\$ for *grossing me out*!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 39 bytes

```
i=>i.Count(x=>x==98)>i.Count(x=>x=='s')

```

Try it online!
> 1 votes

# Answer
# PHP, ~~44~~ 42 bytes

-2 bytes thanks to @Elgirhath

```
$b=count_chars($a,1);echo+($b[98]>$b[97]);

```

Try it online!
> 1 votes

# Answer
# Google Sheets, ~~34~~ 33 bytes

*Saved 1 byte thanks to Steve Bennett*

```
=CountIf(A:A,"b")>CountIf(A:A,"s"

```

Input is in column `A`. When you exit the cell, Sheets will automatically add the trailing parentheses.

There's nothing really clever about this solution besides implementing the concept from others.
> 1 votes

# Answer
## Javascript, 46 characters

Shortening Yaraslav's answer:

```
s=>(q=z=>s.filter(e=>e==z).length)('b')>q('s')

```

## Javascript, 62 characters

```
x=>([,a,b]=/(a*)(b*)/.exec(x.sort().join``),b.length>a.length)

```

Maybe I missed something? Just counts if there are more `b` than `a`.
> 1 votes

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

```
s=>s.filter(e=>e=='b').map(Date)>s.filter(e=>e=='s').map(Date)

```

Try it online!

# JavaScript (Node.js), 56 bytes

```
s=>s.filter(e=>e=='b').length>s.filter(e=>e=='s').length

```

Try it online!
> 0 votes

---
Tags: code-golf
---


# Question
Title: Build an interpreter for "Goggle kids Code"
Partially inspired by this question.

## Overview

The execution of Goggle kids Code starts with an empty binary tape with 100 items, with the pointer starting at the index 0:

```
00000...
^

```

At the end of the execution, you can assume that the tape is implicitly outputted.

## Instructions

Goggle kids Code is a simple language involving a stack-like tape.

* `/`: Move the pointer right.
* `\`: Move the pointer left.
* `>`: Take two items from the tape, the left item and the current item. Zero the current item, move left, and set the item as 1 if `left` is larger than `current`, else 0.
* `=`: Similar to `>`, but performs an equality comparison instead.

The only looping structure in Goggle kids Code is the repeat loop, which takes a *strictly positive* number on the right introduced by a `x` symbol. (So things like `(...)x0` is impossible here.) The syntax for this is:

```
(...)xI

```

The parentheses can only contain single instructions, although you can introduce other instructions with commas.

## Sample program + Explanation

```
((/,>)x4,/)x13

(         )x13  Do this 13 times:
 (   )x4            Do this 4 times:
  /                    Move right
   ,                   After that,
    >                  Greater than
        ,           After that,
         /          Move pointer right.

```

Another example that does something useful (fills 13 items from the tape with 1's):

```
(   )x13    Do this 13 times:
 /              Move right
  ,             After that,
   =            Equality

```

## Rules

* You can assume the tape pointer never wraps around.
    + The test cases won't abuse out-of-bounds tape-moving.
* To simplify the solution, you are allowed to output part of the tape, as long as that part is modified.
* You are allowed to have a different instruction mapping, but if you do that, please make sure to clarify which mapping you used.
* You could ignore checking the commas in the source code, they'll always be there.
    + Instructions are always separated by the comma.

## Test cases

The trailing `0` digits are omitted here, for compactness of example outputs.

<pre><code>((/,>)x4,/)x13  -> 0000000000000 (doesn't modify the tape)

(/,=,/)x13      -> 1111111111111

(/,=,/,/)x13    -> 1010101010101010101010101

(/,=)x13,/,=    -> 00000000000000000

(/,/,=,\)x3     -> 0100
```
</code></pre>

# Answer
> 2 votes
# Ruby, 89 bytes

```
t=[i=0]*100;(eval"[#$_]").flatten.map{|x|x<2?t[i-=1,2]=[x==t[i]-t[i+1]?1:0,0]:i+=x-3};p t

```

Try it online!

The translation map of the characters used for instructions is indicated in TIO header.

# Answer
> 12 votes
# Python 2, ~~131 126 123 110~~ 104 bytes

*Saved 13 bytes thanks to @dingledooper's approach of flattening nested list using backtick.*
*Saved 2 bytes thanks to @l4m2*

```
p,t=0,[0]*100
for i in`input()`:
 if"/"<i:i=int(i);p+=i/3-1
 if i<2:t[p:p+2]=cmp(*t[p:p+2])==i,0
print t

```

Try it online! or Verify all test cases

Takes input from `STDIN`, where `/\>=x` are replaced with `6210*`

### Big idea:

Python 2 `input()` implicitly evaluates the string read from `STDIN`. Thus, reading modified input like `((6,1)*4,2)*13` returns a nested tuple of integers, aka

```
((6, 1, 6, 1, 6, 1, 6, 1), 2, (6, 1, 6, 1, 6, 1, 6, 1), 2, ...)

```

Note that loops containing single instruction must be terminated with comma, e.g `(1,)*10`.

Now that all loops have been automatically unrolled for us, we just have to flatten the resulting tuple, and decode the instructions.

To flatten the nested tuple, we simply convert it to string, then takes all numerical characters.

# Answer
> 4 votes
# JavaScript (Node.js), 149 bytes

```
s=>eval(`[${s.replace(/ \d+/g,'.toString().repeat($&)')}]+6`).replace(/\d/g,c=>c>4?p+=c-6:(X[p-1]=X[p-1]-X[p]==c,X[p--]=0),X=Array(100).fill(p=0))&&X

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 135 bytes

```
,

\d+
$*
+`\([^()]+\)x|(?<=\(([^()]+)\)x1*)1
$1
^
0
{`(\d)/(\D*)((1)|0)?
$1$#4$2
(\d)\\(\D*)
$2$1
(?=(10>|(.)\2=))?.\d[>=](\D*)
$#1$+0

```

Try it online! Link includes test cases. Explanation:

```
,

```

Delete commas.

```
\d+
$*

```

Convert the multipliers to unary.

```
+`\([^()]+\)x|(?<=\(([^()]+)\)x1*)1
$1

```

Expand all repetitions from the inside out. (The last two stages can be performed by a single stage in Retina 1 at a saving of 19 bytes although you do then have to use `${3}` instead of `$+` in the last stage.)

```
^
0

```

Start with a tape with a `0`. (The tape is automatically extended to the right as necessary, as this was slightly golfier than predefining the tape..)

```
{`

```

Process the instructions until they have all been executed.

```
(\d)/(\D*)((1)|0)?
$1$#4$2

```

Move right, extending the tape as necessary.

```
(\d)\\(\D*)
$2$1

```

Move left.

```
(?=(10>|(.)\2=))?.\d[>=](\D*)
$#1$+0

```

(In)equality. (`$+` is used instead of `$3` because the next character is a digit.)

# Answer
> 1 votes
# JavaScript (Node.js), 235 bytes

```
p=>{s=[],l=Array(13).fill(i=q=0),e={'(':`s.unshift(1,i)`,')':`++s[0]<=parseInt(p.substr(i+1))?i=s[1]:s.splice(0,2)`,'/':`q++`,'\\':`q--`,'>':`l[q]=0,q--`,'=':`l[q]=0,q--,l[q]=+!l[q]`};while(i<p.length)eval(e[p[i++]]);return l.join('')}

```

Try it online!

# JavaScript (Node.js), 231 bytes

```
p=>{s=[],l=Array(13).fill(i=q=0),e={'(':`s.unshift(1,i)`,')':`++s[0]<=parseInt(p.substr(i+1))?i=s[1]:s.splice(0,2)`,'/':`q++`,'\\':`q--`,'>':`l[--q]=0`,'=':`l[q]=0,l[--q]=+!l[q]`};while(i<p.length)eval(e[p[i++]]);return l.join('')}

```

Try it online!

---
Tags: code-golf, interpreter
---


title: Can I trade today?

text:
# Question
Title: Can I trade today?
Back in 2018, there has been introduced new law in Poland to ban trading on sundays, but certain exceptions have been made (listed below). The task today is to determine, can one trade on the sunday provided by the user (according to these rules).

# Rules

You can trade only if one of the following is satisfied:

* The day is the last sunday of 1st, 4th 6th and 8th month.
* The day is one of the two sundays preceding Christmas.
* The day is the sunday preceding Easter

## Simplifications

Obviously one can't trade on certain holidays, but you can omit the check for them in your code. The only exclusion to this rule is Easter or Christmas (for obvious reasons).

For example, if the rules above allowed trading on 6th of January and albeit in reality you can't trade due to a holiday, you don't need to take that on the account (and assume that one can trade on 6th of January).

## I/O rules

You can take the date in any reasonable format - "DDMMYYYY", "MMDDYYYY" and so on. The output should be a truthy or falsy value (answering the question - can you trade on this sunday?)

You can assume the input date to always be a sunday.

## Examples

A few examples:

* You can trade on 27 January of 2019, due to rule 1.
* You can't trade on 13 January of 2019.
* You can't trade on 21 April of 2019 - it's Easter.
* You can trade on 14 April of 2019, due to rule 3.
* You can trade on 28 April of 2019, due to rule 1.
* You can trade on 15 December of 2019, due to rule 2.
* You can trade on 22 December of 2019, due to rule 2.

## Obvious clarifications

* You'll have to calculate the date of Easter and Christmas in the process.
* Your program has to work correctly with any other year than 2019.
* You MUST take on the account that you can't trade on Easter or Christmas, even if the conditions are satisfied.
* You don't need to check for other holidays.

# Scoring criterion

The shortest code (in bytes) wins.

# Answer
# JavaScript (ES6),  ~~173~~  172 bytes

Takes input as `(year, month, day)`. Returns **0** or **1**.

As anticipated by @streetster, computing Easter is the biggest part.

```
(y,m,d)=>169>>--m&(D=new Date(y,m,d+7)).getMonth()!=m|m>10&(d+3)/14|+D==+new Date(y,2,56-(c=(y%19*351-~((b=(a=y/25>>2)>>2)+a*29.32+13.54)*31.9)/33%29|0)-~(a-b+c-24-y/.8)%7)

```

Try it online!

## How?

### Last Sunday

We use the binary mask `0b10101001` (or **169** in decimal) to encode the 0-indexed months for which it's allowed to trade on the last Sunday. We make sure that **m-1** is one of these months and that adding 7 days brings us to the next month.

```
169 >> --m & (D = new Date(y, m, d + 7)).getMonth() != m

```

### Christmas

We simply test whether the month is December and the day is more than **10** and less than **25**.

```
m > 10 & (d + 3) / 14

```

All possible cases are summarized in the following table:

```
 Mo Tu We Th Fr Sa | **Su** | Mo Tu We Th Fr Sa | **Su** | Mo Tu We Th Fr Sa | **Su** | Mo Tu We
-------------------+----+-------------------+----+-------------------+----+----------
  8  9[10]11 12 13 | **14** | 15 16 17 18 19 20 | **21** | 22 23 24[25]26 27 | 28 | 29 30 31
  7  8  9[10]11 12 | **13** | 14 15 16 17 18 19 | **20** | 21 22 23 24[25]26 | 27 | 28 29 30
  6  7  8  9[10]11 | **12** | 13 14 15 16 17 18 | **19** | 20 21 22 23 24[25]| 26 | 27 28 29
  5  6  7  8  9[10]| **11** | 12 13 14 15 16 17 | **18** | 19 20 21 22 23 24 |[25]| 26 27 28
  4  5  6  7  8  9 |[10]| 11 12 13 14 15 16 | **17** | 18 19 20 21 22 23 | **24** |[25]26 27
  3  4  5  6  7  8 |  9 |[10]11 12 13 14 15 | **16** | 17 18 19 20 21 22 | **23** | 24[25]26
  2  3  4  5  6  7 |  8 |  9[10]11 12 13 14 | **15** | 16 17 18 19 20 21 | **22** | 23 24[25]
```

### Easter

We test whether **D** (computed above) is equal to Easter. The algorithm was taken from this page (function *ShortGregorianEaster1*). It returns a day in March which may be greater than 31, in which case `Date()` quietly converts into a day in April.

```
+D == +new Date(y, 2, some_long_and_boring_formula)

```
> 4 votes

# Answer
# Python 2 \+ `dateutil`, ~~163~~ 157 bytes

Possibly could be golfed some more. Even using a library function, calculating the date for Easter still takes up almost half of the code.

*-6 bytes thanks to @Arnauld*

```
from dateutil.easter import*
y,m,d=input()
e=easter(y)
print(e.month==m)*((e.day==d+7)-(e.day==d)*(m*d>99))+m/12*(d<25)*(d>10)+(m in[4,6])*d/24+(m%7==1)*d/25

```

Try it online!

Accepts input in the form `YYYY, (M)M, (D)D`. Returns `1` if trading is allowed, `0` otherwise.
> 2 votes

# Answer
# 05AB1E, ~~109~~ ~~103~~ 101 bytes

```
т÷©>3*4÷DV¹19%DU19*15O®8*13+25÷-30%DX11÷+29÷-23+DY-¹D4÷++7%(91O31‰R»9bS30+6ÝδαεŽ5ÂNèδ»}˜12ÐÝ+sδ»«sª²å

```

Input as `year`, `day\nmonth` (multi-line string).

Try it online or verify a few more test cases.

(68 bytes are used to calculate Easter Sunday.)

**Explanation:**

Calculate the week before Easter Sunday, using *@PeterTaylor*'s formula in his GolfScript answer here:

```
т÷             # Integer-divide the (implicit) input-year by 100
  ©            # Store it in variable `®` (without popping)
>              # Increase it by 1
 3*            # Multiply it by 3
   4÷          # Integer-divide it by 4
     DV        # Store a copy in variable `Y`
¹19%           # Push the input-year modulo-19
    DU         # Store a copy in variable `X`
19*            # Multiply the year-modulo-19 by 19
   15          # Push 15
     O         # Sum the three values on the stack together:
               #  year/100*3/4 + year%19*19 + 15
®8*            # Push variable `®` and multiply it by 8
   13+         # Add 13
      25÷      # Integer-divide it by 25
         -     # Subtract it from the earlier calculated number
          30%  # Modulo-30
             D # Duplicate it
X11÷           # Push `X` integer-divided by 11
    +          # Add it to top copy
     29÷       # Integer-divide it by 29
        -      # Subtract it from the other copy
         23+   # Add 23
            D  # Duplicate it
Y-             # Subtract `Y` from the top copy
  ¹D           # Push the input-year two times
    4÷         # Integer-divide to top year by 4
      +        # Add it to the year
       +       # Add it to the earlier number
        7%     # Modulo-7
          (    # Negate it
91             # Push 91 (three purposes: it adds 97; adds an additional 1 to make the
               #  day 1-based; subtracts 7 since we want the week before Easter Sunday)
  O            # Sum the three values on the stack
  31‰          # Divmod it by 31 to extract the 1-based month and day
     »         # And join those by newlines

```

Calculate all the other dates that could potentially be a truthy Sunday:

```
9              # Push 9
 bS            # Convert it to a binary-list: [1,0,0,1]
   30+         # Add 30 to each: [31,30,30,31]
      6Ý       # Push list [0,1,2,3,4,5,6]
        δ      # Apply double-vectorized:
         α     #  Take the absolute difference
               # [[31,30,29,28,27,26,25],[30,29,28,27,26,25,24],[30,29,28,27,26,25,24],[31,30,29,28,27,26,25]]
ε              # Map each to:
 Ž5Â           #  Push compressed integer 1468
    Nè         #  Index the map-index into it
      δ»       #  And join it to each individual day with a newline delimiter
}˜             # After the map: flatten the list
  12Ð          # Push 12 three times to the stack
     Ý         # Pop one, and push list [0,1,2,3,4,5,6,7,8,9,10,11,12]
      +        # Add each to 12: [12,13,14,15,16,17,18,19,20,21,22,23,24]
       s       # Swap so the third 12 is at the top of the stack
        δ»     # Join it to each individual day with a newline delimiter
          «    # And merge these to the earlier flattened list

```

Merge it together to a single list:

```
sª             # Add the earlier calculated Easter Sunday - 7 to the list

```

I.e. for the year 2019, we now have the following dates that are potentially a truthy Sunday:

```
["31\n1","30\n1","29\n1","28\n1","27\n1","26\n1","25\n1", # January 31 to 25
 "30\n4","29\n4","28\n4","27\n4","26\n4","25\n4","24\n4", # April 30 to 24
 "30\n6","29\n6","28\n6","27\n6","26\n6","25\n6","24\n6", # June 30 to 24
 "31\n8","30\n8","29\n8","28\n8","27\n8","26\n8","25\n8", # August 31 to 25
 "12\n12","13\n12","14\n12","15\n12","16\n12","17\n12","18\n12","19\n12","20\n12","21\n12","22\n12","23\n12","24\n12",
                                                          # December 12 to 24
 "24\n3"]                                                 # Sunday week before Easter

```

And we check if the second input is in this list to complete the program:

```
  ²å           # And check if the second input-string is in this list
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž5Â` is `1468`.
> 1 votes

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


title: Omit needless spaces for me

text:
# Question
Title: Omit needless spaces for me
A great Python golfing tip is to omit needless spaces. But if you are like me, you don't always have the time to search for which spaces to remove. If only there was a way to speed up the process...

## Task

Given a *single line* of Python, as input, return/output a new line which omits all needless spaces. The table below shows which spaces are *needless*, and must be removed for *maximum golfage*.

```
   | L D S
---+-------
 L | s s n
 D | n - n
 S | n n n

First token is row, second token is column
L: Letter
D: Digit
S: Symbol

s: space
n: no space
-: never happens (except multidigit numbers)

```

## Clarifications

* What is considered a letter, digit, and symbol?
    + Letter: `_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`
    + Digit: `0123456789`
    + Symbol: `!"\#$%&'()*+,-./:;<=>?@[]^`{|}~`
* You can assume that all characters in the input are either a *Letter*, *Digit*, *Symbol*, or *Space*.
* You can assume that there will be no such test case where two digits are separated by *one or more* spaces
* You can assume that all test cases contain valid Python syntax
* You can assume that there will be no leading or trailing spaces.
* Follow the above rules for omitting spaces, regardless of whether omitting them will produce incorrect or different code

## Test Cases

### Input

```
print ( "Hello, World!" )
eval("eval('eval(`1`)')")
_  =  '_  =  %  r  ;  print _  %%  _'  ;  print _  %  _
[ 1for _ in range(10, 6 , -1)     ]
print 16

```

### Output

```
print("Hello,World!")
eval("eval('eval(`1`)')")
_='_=%r;print _%%_';print _%_
[1for _ in range(10,6,-1)]
print 16

```

This is , so the shortest code in bytes wins!

# Answer
# Retina 0.8.2, ~~22~~ 21 bytes

*Saved a byte thanks to a mysterious hint from @Neil :P*

```
(\d|\W) +
$1
 (\W)
$1

```

Try it online!
> 9 votes

# Answer
# JavaScript (ES9),  ~~60~~  43 bytes

```
s=>s.replace(/(?<![a-z_] *) | (?=\W)/gi,'')

```

Try it online!
> 5 votes

# Answer
# Java (JDK), 48 bytes

```
s->s.replaceAll("(?<![a-zA-Z_] *) | (?=\\W)","")

```

Try it online!

Port of Arnauld's JS answer.
> 4 votes

# Answer
# perl -p, 24 27 26 bytes

```
s/([_\pL] ) +(?=\w)| /$1/g

```

Try it online!

This replaces any letter or underscore + space combo, which is followed by letter, digit or underscore, by itself, and removes any other space. In effect, it keeps any space which is proceeded by a letter or an underscore, and is followed by a letter, digit or underscore, and removes any other space. The `(?=\w)` is a lookahead, and won't be consumed by the matcher; this makes cases like `_ _ _ _ _` keep all the spaces.

This will not work correctly for input containing characters outside of the ASCII range.
> 3 votes

# Answer
# Charcoal, 41 bytes

```
≔ωη≔ωζＦθ≡ι ≔ηζ«×ζ№⁺_⭆⁶²⍘κφιι≔ωζ≔× №⁺_α↥ιη

```

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

```
≔ωη

```

Set `h` to the empty string. This variable is a space if the last non-space character was a letter.

```
≔ωζ

```

Set `z` to the empty string. This variable is a space if the last character was a space and the last non-space character was a letter.

```
Ｆθ

```

Loop over the characters of the input.

```
≡ι ≔ηζ«

```

If the current character is a space then copy `h` to `z`, otherwise:

```
×ζ№⁺_⭆⁶²⍘κφι

```

If the current character is a letter or digit then output `z`.

```
ι

```

Output the current character.

```
≔ωζ

```

Set `z` to the empty string.

```
≔× №⁺_α↥ιη

```

Set `h` to a space if the current character is a letter, otherwise set it to the empty string.
> 2 votes

# Answer
# Befunge-93, 285 bytes

```
>~:1+!#@_11g\v>>,>>>>0>11p
v #          <>  ^
>:" "-#v_ \1` |
v      <      >      2^
>:"/"`#v_>    >^
v      <
>:"9"`#v_ \2- |
v      <      >" ",,^
>:"@"`#v_^
v      <      >    >,1^
>:"Z"`#v_ >\2-|
v      <      >" ",^
>:"_"-#v_ ^
v      <
>:"`"`#v_^
v      <
>:"z"`#v_ ^
       > ^

```

Try it online!

This is a simple statement machine, using a single 3 valued state (written to position `(1,1)`). The state is `1` if the previous character was a letter or underscore, `2` if the previous character was a space, and the last non-space character was a letter or underscore, and `0` otherwise.

The program reads one character at a time, ending the program if there is no more input; the read character is pushed on the stack. We then push the current state on the stack, and swap the two elements on the stack. We go through a bunch of if/then/else statements, to find out what kind of character we have (digit, letter or underscore, space, other symbol). If the current character is a digit, letter or underscore, and the current state is `2`, we print a space. We then print the current character, unless that character is a space. Finally, we push the new state on the stack, which we then store on position `(1,1)`, and we enter the loop again.
> 2 votes

# Answer
# Jelly, 27 bytes

```
eþØW,ØD¤
+⁹n⁶¤Tị
Ñ>/ŻçµÑSḊç

```

A full program which accepts a Python formatted string of Python code which prints the result.

**Try it online!** (Do note that Jelly evaluates its arguments as Python *before* using them.)

### How?

```
eþØW,ØD¤   - Link 1: list of characters, A          e.g. "_ 5 ;"
       ¤   - nilad followed by link(s) as a nilad:
  ØW       -   word characters                           "A..Za..z0...9_"
     ØD    -   digit characters                          "0...9"
    ,      -   pair                                      ["A..Za..z0...9_, "0...9"]
 þ         - outer product using:
e          -   exists in?                                [[1,0,1,0,0], [0,0,1,0,0]]

+⁹n⁶¤Tị    - Link 2: list of integers, X; list of characters, Y
    ¤      - nilad followed by link(s) as a nilad:
 ⁹         -   chain's right argument, Y
   ⁶       -   the space character
  n        -   not equal? (vectorises)
+          - add (to X)
     T     - truthy (non-zero) indices
      ị    - index into (Y)

Ñ>/ŻçµÑSḊç - Main Link: list of characters, S
Ñ          - call next Link as a monad -> Link_1(S)
  /        - reduce by:
 >         -   is greater than (gives 1s where letters are, 0s elsewhere)
   Ż       - prepend a zero
    ç      - call last Link as a dyad -> Link_2(that, S)
     µ     - start a new monadic Link:  (call that R)
      Ñ    - call next Link as a monad -> Link_1(R)
       S   - sum (gives 1s at letters, 2s at digits, 0s elsewhere)
        Ḋ  - dequeue
         ç - call last Link as a dyad -> Link_2(that, R)
           - implicit print

```

First removes spaces which do not directly follow letters, then removes remaining spaces which are not directly before letters or digits.
> 1 votes

# Answer
# Python 3, 60 bytes

```
lambda s:re.sub(r' +(?=\W)|(?<![a-zA-Z_]) +','',s)
import re

```

Try it online!

Port of Arnauld's JavaScript answer.
> 1 votes

---
Tags: code-golf, python
---


# Question
Title: Make a program for printing a string in my esolang MAWP!
# The task

Given an ascii string, output a program in my esolang MAWP that outputs the inputted string when run.

# Useful functions in MAWP

```
Numbers from 0-9: Pushes the number to stack
M                 Takes the top two numbers off stack and pushes the sum to stack
A                 Takes the top two numbers off stack and pushes the difference to stack (xyA = y-x)
W                 Takes the top two numbers off stack and pushes the multiplied result to stack
P                 Takes the top two numbers off stack and pushes the floored divided result to stack (xyP = yx)
;                 Takes top number off stack and prints it as an ascii char

```

# Test cases

Input: `Hello, World!`

Possible output: `89W;689MWA;269WW;269WW;1278WWA;159WA;48W;699WM;1278WWA;67W89WM;269WW;455WW;148WM;`

Input: `codegolf`

Possible output: `929MW;278WWA;455WW;1689MWA;1849MWA;1278WWA;269WW;689MW;`

# Rules

1. There can be multiple solutions for each symbol, but the length must be minimal: for example, `04M5W5W;` is unacceptable while `45W5W;` is fine.
2. The stack starts with a 1 one it.
3. You may leave something on the stack
4. Your output may not print out other characters other than the string, and all of the character s must be given in the og order.
5. This is code-golf, so lowest byte score wins!

# ASCII table for reference

# Answer
> 4 votes
# JavaScript (Node.js),  ~~276 266~~  263 bytes

*Saved 3 bytes thanks to @KevinCruijssen*

```
i=>[v=[],O='',[...2**29+'4'].map(F=x=>F[v[x]=+x]=x)].map(s=_=>v.map(x=>v.map(y=>[x+y,x*y,y-x].map((z,o)=>(!F[z]&&V.push(z))|(S=~~s[x]-~s[y])<s[z]|S==s[z]&F[x]<2?F[s[z]=S,z]=F[x]+F[y]+'MWA'[o]:0)),V=[])&&v.push(...V))&Buffer(i).map(n=>O+=F[n]+';')||O.replace(1,'')

```

Try it online!

### MAWP interpreter

Here is a simple MAWP interpreter I wrote to check the results.

```
function MAWP(code) {
  let stack = [ 1 ], out = "";

  function assertStkSz(n) { if(stack.length < n) throw "stack error"; }

  [...code].forEach(c => {
    switch(c) {
      case 'M': assertStkSz(2); stack.push(stack.pop() + stack.pop()); break;
      case 'A': assertStkSz(2); stack.push(stack.pop() - stack.pop()); break;
      case 'W': assertStkSz(2); stack.push(stack.pop() * stack.pop()); break;
      case 'P': assertStkSz(2); stack.push(stack.pop() / stack.pop() | 0); break;
      case ';': assertStkSz(1); out += String.fromCharCode(stack.pop()); break;
      default : stack.push(+c); break;
    }
  })
  return out;
}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~151~~ 150 bytes

```
žQÇεÑÅs¸˜2∍DT‹N59‹iPi©'WªëP®P-®„WMJëài`9-Dgi…9MWJ©NUë®NX-'M««]JR•4ñ4₄¬[Ý•5äŽ6þbT„WM‡5äøJ•XDŒ•27вǝεDg46N44‹è‹i©NUëW≠i®NX-ì'A«]"19M29MW"16ǝIÇƵPαè';ý1õ.;

```

Not too happy with the byte-count, but it could be worse..

Try it online or verify all ASCII characters.

**Explanation:**

I first tried to do the mapping of each printable ASCII character (integers in the range \\$\[32,126\]\\$) manually. With this, I've used the following strategy:

1) I've first determined all integers that can be formed by multiplying two single-digit integers:

```
  (32) → 48W
# (35) → 57W
$ (36) → 66W
( (40) → 58W
* (42) → 67W
- (45) → 59W
0 (48) → 68W
1 (49) → 77W
6 (54) → 69W
8 (56) → 78W
? (63) → 79W
@ (64) → 88W
H (72) → 89W
Q (81) → 99W

```

We can add or subtract a single digit from each of these numbers to form all integers in the range \\$\[32,90\]\\$:

```
! (33) → [48W1M] / 257WA
" (34) → 48W2M / [157WA]
% (37) → [66W1M] / 358WA
& (38) → 66W2M / 258WA
' (39) → 66W3M / [158WA]
) (41) → 58W1M / 167WA
+ (43) → [67W1M] / 259WA
, (44) → 67W2M / [159WA]
. (46) → [59W1M] / 268WA
/ (47) → 59W2M / [168WA]
2 (50) → [77W1M] / 469WA
3 (51) → 77W2M / 369WA
4 (52) → 77W3M / 269WA
5 (53) → 77W4M / [169WA]
7 (55) → 69W1M / 178WA
9 (57) → [78W1M] / 679WA
: (58) → 78W2M / 579WA
; (59) → 78W3M / 479WA
< (60) → 78W4M / 379WA
= (61) → 78W5M / 279WA
> (62) → 78W6M / [179WA]
A (65) → [88W1M] / 789WA
B (66) → 88W2M / 689WA
C (67) → 88W3M / 589WA
D (68) → 88W4M / 489WA
E (69) → 88W5M / 389WA
F (70) → 88W6M / 289WA
G (71) → 88W7M / [189WA]
I (73) → [89W1M] / 799WA
J (74) → 89W2M / 799WA
K (75) → 89W3M / 699WA
L (76) → 89W4M / 599WA
M (77) → 89W5M / 499WA
N (78) → 89W6M / 399WA
O (79) → 89W7M / 299WA
P (80) → 89W8M / [199WA]
R (82) → 99W1M
S (83) → 99W2M
T (84) → 99W3M
U (85) → 99W4M
V (86) → 99W5M
W (87) → 99W6M
X (88) → 99W7M
Y (89) → 99W8M
Z (90) → 99W9M

```

3) When there are two options, we want to prioritize the ones containing a digit `1` (since those is already initially on the stack, and we could potentially remove later on). When one of the two numbers contains a `1` I've put it in square-blocks in the list above. If both or neither contain a `1` it's irrelevant which one we choose.

4) Now that everything below 91 is covered, we are left with the integers in the range \\$\[91,126\]\\$.
I first determined all integers which could be formed by one single-digit integer multiplied by a two-digit integer in the range \\$\[10,18\]\\$, since 18 being 9+9 is the highest we could create:

```
[ (91) → 794MW
` (96) → 697MW
b (98) → 795MW
c (99) → 992MW
f (102) → 698MW
h (104) → 894MW
i (105) → 796MW
l (108) → 699MW
p (112) → 797MW
u (117) → 994MW
w (119) → 798MW
~ (126) → 799MW

```

5) And there are also some additional integers which can be formed by using three single digits outside of the ones above, which are edge cases in my program:

```
d (100) → 455WW
x (120) → 869MW
y (121) → 358WW
} (125) → 555WW

```

6) After that, we can use a similar strategy as we did in steps 2 and 3:

```
\ (92) → [794MW1M] / 4268WWA
] (93) → 794MW2M / 3268WWA
^ (94) → 794MW3M / 2268WWA
_ (95) → 794MW4M / [1268WWA]
a (97) → 697MW1M / 1795MWA
e (101) → 455WW1M / 1698MWA
g (103) → 698MW1M / 1894MWA
j (106) → [796MW1M] / 2699MWA
k (107) → 796MW2M / [1699MWA]
m (109) → [699MW1M] / 3797MWA
n (110) → 699MW2M / 2797MWA    *
o (111) → 699MW3M / [1797MWA]
q (113) → [797MW1M] / 4994MWA
r (114) → 797MW2M / 3994MWA
s (115) → 797MW3M / 2994MWA
t (116) → 797MW4M / [1994MWA]
v (118) → 994MW1M / 1798MWA
z (122) → [358WW1M] / 3555WWA
{ (123) → 358WW2M / 2555WWA
| (124) → 358WW3M / [1555WWA]

```

The one with `*` behind it is the only edge case after all these steps, since `19M29MW` can be used that contains a 1, so is potentially shorter than both `699MW2M` and `2797MWA`.

---

As for the actual code to implement these steps and encode the input:

```
žQ                           # Push all printable ASCII characters
  Ç                          # Convert it to an integer list in the range [32,127]
   ε                         # Map each integer to:
    Ñ                        #  Get the divisors of the current integer
     Ås                      #  Get the middle (if it's a square) or middle two integers
       ¸˜2∍                  #  If it's a square, duplicate that integer
                             #  (so we only have pairs of integers now)
    D                        #  Duplicate the pair
     T‹                      #  Check for both whether they're a single digit (<10):
       y91‹i                 #  If the integer we're mapping over is below 91:
            Pi               #   If both values in the pair are a single digit:
              ©              #    Store the pair in variable `®` (without popping)
               'Wª          '#    And append a "W" to the list
             ë               #   Else:
              P              #    Pop and take the product of the duplicated pair
               ®P            #    Take the product of pair `®` as well
                 -           #    Subtract them from one another
              ®              #    Push pair `®`
              „WM            #    Push string "WM"
                 J           #    Join the pair together, and then all three together
           ë                 #  Else (the integer we're mapping over is above 90):
            ài               #   If either of the two integers is a single digit:
              `              #    Push both separated to the stack
               9-            #    Subtract 9 from the larger 2-digit integer
                 Dgi         #    If it's now a single digit:
                    …9MW     #     Push string "9MW"
                        J    #     And join all three together
                         ©   #     Store this in variable `®` (without popping)
                          NU #     And store the map-index in variable `X`
                   ë         #    Else:
                    ®        #     Push the string from variable `®`
                     N       #     Push the current map-index
                      X-     #     Subtract the saved map-index of `X`
                        'M  '#     Push an "M"
                          «« #     Join the three together
   ]                         # Close all if-statements and map
    J                        # Join each inner list together to a single string

```

We now have the following list:

```
["48W","148WM","248WM","57W","66W","166WM","266WM","366WM","58W","158WM","67W","167WM","267WM","59W","159WM","259WM","68W","77W","177WM","277WM","377WM","477WM","69W","169WM","78W","178WM","278WM","378WM","478WM","578WM","678WM","79W","88W","188WM","288WM","388WM","488WM","588WM","688WM","788WM","89W","189WM","289WM","389WM","489WM","589WM","689WM","789WM","889WM","99W","199WM","299WM","399WM","499WM","599WM","699WM","799WM","899WM","999WM","749MW","749MW1M","749MW2M","749MW3M","749MW4M","839MW","839MW1M","759MW","929MW","1010","929MW2M","689MW","689MW1M","849MW","769MW","769MW1M","769MW2M","939MW","939MW1M","1011","939MW3M","859MW","859MW1M","859MW2M","859MW3M","859MW4M","949MW","949MW1M","789MW","1012","1111","789MW3M","789MW4M","789MW5M","789MW6M","959MW"]

```

As you can see, it contains some errors like `"1010","1011","1012","1111"` for the edge cases \[100,110,120,121\] respectively as discussed earlier, which could be `"455WW","869MW","358WW","555WW"` instead; `"789MW6M"` for 125, which could be `"555WW"` instead; and `"789MW3M"` for 122, which could be `"358WW1M"` instead. So we fix those edge cases manually (except for `"1011"` since we already fix that edge case at the very end anyway):

```
R                            # Reverse the list
 •4ñ4₄¬[Ý•                   # Push compressed integer 1358555358869455
          5ä                 # Split it into 5 equal-size parts: [1358,555,358,869,455]
 Ž6þ                         # Push compressed integer 1783
    b                        # Convert it to binary: 11011110111
     T„WM‡                   # Transliterate "10" to "WM": "WWMWWWWMWWW"
          5ä                 # Also split it into 5 equal-size parts:
                             #  ["WWM","WW","WW","MW","WW"]
 ø                           # Pair the two lists together
  J                          # And join each inner pair together:
                             #  ["1358WWM","555WW","358WW","869MW","455WW"]
•XDŒ•                        # Push compressed integer 2149280
     27в                     # Convert it to base-27 as list: [4,1,5,6,26]
ǝ                            # Insert the strings at those indices in the reversed list

```

Then we'll change every case with `...2M` or higher to `x...A`:

```
ε                            # Map each string to:
 Dg                          #  Get the length (without popping by duplicating first)
     N44‹                    #  Check if the map-index is below 44
                             #  (1 if truthy; 0 if falsey)
   46    è                   #  Use it to index into 46 (6 if truthy; 4 if falsey)
          ‹i                 #  If the length is smaller than that:
            ©                #   Store the current string in variable `®`
             NU              #   And the map-index in variable `X`
           ë                 #  Else:
            W                #   Get the smallest digit (without popping)
             ≠i              #   If it's NOT 1:
               ®             #    Push the string of variable `®`
                NX-          #    Push the map-index and subtract `X`
                   ì         #    Prepend this digit in front of the string
                    'A«     '#    And append an "A"
]                            # Close the if-statements and map

```

We now have the following (still reversed!) list:

```
["959MW","555WW","1555WWA","2555WWA","1358WWM","358WW","869MW","789MW","949MW1M","949MW","1949MWA","2949MWA","3949MWA","859MW1M","859MW","1859MWA","1011","939MW1M","939MW","1939MWA","769MW1M","769MW","849MW","689MW1M","689MW","1689MWA","455WW","929MW","759MW","839MW1M","839MW","1839MWA","2839MWA","3839MWA","749MW1M","749MW","999WM","899WM","799WM","699WM","599WM","499WM","399WM","299WM","199WM","99W","199WA","299WA","399WA","499WA","599WA","699WA","799WA","189WM","89W","189WA","289WA","389WA","489WA","589WA","689WA","188WM","88W","79W","179WA","279WA","379WA","479WA","579WA","178WM","78W","169WM","69W","169WA","269WA","369WA","177WM","77W","68W","168WA","159WM","59W","159WA","167WM","67W","158WM","58W","158WA","258WA","166WM","66W","57W","157WA","148WM","48W"]

```

Fix the final test case as discussed earlier:

```
"19M29MW"                    # Push string "19M29MW"
         16ǝ                 # And insert it at index 16

```

And then convert the input using this finished (still reversed) list:

```
I                           # Push the input-string
 Ç                          # Convert each character to its codepoint integer
  ƵP                        # Push compressed integer 126
    α                       # Take its absolute difference with each codepoint integer
     è                      # Index those into the list we created
      ';ý                  '# Join them together with a ";" delimiter
         1õ.;               # And remove the very first "1"
                            # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•4ñ4₄¬[Ý•` is `1358555358869455`; `Ž6þ` is `1783`; `•XDŒ•` is `2149280`; `•XDŒ•27в` is `[4,1,5,6,26]`; and `ƵP` is `126`.

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


# Question
Title: List of programming languages that can run code at runtime
What all languages have a construct similar to python's `eval`, so you can write code during runtime and run it?

A list would be helpful for certain programming challenges - ones where it is obvious an `eval` is either necessary or highly efficient.

# Answer
A few I recall:

* Lua: `loadstring("2 + 2")`
* \*Script (Coffee, Java, Type, Action): `eval("2 + 2")`
* Erlang / Elixir: `Code.eval_string("a + b", [a: 2, b: 2], file: __ENV__.file, line: __ENV__.line)`
* J: `". '2 + 2'` (eval it right away) or `3 : '2 + 2'` (define a function; `(3 : '2 + 2') 0` runs it)
* Ruby: `eval "2 + 2"`
* Perl: `eval "2 + 2"`
* Bash: `a="ls | wc -l"`, `eval $a`
* PHP: `eval("2 + 2")`
* Lisp, obviously: `(setq test'(+ 2 2))` and `(eval test)`
* Python: `eval('2 + 2')`
* ColdFusion: `<cfset x = "int(2+2)">` and `<cfset y = Evaluate(x)>`
* FORTH: `S" 2 2 + ." eval` (note: it depends on the implementation; most use either `EVALUATE` or `eval`)
* VBScript, VBA: `Execute('2 + 2')` (note: for VBA as far as I recall, it's `eval`)
* Smalltalk: `Compiler evaluate:'2 + 2'`
* APL: The  primitive executes a character vector that contains a valid APL expression: `⍎ '2×3'` or `⍎ 'S←A String'`. The former will execute the mathematical expression and return `6`; the latter will create a variable `S` in the APL workspace, and assign it the value A String
* PowerShell: `invoke-expression '2 + 2'`
* R: `eval(parse(text = "2 + 2"))`
* Io: `doString("2 + 2")`
* Burlesque: `"2 2.+"pe`

Other languages:

* Java: see `ScriptEngine` functionality.
* C, C++: they can execute shellcode
* D: via `mixin`s, `int a = 0;` and then `mixin("a = 2 + 2;");` (note: the string must be constant and known at the compile time)
> 7 votes

---
Tags: tips
---