title: Turn-based RPS Poker

text:
# Question
Title: Turn-based RPS Poker
This is a two-player card game which resembles a vastly simplified game of Texas Hold'em, combined with RPS (rock-paper-scissors) and the most basic mechanic of commercial turn-based card games.

## The deck

A single full deck consists of 30 unique cards, where each card has one symbol out of `RPS` and one number between 0 and 9 inclusive. Each card is referred to as a 2-char string like `R0` or `S3` (symbol, then number).

Since the 30-card deck is divided into three smaller decks during the game, let's call the 30-card deck a *full deck* (as opposed to simply *deck*).

## The match

A single match consists of two phases: Draft phase and Main phase. In the Draft phase, the two players' decks (10 cards each) are decided. In the Main phase, actual games of Poker are played, and each player gets some score based on the number of games won.

**Draft phase**

1. The full deck of 30 cards is shuffled.
2. Repeat five times:
    1. Each player is given two cards from the top of the full deck.
    2. Each player selects one of them, which will go into their own deck.
    3. Each player gives the unselected card to their opponent.

At the end of Draft phase, players A and B have a deck of 10 cards each, and the main deck has 10 cards remaining. Additionally, each player gets to know 5 of the 10 cards in the opponent's deck during the process.

**Main phase**

1. Each deck (player's and the remaining) is shuffled.
2. Each player draws three cards from their own deck.
3. Repeat 10 times:
    1. A card (called *base card*) is shown from the remaining deck.
    2. Each player plays a card from their own hand.
    3. A winner is determined by comparing (A's play + base) to (B's play + base). The winner gains 1 point.
    4. Each player draws a card from their own deck (unless there's nothing to draw).

## Deciding the winner of a single game

The winner is decided by comparing the two-card combinations in the following order:

1. If one combination is a pair (two cards sharing a number) and the other is not, a pair always wins against a non-pair.
2. If the two cards played (excluding the base card) have different numbers, the player who played a higher-numbered card wins.
3. Otherwise, the two cards are compared under the RPS rules. R wins against S, S wins against P, and P wins against R.

Note that a draw is not possible since every card is unique in a deck.

## Bots and the controller

An answer should include a single bot that can handle the Draft phase and the Main phase.

The controller code is here, with three example bots.

A bot has the following structure:

```
{
  name: 'MinimalValid',
  draftPick(cards) { return 0; },
  draftReceive(card) {},
  mainPlay(cards, base) { return 0; },
  mainPostprocess(card) {},
},

```
* `name`: The name of the bot, a string.
* `draftPick`: Called when the bot is given two cards to choose from during the draft phase (2-2).
    + Input: an array of cards to choose from
    + Output: a valid index in the array of cards
* `draftReceive`: Called to inform the "unselected-by-opponent" card to the bot (2-3).
    + Input: a single card
    + Output: nothing
* `mainPlay`: Called when the bot plays a card during the main phase (3-2).
    + Input: the hand (an array of cards), the base card
    + Output: a valid index in the hand
* `mainPostprocess`: Called to inform the card played by the opponent.
    + Input: a single card
    + Output: nothing

A slightly better bot to illustrate how to keep state in `this`:

```
{
  name: 'Simple',
  myDeck: new Set(),
  draftPick(cards) {
    let cardId = cards[0][1] < cards[1][1] ? 1 : 0;
    this.myDeck.add(cards[cardId]);
    return cardId;
  },
  draftReceive(card) {
    this.myDeck.add(card);
  },
  mainPlay(cards, base) {
    this.myDeck.delete(cards[0]);
    return 0;
  },
  mainPostprocess(card) {
  },
},

```

A bot is immediately disqualified by the controller if it throws an exception or returns an invalid index. A submission is also invalid if it tries to cheat the controller in any way.

Given multiple bots, the controller will run round-robin matches. The entire cycle will be run multiple times (exact number depends on the number of submissions) and all scores will be accumulated to decide the overall winner.

The deadline is **00:00 UTC on June 18, 2021**. ~~If we don't have 10 submissions (excluding the two example bots) until then, the deadline will be extended by a week until we do.~~ The winning answer will be accepted at that point.

The winner is **Basic Odds** by MegaTom. Congratulations!

You can still submit new bots even though the competition is officially over. (assuming I am active) I will run a new round and update the leaderboard. The accepted answer will not change even if the winner changes after the deadline.

The two bots presented here will be included when running the matches.

## Leaderboard

The following is the total scores after 100 rounds.

```
1. BasicOdds     2500
2. ObviousStrats 2336
3. tsh           2016
4. Simple        1916
5. MinimalValid  1232

```

# Answer
> 3 votes
# Basic Odds

This bot takes high cards, then, using its information on the game state, will calculate the chance of winning now, and on a random future round. Whichever card has the highest difference between those numbers will be played.

```
{
  name: 'BasicOdds',
  selfCards: new Set(),
  opponentCards: new Set(),
  otherCards: new Set(),
  isWinner(self, opponent, base = '') {
    if (self[1] === base[1] && opponent[1] !== base[1]) return true;
    if (self[1] !== base[1] && opponent[1] === base[1]) return false;
    if (self[1] > opponent[1]) return true;
    if (self[1] < opponent[1]) return false;
    if ('RSPR'.includes(self[0] + opponent[0])) return true;
    return false;
  },
  draftPick(cards) {
    if (this.otherCards.size === 0) {
      fullDeck.forEach(card => { this.otherCards.add(card); });
      this.selfCards.clear();
      this.opponentCards.clear();
      this.start = false;
    }
    this.otherCards.delete(cards[0]);
    this.otherCards.delete(cards[1]);
    if (this.isWinner(cards[0], cards[1])){
      this.selfCards.add(cards[0]);
      this.opponentCards.add(cards[1]);
      return 0;
    } else {
      this.opponentCards.add(cards[0]);
      this.selfCards.add(cards[1]);
      return 1;
    }
  },
  draftReceive(card) {
    this.selfCards.add(card);
    this.otherCards.delete(card);
  },
  mainPlay(cards, base) {
    this.otherCards.delete(base);
    let values = cards.map((card,i)=>{
      let winnings = 0;
      this.otherCards.forEach(oc=>{
        winnings += +this.isWinner(card, oc, base);
      })
      winnings *= (this.selfCards.size - this.opponentCards.size) / this.otherCards.size;
      this.opponentCards.forEach(oc=>{
        winnings += +this.isWinner(card, oc, base);
      })
      let futureWinnings = 0;
      let m1 = (this.otherCards.size - this.selfCards.size + this.opponentCards.size) / this.otherCards.size;
      let m2 = m1 * (this.selfCards.size - this.opponentCards.size) / (this.otherCards.size - 1);
      this.otherCards.forEach(newBase=>{
        this.opponentCards.forEach(oc=>{
          futureWinnings += (+this.isWinner(card, oc, newBase)) * m1;
        })
        this.otherCards.forEach(oc=>{
          if(oc !== newBase){
            futureWinnings += (+this.isWinner(card, oc, newBase)) * m2;
          }
        })
      });
      return [winnings - futureWinnings/(this.selfCards.size-1), i];
    })
    let bestIndex = values.reduce((r, a) => (a[0] > r[0] ? a : r))[1];

    this.selfCards.delete(cards[bestIndex]);
    return bestIndex;
  },
  mainPostprocess(card) {
    this.otherCards.delete(card);
    this.opponentCards.delete(card);
  },
}

```

Credit to Spitemaster for the code he got from tsh, that I based this off of.

# Answer
> 2 votes
# ObviousStrats

```
{
  name: 'ObviousStrats',
  selfCards: new Set(),
  opponentCards: new Set(),
  otherCards: new Set(),
  isWinner(self, opponent, base = '') {
    if (self[1] === base[1] && opponent[1] !== base[1]) return true;
    if (self[1] !== base[1] && opponent[1] === base[1]) return false;
    if (self[1] > opponent[1]) return true;
    if (self[1] < opponent[1]) return false;
    if ('RSPR'.includes(self[0] + opponent[0])) return true;
    return false;
  },
  draftPick(cards) {
    if (this.otherCards.size != 30) {
      fullDeck.forEach(card => { this.otherCards.add(card); });
      this.selfCards.clear();
      this.opponentCards.clear();
    }
    if (this.isWinner(cards[0], cards[1])){
      this.selfCards.add(cards[0]);
      this.opponentCards.add(cards[1]);
      return 0;
    } else {
      this.opponentCards.add(cards[0]);
      this.selfCards.add(cards[1]);
      return 1;
    }
  },
  draftReceive(card) {
    this.selfCards.add(card);
  },
  mainPlay(cards, base) {
    this.otherCards.delete(base);
    let match = cards.findIndex(card => card[1] == base[1]);
    if (match > -1){
        this.selfCards.delete(cards[match]);
        return match;
    }
    const opponentMatch = [...this.opponentCards].findIndex(card => card[1] == base[1]);
    if (opponentMatch > -1){
        const minValue = Math.min(...cards.map(card => parseInt(card[1])));
        match = cards.findIndex(card => +card[1] == minValue);
        this.selfCards.delete(cards[match]);
        return match;
    }
    const maxValue = Math.max(...cards.map(card => +card[1]));
    match = cards.findIndex(card => card[1] == maxValue);
    this.selfCards.delete(cards[match]);
    return match;
  },
  mainPostprocess(card) {
    this.otherCards.delete(card);
    this.opponentCards.delete(card);
  },
}

```

ObviousStrats doesn't over-complicate things. When drafting, it picks the card that would win if played against the other. When playing, it plays a pair, its lowest card if it knows its opponent has a pair, and otherwise its highest card.

Thanks tsh for the base code!

# Answer
> 1 votes
```
{
  name: 'tsh',
  /** @typedef {'R0'|'R1'|'R2'|'R3'|'R4'|'R5'|'R6'|'R7'|'R8'|'R9'|'P0'|'P1'|'P2'|'P3'|'P4'|'P5'|'P6'|'P7'|'P8'|'P9'|'S0'|'S1'|'S2'|'S3'|'S4'|'S5'|'S6'|'S7'|'S8'|'S9'} Card */
  /** @type {Set<Card>} */
  selfCards: new Set(),
  /** @type {Set<Card>} */
  opponentCards: new Set(),
  /** @type {Set<Card>} */
  otherCards: new Set(),
  /**
   * @param {Card} self
   * @param {Card} opponent
   * @param {Card} base
   */
  isWinner(self, opponent, base = '') {
    if (self[1] === base[1] && opponent[1] !== base[1]) return true;
    if (self[1] !== base[1] && opponent[1] === base[1]) return false;
    if (self[1] > opponent[1]) return true;
    if (self[1] < opponent[1]) return false;
    if ('RSPR'.includes(self[0] + opponent[0])) return true;
    return false;
  },
  /**
   * @param {Card} card
   * @returns number
   */
  scoreCard(card, deckRatio) {
    const sameNum = [...this.selfCards].filter(c => c[1] === card[1]);
    const otherSameNum = [...this.otherCards].filter(c => c[1] === card[1]);
    const largeThanOpponent = [...this.opponentCards].filter(c => c[1] < card[1]).length * 0.1;
    const cardValue = parseInt(card[1], 10) + largeThanOpponent + 0.5;
    if (otherSameNum.length === 0) {
      return cardValue - 1 + largeThanOpponent;
    } else if (otherSameNum.length === 1) {
      const cardWin = !this.isWinner(card, otherSameNum[0]);
      if (cardWin) {
        return 10 * deckRatio + cardValue * (1 - deckRatio);
      } else if (sameNum.length === 1) {
        return 0 * deckRatio + (cardValue - 1) * (1 - deckRatio);
      } else {
        return cardValue - 1;
      }
    } else {
      return (9 + cardValue) * deckRatio * (1 - deckRatio) / 2 +
        10 * deckRatio ** 2 +
        cardValue * (1 - deckRatio) ** 2;
    }
  },
  /**
   * @param {Card} card
   * @returns number
   */
  scorePickCard(card) {
    return this.scoreCard(card, 10 / this.otherCards.size);
  },
  /**
   * @param {Card} card
   * @param {Card} base
   * @returns number
   */
  scorePlayCard(card, base) {
    const selfWin = [...this.opponentCards, ...this.otherCards]
      .every(c => this.isWinner(card, c, base));
    if (selfWin) return Infinity;
    const knownWin = [...this.opponentCards]
      .filter(c => this.isWinner(card, c, base)).length /
      (this.selfCards.size + 1);
    const deckRatio = this.selfCards.size / this.otherCards.size;
    return this.scoreCard(card, deckRatio) + knownWin;
  },
  /**
   * @param {[Card, Card]} cards
   * @returns 0|1
   */
  draftPick(cards) {
    if (!this.otherCards.size) {
      fullDeck.forEach(card => { this.otherCards.add(card); });
      this.selfCards.clear();
      this.opponentCards.clear();
    }
    cards.forEach(card => this.otherCards.delete(card));
    const scores = cards.map(c => this.scorePickCard(c));
    if (scores[0] > scores[1]) {
      this.selfCards.add(cards[0]);
      this.opponentCards.add(cards[1]);
      return 0;
    } else {
      this.opponentCards.add(cards[0]);
      this.selfCards.add(cards[1]);
      return 1;
    }
  },
  /**
   * @param {Card} card
   */
  draftReceive(card) {
    this.selfCards.add(card);
  },
  /**
   * @param {[Card, Card]} cards
   * @param {Card} base
   * @returns number
   */
  mainPlay(cards, base) {
    this.otherCards.delete(base);
    const opponentWin = [...this.opponentCards].some(o => (
      [...this.selfCards].every(m => !this.isWinner(m, o, base))
    ));
    const scores = cards.map(card => {
      const score = this.scorePlayCard(card, base);
      if (opponentWin) return -score;
      return score + 10 * (card[1] === base[1]);
    });
    const index = scores.indexOf(Math.max(...scores));
    this.selfCards.delete(cards[index]);
    return index;
  },
  /**
   * @param {Card} card
   */
  mainPostprocess(card) {
    this.otherCards.delete(card);
    this.opponentCards.delete(card);
  },
}

```

Try it online!

It cost so many bytes, but only *somehow* better than Simple... Don't know how to name it, so, whatever...

Anyone may try to build your own bot based on this one if it could be helpful.

---
Tags: king-of-the-hill, javascript, card-games
---


title: Italicize ASCII art

text:
# Question
Title: Italicize ASCII art
Given an input of an ASCII art picture, output the ASCII art italicized.

To italicize the ASCII art:

1. Insert zero spaces before the last line, one space before the second-last line, two spaces before the third-last line, etc.
2. Remove any extra leading whitespace that may have been created. That is, if each line has at least `n` spaces preceding it, remove `n` spaces from the beginning of each line.
3. Replace all `\`s with `|`, all `|`s with `/`, and all `/`s with `_`. Keep existing `_`s the same.

The input is guaranteed to contain only the characters `\|/_` and space.

For example, the input

```
/\/\/\    /\/\/\      /\/\/\    /\/\/\
 /\    /\  /\    /\  /\        /\
  /\/\/\    /\/\/\    /\        /\  /\/\
   /\        /\        /\        /\    /\
    /\        /\          /\/\/\    /\/\/\

```

must output

```
_|_|_|    _|_|_|      _|_|_|    _|_|_|
_|    _|  _|    _|  _|        _|
_|_|_|    _|_|_|    _|        _|  _|_|
_|        _|        _|        _|    _|
_|        _|          _|_|_|    _|_|_|

```

which in turn, provided as input, outputs

```
    _/_/_/    _/_/_/      _/_/_/    _/_/_/
   _/    _/  _/    _/  _/        _/
  _/_/_/    _/_/_/    _/        _/  _/_/
 _/        _/        _/        _/    _/
_/        _/          _/_/_/    _/_/_/

```

which would output

```
        ______    ______      ______    ______
      __    __  __    __  __        __
    ______    ______    __        __  ____
  __        __        __        __    __
__        __          ______    ______

```

Input and output may be either a single string (with optional trailing newline) or an array of lines.

Since this is , the shortest code in bytes will win.

Extra test cases:

```
|||||
  /////
 \\\\\
   _____

```

```
 /////
  _____
|||||
 _____

```

```
________

```

```
________

```

(that is, input of empty string results in output of empty string)

# Answer
> 6 votes
## CJam, ~~43~~ 38 bytes

```
qN/W%eeSf.*:sW%z_{S-}#>zN*"\|/__"_(+er

```

Requires the input to be padded to a rectangle.

Try it online!

### Explanation

```
qN/     e# Read input, split into lines.
W%      e# Reverse lines.
ee      e# Enumerate them (pairing each line with its index starting from 0).
Sf.*    e# Turn each index i into i spaces.
:s      e# Flatten each pair into a single string, prepending the spaces.
W%      e# Reverse the lines again.
z_      e# Transpose the character grid, duplicate it.
{S-}#   e# Find the first row index that contains non-spaces.
>       e# Discard that many rows.
zN*     e# Transpose back and join with linefeeds.
"\|/__" e# Push this string.
_(+     e# Make a copy that's rotated one character to the left, i.e. "|/__\".
er      e# Perform character transliteration mapping from the first string to the second.

```

# Answer
> 4 votes
# MATL, ~~38~~ ~~33~~ 29 bytes

```
P"NZ"@Y:'\|/' '|/_'XEh]XhPcYv

```

Output lines have trailing spaces to match the longest line (this is allowed by the challenge).

Input is a cell array (list) of strings. The array uses curly braces, and strings use single quotes, as follows (click each link to *Try it online!*).

* First example:

```
{'/\/\/\    /\/\/\      /\/\/\    /\/\/\'  ' /\    /\  /\    /\  /\        /\'  '  /\/\/\    /\/\/\    /\        /\  /\/\' '   /\        /\        /\        /\    /\' '    /\        /\          /\/\/\    /\/\/\'}

```
* Second example:

```
{'_|_|_|    _|_|_|      _|_|_|    _|_|_|' '_|    _|  _|    _|  _|        _|      ' '_|_|_|    _|_|_|    _|        _|  _|_|' '_|        _|        _|        _|    _|' '_|        _|          _|_|_|    _|_|_|'}

```
* Third example:

```
{'    _/_/_/    _/_/_/      _/_/_/    _/_/_/' '   _/    _/  _/    _/  _/        _/       ' '  _/_/_/    _/_/_/    _/        _/  _/_/  ' ' _/        _/        _/        _/    _/   ' '_/        _/          _/_/_/    _/_/_/    '}

```

### Explanation

The array is initially flipped. Each string is processed in a loop and the modified string is pushed onto the stack. Processing consists in replacing the characters and appending a number of spaces. The number of spaces equals the current number of elements in the stack (thanks to the fact that the array has been flipped).

After the loop the strings are collected in an array, which is flipped back, converted to a 2D char array, and disposed of unwanted leading spaces: leading spaces that are present in all rows of the 2D char array.

```
P             % implicitly input cell array of strings. Flip it (reverse order)
"             % for each
  NZ"         %   string with as many spaces as elements there are on the stack
  @Y:         %   push current input string
  '\|/'       %   push string: origin for replacement
  '|/_'       %   push string: target for replacement
  XE          %   replace
  h           %   concatenate string with spaces and modified-character string
]             % end for each
Xh            % collect all processed strings in a cell array
P             % flip back to restore original order
c             % convert to 2D char array
Yv            % remove trailing spaces common to all rows. Implicitly display

```

# Answer
> 4 votes
# Pyth, 32

```
jCf|Z=Z-Td.t_.e+*kd.rb"\|/__"_Qd

```

Try it here or run the Test Suite

Each line has several trailing spaces. This works by applying `.r` which is the rotation built-in to each line of the string. The rotation takes each character in the string that matches one in the other argument `"\|/__"` and replaces it with the next character. The double underscore nicely prevents underscores from becoming backslashes. The strings are also padded based on their index.

Once that is done, the lines are zipped together, then we filter out each column that only contains spaces, until one of them doesn't. Then we unzip and join on newlines.

# Answer
> 2 votes
# Dyalog APL (older versions), ~~23~~ 48 bytes

Adjusting whitespace is expensive:

```
{{⍵↓⍨0,⌊/+/∧\' '=⍵}(⍳≢⍵)⌽'|/ _'['\| '⍳(∊,⊢,∊)⍵]}

```

This requires `⎕ML←0`, which was default until recently.

# Answer
> 2 votes
## JavaScript (ES6), ~~171~~ ~~149~~ 148 bytes

```
a=>a.map(s=>(t=' '.repeat(--i)+s,l=t.match` *`[0].length,n=l<n?l:n,t),n=i=a.length).map(s=>s.slice(n).replace(/./g,c=>"|/__ "["\\|/_ ".indexOf(c)]))

```

Accepts and returns lines as an array of strings.

Edit: Saved 22 bytes thanks to @user81655. Saved 1 byte by realising that the input is limited to the 5 characters `\|/_` and space.

# Answer
> 2 votes
# Vyxal, `a` ~~39~~ 37 bytes

-2 thanks to @Aaron Miller

```
ṘėṘƛt`\|/``|/_`Ŀnh$꘍;:ƛ`^ *`$et;g£ƛ¥ȯ

```

Really bad answer, id like to fix it; the program takes in the string, breaks it into chunks, transliterates to the correct characters, and then spends most of the chars trying to fix the spacing.

Try it Online!

# Answer
> 1 votes
# Pip `-rl`, ~~39~~ ~~38~~ ~~37~~ 36 bytes

*How do you golf an elephant? One byte at a time...*

```
YsXRV,#g.:gWw~=@ZyY@>*yyTR"\|/""|/_"

```

Try it online!

# Answer
> 1 votes
# Jelly, 32 bytes

```
JU⁶ẋ$;¥"µEƤS$€Ṃ$‘ṫ€@µ“\|/“|/_”yⱮ

```

Try it online!

The number in STDIN just indicates how many times italicization will be run (for easier testing). Set it to 1 for normal execution.

# Answer
> 0 votes
# Stax, 24 bytes

```
╦'Fi╘◘¥╘τ9jq'∟w7#ù╢→↨↨─╟

```

Run and debug it

Takes a list of lines as input. They are formatted as ascii codepoints for convenience, but you can still pass a list of strings directly.

# Answer
> 0 votes
# Python 3.8 (pre-release), 84 bytes

```
def f(s):
 i=len(s)
 for x in s:print(' '*i+x.translate({92:124,124:47,47:95}));i-=1

```

Try it online!

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


title: I'm Lazy*: Top-left align my text

text:
# Question
Title: I'm Lazy*: Top-left align my text
* and don't have a word processor with top-left align support :D

Take several lines of input, with at least four unique characters of your choice including newline and space. The input can also be taken as a space-padded matrix of characters. Squash it upwards, then squash it left. Output this, with any amount of trailing newlines and spaces.

## To squash upwards

For any non-space character "below" a space, swap their places, until there are no more non-space characters below spaces.

## To squash left

For each line, remove all spaces.

## Example (with `abcdefghjkl \n`):

With the input (STDIN, function arguments, etc.):

```
a b c d  e
ff ggg h i
 jj kk lll

```

Squash upwards:

```
afbgcgdhle
fjj gk l i
    k    l

```

Squash left:

```
afbgcgdhle
fjjgkli
kl

```

Output this text. (STDOUT, function return value, etc.)

## More examples

```
input
=>
output
-------
a b c
=>
abc
-------
a

c
=>
a
c
-------

=>
------- ^ note that trailing spaces are allowed so a single line with a space is valid here
a
=>
a
-------

 a
=>
a
-------
ab
c
=>
ab
c
-------
abc
d e
f g
=>
abc
de
fg
-------
abc
d
f g
=>
abc
dg
f
```

---

This is , shortest answer in bytes per language wins.

---

Finding out which academic journal requires submissions to be top-left aligned is left as an excercise for the reader.

# Answer
# APL (Dyalog Unicode), 11 bytes

```
~∘' '⍤1∘⍉⍣2

```

Try it online!

A train taking and returning a character matrix.

```
         ⍣2  ⍝ repeat 2 times:
        ⍉    ⍝ transpose the character matrix
~∘' '        ⍝ remove spaces
     ⍤1      ⍝ in each row
             ⍝ each row is padded with spaces to keep the matrix shape

```

---

# APL (Dyalog Extended), 8 bytes

-2 bytes thanks to Bubbler!

In the extended variant  provides easy access to the *dfns* namespace, which has a function to **d**rop **a**ll **b**lanks.

```
⌂dab∘⍉⍣2

```

Try it online!
> 9 votes

# Answer
# Jelly, 5 bytes

```
Zḟ€⁶Z

```

Try it online!

```
Zḟ€⁶Z  Main Link
Z      Transpose the matrix
 ḟ     Filter out
  €    From each row
   ⁶   Spaces
    Z  Transpose the matrix

```
> 8 votes

# Answer
# , 14 bytes

```
-.&' '"1@|:^:2

```

Try it online!

Not surprising, but what I came up with is almost identical to ovs's APL approach.

## how

Transpose `|:` and remove spaces `-.&' '` on each line `"1` two times `^:2`.
> 6 votes

# Answer
# Python 3, 68 bytes

```
lambda x,g=lambda x:[sorted(r,key=' '.find)for r in zip(*x)]:g(g(x))

```

Try it online!

-15 bytes thanks to dingledooper
> 5 votes

# Answer
# Red, 108 bytes

```
func[x][loop 2[x: collect[while[x/1/1][keep pad trim/all form collect[forall x[keep take x/1]]length? x]]]x]

```

Try it online!

Takes input and returns output as a series of strings space-padded to equal length.
> 5 votes

# Answer
# MATL, 7 bytes

```
,c!Z{Xz

```

Try it online! Or verify all test cases.

Input is a char matrix (rectangular char array).

### Explanation

```
,      % Do twice
  c    %   Convert to char. The first time this takes the input (implicit),
       %   and does nothing because the input is already a char matrix. The second
       %   time this transforms the cell array of char vectors at the top of the
       %   stack into a char matrix, right-padding each line with space
  !    %   Transpose
  Z{   %   Convert char matrix into cell array of its rows
  Xz   %   Remove space from each char vector contained in that cell array
       % End (implicit)
       % Display (implicit)

```
> 4 votes

# Answer
# Japt, 6 bytes

```
Õ¸¬Õ¸¬

```

Try it

```
Õ¸¬Õ¸¬     :Implicit input of string
Õ          :Transpose
 ¸         :Split on spaces
  ¬        :Join
   Õ¸¬     :Repeat

```

# Japt `-h`, 6 bytes

```
2Æ=Õ¸¬

```

Try it

```
2Æ=Õ¸¬     :Implicit input of string U
2Æ         :Map the range [0,2)
  =        :  Reassign to U
   Õ       :  Transpose
    ¸      :  Split U on spaces
     ¬     :  Join
           :Implicit output of last element

```
> 4 votes

# Answer
# K (ngn/k), 14 bytes

```
2{{x@<^x}'+x}/

```

Try it online!

* `2{...}/` set up a do-reduce, running the code in `{...}` twice
    + `{...}'+x` call the nested `{...}` with each item of the transposed input
        - `{x@<^x}` shuffle spaces to the end
> 4 votes

# Answer
# 05AB1E, 6 bytes

Input and output is a list of lists of characters.

```
2FζðδK

```

Try it online! or Try all cases!

`2F` iterate two times:
`ζ` tranpose the list of lists, padding shorter lists with spaces
`ðδK` remove all spaces
> 3 votes

# Answer
# C (gcc), ~~197~~ \\$\cdots\\$ ~~181~~ 180 bytes

Saved a byte thanks to a stone arachnid!!!
Saved 4 bytes thanks to ceilingcat!!!

```
#define F for(i=0;i<l;)for(j=0,p=t[i++];*p;++p,++j)if(*p<33)for(k
i;j;k;f(t,l,p,q)char**t,*p,*q;{F=i;q=t[k]+j,k<l;)k+=*q-32?*p=*q,*q=32,l:1;F=0,q=p;!k**++q;)*q-32?*p=*q,k=*q=32:0;}

```

Try it online!
> 3 votes

# Answer
# Vyxal `aj`, 7 bytes

```
2(ÞTȧvṅ

```

Try it Online! (Test cases!)

```
2(ÞTȧvṅ
2(         Repeat twice:
  ÞT        Transpose
    ȧ       Remove whitespace
     vṅ     Join sublists on empty string

```
> 3 votes

# Answer
# Factor \+ `combinators.extras`, 62 bytes

```
[ [ flip [ [ 32 = ] partition prepend ] map ] twice "\n"join ]

```

Try it online!

It's a quotation that accepts a matrix of characters/list of strings from the data stack as input and leaves a string on the data stack as output.

* `[ ... ] twice` Call a quotation twice.
* `flip` Transpose a matrix.
* `[ ... ] map` Do something to every row in the matrix.
* `[ 32 = ] partition prepend` Separate the spaces from the other characters, then stick 'em on one end.
* `"\n"join` Convert a matrix of code points (e.g. `{ { 91 91 32 } { 91 32 32 } { 32 32 32 } }`) to a string.
> 2 votes

# Answer
# Vim, 55 bytes

```
YP:s/./\\_./g
Dddqq:%s/\v (<C-r>-)(\S)/\2\1
@qq@q:%s/ //g

```

Requires input to be padded to a rectangle. Try it online!

### Strategy

We're going to handle the vertical swaps by constructing a regex that will match any \\$n\\$ characters--including newline--where \\$n\\$ is the length of each line. Then we look for a space followed by \\$n\\$ characters followed by a non-space and swap the space for the non-space. Since the potential matches of this regex are overlapping, we'll use a macro to keep on doing the replacement until there are no more matches. Then the horizontal squashing is easy: just remove all spaces.

### Explanation

```
YP

```

Copy the top line upward. We're going to turn this copy into the regex we need.

```
:s/./\\_./g<cr>

```

Replace each character on the line with `\_.`. In Vim regex, this is a construct that matches any single character including newline (TIL). Line 1 now contains a regex that matches \\$n\\$ characters.

```
Ddd

```

Delete to the end of the line (putting the regex in register `-`) and then delete the now-blank line (doesn't overwrite `-` because it's a multiline deletion).

```
qq

```

Begin recording macro `q`:

```
:%s/\v (<C-r>-)(\S)/\2\1 <cr>

```

Do a substitution on all lines: space, followed by the regex we stored in register `-` (group 1), followed by a non-space character (group 2) =\> group 2, followed by group 1, followed by space. (The `\v` sequence means we don't have to backslash the parentheses, saving a net 2 bytes.)

```
@qq

```

After the substitution, call the macro recursively. Stop recording...

```
@q

```

... and call the macro. This recursive macro will run until no more substitutions can be made.

```
:%s/ //g<cr>

```

Replace all spaces on all lines with empty string.
> 2 votes

# Answer
# Scala 2.12, 71 bytes

Fixed a mistake thanks to @ophact

```
1.to(2)./:(_){_.transpose.map{r=>val(x,s)=r.partition(32<);x++s}->_ _1}

```

Try it in Scastie!

Takes a matrix of characters as input. The non-space characters have to be greater than 32 (ASCII).

```
1.to(2)  //Make the range[1..2]. This is just to repeat the function twice
./:(_){  //Fold over it with the input as the initial value for the accumulator
_.transpose  //Transpose the matrix first so we can work on the columns
 .map{r=>    //For every row,
  val(x,s)=r.partition(32<); //x is non-space characters, s is spaces
  x++s       //Join those together, with all the spaces at the end
 }->_   //Make a 2-tuple with the current number (either 1 or 2)
 _1}    //Get the first element of that tuple (the matrix), discarding the number

```
> 1 votes

# Answer
# Pip `-rl`, ~~11~~ 9 bytes

```
ZD J*||Zg

```

Takes input as lines of stdin, padded to a full rectangle. Try it online!

### Explanation

```
           g is list of lines of stdin (-r flag)
       Zg  Zip g (transposing into a list of lists of characters)
     ||    Strip whitespace from each character (replacing spaces with empty string)
   J*      Join each sublist into a single string
ZD         Zip again, padding shorter sublists with nil
           Autoprint with each sublist on a separate line (-l flag)

```

Changing the flags to `-rP` shows the actual structure of the list that gets output (`()` is nil):

```
["a";"f";"b";"g";"c";"g";"d";"h";"l";"e"]
["f";"j";"j";();"g";"k";();"l";();"i"]
[();();();();"k";();();();();"l"]

```

Since the `-l` flag joins each sublist together without a separator, and since nil normally produces no output, `-rl` gives us exactly the output we want:

```
afbgcgdhle
fjjgkli
kl

```
> 1 votes

# Answer
# JavaScript (ES10), 82 bytes

Expects a space-padded matrix of characters. Returns a list of lists of characters.

```
m=>m.map(r=>r.flatMap((_,x)=>m.some((r,y)=>1/(c=r[x])||m[y+=[,x]]?0:m[y]=1)?c:[]))

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 46 bytes

```
+`(?<=(.)*) (.*¶(?<-1>.)*(?(1)$))(\S)
$3$2

```

Try it online! Takes space-padded input. Note: Lines 2 and 3 end in a space. Explanation:

```
(?<=(.)*) (.*¶(?<-1>.)*(?(1)$))(\S)
$3$2

```

Find a space above non-whitespace and exchange the two.

```
+`

```

Repeat until no more exchanges can be made.

```

```

Delete the remaining spaces.
> 1 votes

# Answer
# Charcoal, 26 bytes

```
ＷＳ⊞υιＦ²≔Ｅ§υ⁰◨Φ⭆υ§μλ›μ Ｌυυυ

```

Try it online! Link is to verbose version of code. Takes input as newline-terminated space-padded list of strings. Explanation:

```
ＷＳ⊞υι

```

Input the strings.

```
Ｆ²

```

Repeat twice.

```
≔Ｅ§υ⁰◨Φ⭆υ§μλ›μ Ｌυυ

```

Transpose the array, filter out the spaces, then right-pad back to the original length.

```
υ

```

Output the final result.
> 1 votes

# Answer
# JavaScript (ES10note), 76 bytes

```
a=>(g=a=>a[0].map((c,i)=>a.map(l=>l[i]).sort((x,y)=>(y>' ')-(x>' '))))(g(a))

```

Try it online!

Just noticed that this Python answer by hyper-neutrino used the same algorithm. You may upvote that one.
> 1 votes

# Answer
# Husk, 5 bytes

```
TmfIT

```

Try it online!

same as jelly
> 1 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
a=PadRight[#/." "->Nothing]/. 0->" "&;a@a@#&

```

Try it online! Pure function. Takes a space-padded matrix of characters and returns the squashed matrix. This function uses the relatively straightforward algorithm: transpose, remove spaces, pad with spaces, and repeat once more. The Unicode character is U+F3C7 for `\[Transpose]`. Note that without the space, the `ReplaceAll` expression would be parsed as `/ .0 -> " "`.
> 1 votes

---
Tags: code-golf, string, array, matrix
---


title: Declare a Code Golf Winner

text:
# Question
Title: Declare a Code Golf Winner
Normally, I'd open with some flavor text here about being bored and/or lazy but looking through the questions that would be *far* from original. So instead I'm going to open with a meta and self-referential flavor text describing this lack of originality that then describes itself and how meta and self-referential it is.

# Challenge

Write a program that takes in the ID for some question on PPCG, and uses the SE API to grab the answers and select the winner.

You may assume that it is a question, and the following answer format:

```
# Language, [<s>XXX</s>] YYY bytes

[Thanks to @user1 for saving XX bytes!]
[Thanks to @user2 for saving YY bytes!]

print "badly formatted but easier to tally like this"

```

To clarify:

* It might have 1 or more attributions or crossed out past scores, and it might not.
* The attributions and crossed-out scores are not necessarily correlated; one can appear without the other.
* If there are no attributions, then the code will start 2 newlines after the heading.

Anyway, you can either extract the length in the beginning or count the length of the code at the end. For the former, only use the last score. For the latter, don't count the attributions. You can assume that the two will match up.

Your program should spit out the ID for the answer with the fewest bytes. Your program should also do this in the fewest bytes possible, as the shortest answer in bytes will win.

*Note: yes, I have seen Write code to determine the accepted answer, but that challenge has submissions voting on the winner whereas this is code golf with a specific task and an explicit winner independent of other answers.*

# Answer
> 1 votes
# JavaScript, 283 bytes

```
n=>fetch(`https://api.stackexchange.com/2.2/questions/${n}/answers?site=codegolf&filter=!*SU8CGYZitCB.D*(BDVIficKj7nFMLLDij64nVID)N9aK3GmR9kT4IzT*5iO_1y3iZ)6W.G*`).then(r=>r.json()).then(s=>alert(s.items.sort((a,b)=>(g=s=>s.match(/\d+(?= bytes)/)[0])(a.body)-g(b.body))[0].answer_id))

```

Run on a subdomain of `stackexchange.com`.

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


title: Negate The String

text:
# Question
Title: Negate The String
*Disclaimer: This isn't my challenge but ThisGuy said I was OK to post.*

---

Occasionally I want to make a word into it's opposite, like `happiness` goes to `unhappiness`. Unfortunately when this happens, my brain will sometimes go blank. Then one day, after yet another this happening, I thought to my self "This is what programs are for!"

As the English language has many exceptions, I have created a list which contains the prefix for the starting letter

```
q or h          -> dis- (honest -> dishonest)
l                -> il-  (legal -> illegal)
m or p           -> im-  (mature -> immature)
r                -> ir-  (responsible -> irresponsible)
everything else  -> un-  (worthy -> unworthy)

```

# Task

Given an input as a string, make the string into its negative and output the result. You can assume that all the inputs given will fit the above rules. Submissions may be programs or functions, not snippets.

# Input

A single string, taken either as a parameter or from STDIN

# Output

The negated form of that string, conforming to the above rules

# How to Win

This is a so shortest code wins

# Answer
# Python, 55 bytes

```
lambda n:'ddiiiiuiimmlrnss'[5-'rlmphq'.find(n[0])::7]+n

```

Try it online!

---

We need to handle 7 different starting letters:
`g` -\> `dis`, `h` -\> `dis`, `p` -\> `im`, `m` -\> `im`, `l` -\> `il`, `r` -\> `ir` and *everything else* -\> `un`

We can store all these negations in a single string and extract the right one through slicing:

```
 d      i      s
  d      i      s
   i      m
    i      m
     i      l
      i      r
       u      n

'ddiiiiuiimmlrnss'[i::7]

```

Now we need to calculate the start index `i`. `'rlmphq'.find` returns 0 for `'r'`, 5 for `q` and -1 for everything not contained in the string. To get the needed value from 0 to 6 we still need to subtract the return value from 5, resulting in this code:

```
'ddiiiiuiimmlrnss'[5-'rlmphq'.find(n[0])::7]

```
> 10 votes

# Answer
# GNU sed, 50 bytes

Includes +1 for `-r`

```
s/^q|^h/dis&/
s/^l|^r|^m/i&&/
s/^p/imp/
t
s/^/un/

```

Nothing fancy. Uses `&` in the replacement to combine a few substitutions, and `t` to skip the last one if one of the first substitutions happens.

Try it online!
> 6 votes

# Answer
# Jelly, 30 bytes

```
1ị“qmlrrhp”iị“3bµWI⁼ṡ÷ʠ$»œs5¤;

```

**Try it online!**

### How?

```
1ị“qmlrrhp”iị“3bµWI⁼ṡ÷ʠ$»œs5¤; - Main link: string
1ị                             - 1 index into the string (first character of the string)
           i                   - 1-based index of 1st occurrence of that in (else zero):
  “qmlrrhp”                    -     char list "qmlrrhp"
            ị                  - index into (1-based and modulo):
                            ¤  -     nilad followed by link(s) as a nilad:
             “3bµWI⁼ṡ÷ʠ$»      -         compressed string "dis"+"imili"+"run"="disimilirun"
                         œs5   -         split "equally" into 5: ["dis","im","il","ir","un"]
                             ; - concatenate with the string

```

Note that the repeated `r` in `“qmlrrhp”` is in the 5th index, which, if referenced, would result in prepending `un`, so it could equally well be anything other than `h` or `p`.
> 5 votes

# Answer
# ///, ~~59~~ 56 bytes

```
/^/\/\/#//#qu/disqu^h/dish^l/ill^m/imm^p/ipp^r/irr^/un/#

```

Try it online!

Input goes after the very last `#`.

**How it works:**

I made an optimization that reduced the size to 56 bytes, but since that complicates things I will explain the original version, then explain the golf.

```
/#qu/disqu//#h/dish//#l/ill//#m/imm//#p/ipp//#r/irr//#/un/# |everything after the ` |` is not code.
/#qu/disqu/                                                 |replace `qu` with `disqu`
           /#h/dish/                                        |replace `h` with `dish`.
                    /#l/ill/                                |replace `l` with `ill`.
                            /#m/imm/                        |replace `m` with `imm`.
                                    /#p/ipp/                |replace `p` with `ipp`.
                                            /#r/irr/        |replace `r` with `irr`.
                                                    /#/un/  |replace everything else with `un`.
                                                          # |safety control

```

**Intuition:** The challenge is simple enough, just add the negative depending on the beginning of the word. However, in ///, you cannot just `concatenate if [...]`, you can only replace something following a specific pattern. So in this program, the positive word beginnings are replaced with the negative word beginnings. The `#` was added to make sure that once a new beginning was added, no more new beginnings would be added. The `#` also made it possible to do 'everything else: un'.

The golf incorporates a new substitution at he beginning: `/^/\/\/#/`. This replaces all `^` with `//#`, which was a common pattern in the original version.
> 4 votes

# Answer
# TI-Basic, 104 bytes

```
Prompt Str0
sub(Str0,1,1→Str2
Str0
If Str2="Q" or Str2="H
"DIS"+Ans
If Str2="L
"IL"+Ans
If Str2="M" or Str2="P
"IM"+Ans
If Str2="R
"IR"+Ans
If Ans=Str0
"UN"+Ans
Ans

```

Requires all capital letters.

Explanation:

```
Prompt Str0             # 4 bytes, input user string to Str0
sub(Str0,1,1→Str2       # 12 bytes, store first character in Str2
Str0                    # 3 bytes, store Str0 in Ans
If Str2="Q" or Str2="H  # 14 bytes, if the first letter was Q or H
"DIS"+Ans               # 8 bytes, store DIS+Ans in Ans
If Str2="L              # 7 bytes, If the first letter was L
"IL"+Ans                # 7 bytes, store IL+Ans in Ans
If Str2="Q" or Str2="H  # 14 bytes, if the first letter was Q or H
"IM"+Ans                # 7 bytes, store DIS+Ans in Ans
If Str2="R              # 7 bytes, if the first letter was R
"IR"+Ans                # 7 bytes, store IR+Ans in Ans
If Ans=Str0             # 6 bytes, if Ans has not been changed (first letter was none of the above)
"UN"+Ans                # 7 bytes, store UN+Ans in Ans
Ans                     # 1 byte, implicitly return Ans

```
> 4 votes

# Answer
## Batch, 114 bytes

```
@set/pw=
@set p=un
@for %%p in (dis.q dis.h il.l im.m im.p ir.r)do @if .%w:~,1%==%%~xp set p=%%~np
@echo %p%%w%

```

Checks the first character of the word against the list of custom prefixes and if so changes the prefix from the default of `un`. Special-casing `qu` is possible at a cost of 21 bytes.
> 3 votes

# Answer
# JavaScript (~~71~~ ~~64~~ 61 bytes)

`w=>({q:a='dis',h:a,l:'il',m:b='im',p:b,r:'ir'}[w[0]]||'un')+w`

Edits:

* Saved 7 bytes thanks to @ErtySeidohl (`charAt(0)` -\> `[0]`)
* Saved 3 bytes thanks to @edc65 (assigning shared prefixes to variables)

```
var f = w=>({q:a='dis',h:a,l:'il',m:b='im',p:b,r:'ir'}[w[0]]||'un')+w;

function onChange() {
   var word = event.target.value;
   var output = f(word);
   document.getElementById('output').innerHTML = output;
}
```

```
Input Word: <input type='text' oninput='onChange()'/><br/>
Output Word: <span id="output">
```
> 3 votes

# Answer
# Javascript, ~~72~~ ~~71~~ ~~66~~ ~~61~~ ~~60~~ 59 bytes

~~`w=>('dis....il.im...im.dis.ir'.split('.')[w.charCodeAt(0)-104]||'un')+w`~~

~~`w=>'un.dis.dis.il.im.im.ir'.split('.')['qhlmpr'.indexOf(w[0])+1]+w`~~

~~Yeah, it's *still* longer than an existing solution. :)~~

```
w=>['un','dis','im','il','ir']['qmlrhp'.search(w[0])%4+1]+w

```

In case this needs any explanation, I'm taking advantage of the q/h and m/p pairs by combining their index in the search string with a mod 4, then using that as the lookup into the prefix array.
> 3 votes

# Answer
## Haskell, 71 bytes

```
f l=maybe"un"id(lookup(l!!0)$zip"qhlmpr"$words"dis dis il im im ir")++l

```

Usage example: `f "legal"`-\> `"illegal"`. Try it online!

Build a lookup table of prefix/replacement pairs for looking up the first char of the input string with a default value of `"un"` if not found.
> 2 votes

# Answer
# Retina, 54 bytes

```
^[^hqlmpr]
un$+
^[hq]
dis$+
^l
il$+
^[mp]
im$+
^r
ir$+

```

Explanation:

```
             {implicit replace stage}
^[^hqlmpr]   Append un to words starting with none of: hqlmpr
un$+
^[hq]        Append dis to words starting with h or q
dis$+
 ^l          Append il to words starting with l
il$+
^[mp]        Append il to words starting with m or p
im$+
^r           Append ir to words starting with r
ir$+

```

First time I've used Retina. It's a pretty neat language.

Try it online!
> 2 votes

# Answer
# C, ~~109~~ 107 bytes

```
f(char*s){printf("%s%s",*s-109&&*s-112?*s-108?*s-114?*s-104&&*s-113|s[1]-117?"un":"dis":"ir":"il":"im",s);}

```

Try it online!
> 1 votes

# Answer
## Mathematica, 107 bytes

```
StringReplace[StartOfString~~x:#:>#2<>x&@@@{{"q"|"h","dis"},{"l","il"},{"m"|"p","im"},{"r","ir"},{_,"un"}}]

```

## Explanation:

`StartOfString~~x:#:>#2<>x&` is a pure function where the first argument is a string pattern to match at the beginning of the string and the second argument is a string to prepend to the match. It returns a delayed rule suitable for use within `StringReplace`. This is then applied to each of the pairs `{{"q"|"h","dis"},{"l","il"},{"m"|"p","im"},{"r","ir"},{_,"un"}}` resulting in the list of rules

```
{
  StartOfString~~x:"q"|"h":>"dis"<>x,
  StartOfString~~x:"l":>"il"<>x,
  StartOfString~~x:"m"|"p":>"im"<>x,
  StartOfString~~x:"r":>"ir"<>x,
  StartOfString~~x_:>"un"<>x
}

```

Finally this list is passed into `StringReplace` which gives an operator on strings.
> 1 votes

# Answer
# PHP, 101 Bytes

```
echo preg_match("#^(qu|[hlmpr])#",$argn,$t)?[qu=>dis,h=>dis,l=>il,m=>im,p=>im,r=>ir][$t[1]]:un,$argn;

```

Online Version
> 1 votes

# Answer
# Excel 78 bytes

```
=TRIM(MID("  disdisil im im ir un",IFERROR(FIND(LEFT(A1),"qhlmpr"),7)*3,3))&A1

```

I found some close contenders using different methods that scored 81 bytes:

```
=IFERROR(CHOOSE(FIND(LEFT(A1),"qhlmpr"),"dis","dis","il","im","im","ir"),"un")&A1

```

And 84 bytes:

```
=IFERROR(TRIM(MID("im disi"&LEFT(A1),MOD(FIND(LEFT(F1),"qlmhrp"),3)*3+1,3)),"un")&A1

```
> 1 votes

# Answer
## REXX, 78 bytes

```
arg a
s.=un
s.q=dis
s.h=s.q
s.l=il
s.m=im
s.p=im
s.r=ir
p=left(a,1)
say s.p||a

```

Saves a few bytes by replying in UPPERCASE, e.g. potent -\> IMPOTENT.
> 0 votes

# Answer
# Perl, 49 + 1 (`-p` flag) = 50 bytes

```
s|^[hq]|dis$&|||s|^[lmr]|i$&$&|||s|p|imp|||s||un|

```

Using:

```
perl -pe 's|^[hq]|dis$&|||s|^[lmr]|i$&$&|||s|p|imp|||s||un|' <<< responsible

```

Try it online.
> 0 votes

# Answer
## Clojure, 65 bytes

```
#(str(get{\q"dis"\h"dis"\l"il"\m"im"\p"im"\r"ir"}(first %)"un")%)

```

Well this is boring... but I couldn't make it any shorter. At least there is very little whitespace.
> 0 votes

# Answer
## OCaml, 85

```
(fun s->(match s.[0]with|'q'|'h'->"dis"|'l'->"il"|'m'|'p'->"im"|'r'->"ir"|_->"un")^s)

```

Anonymous function, uses pattern matching on its first char.
> 0 votes

# Answer
# Vyxal, 38 bytes

```
«÷c4w«?hḟ:u=[`un`|4%«⟑Ẇf:«2ẇ`Ġ⟨`p$i]?+

```

Try it Online!

Messy.
> 0 votes

# Answer
# PowerShell, ~~66~~ 62 bytes

`%4+1` inspired by @Steve Bennett

```
param($s)(echo un dis im il ir)[('qmlrhp'|% I*f $s[0])%4+1]+$s

```

Try it online!
> 0 votes

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


# Question
Title: Solve the halting problem for S combinatory logic
## Background

Combinatory logic is a system where a term is written using a finite set of combinators and function application between terms, and reduction rules are defined for each combinator. The well-known S and K combinators have the following reduction rules:

$$ \begin{aligned} S\\;x\\;y\\;z & \overset{S}{\implies} x\\;z\\;(y\\;z) \\ K\\;x\\;y & \overset{K}{\implies} x \end{aligned} $$

A term is in *normal form* when no reduction is possible. A term has a normal form if a series of reductions applied to it gives a normal form. The halting problem in combinatory logic is essentially about determining whether a term has a normal form.

It is known that any lambda calculus expression can be converted to an expression in SK combinatory logic, and therefore the halting problem for SK combinatory logic is undecidable. However, neither K nor S alone has such property, and it turns out that the halting problem for each of them is decidable. But K is too trivial (it always terminates), so we turn to S.

A paper titled The Combinator S, by Johannes Waldmann, describes how to decide if a term in S combinatory logic has a normal form. Theorem 55 is the main result, and the regular tree grammar is also presented in Appendix 2.

## Examples

The expression \\$S(SS)(SS)S\\$ halts in two steps:

$$ \begin{aligned} S(SS)(SS)S & \overset{S}{\implies} SSS(SSS) \\ & \overset{S}{\implies} S(SSS)(S(SSS)) \\ \end{aligned} $$

But the two expressions \\$S(SS)(SS)(S(SS)(SS))\\$ and \\$SSS(SSS)(SSS)\\$ can be proven to be non-halting, as shown in the paper linked above.

## Challenge

Solve the halting problem for S combinatory logic.

In this system, a term is simply a binary tree where each leaf represents S and each internal node represents application. You may take the input using any suitable structure that can directly represent the term, such as

* a binary tree data type,
* a nested array,
* or a string representation using parentheses (e.g. `S(SS)(SS)(SS)` or `(((S(SS))(SS))(SS))`) or in prefix notation (e.g. `@@@S@SS@SS@SS`).

For output, you can choose to

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

Standard rules apply. Shortest code in bytes wins.

# Answer
# Charcoal, ~~264~~ ~~260~~ ~~257~~ 235 bytes

```
⊞υθＦυＦ⊖ＬιＦι⊞υλＦ⮌υＦ⊖Ｌι⊞ι⍘§⁺§⪪”}∨M.⁶C¬²2´#±³¹⊗Ｉ↧β.|eBＴXmê�…⊟→⁼‹Ｒ$➙≧→↧ÀZLq);p↶⁷b⬤Jⅈ⁺7ς⧴Wn7bＺpïＸ|.➙Ｋ!μ…⁼@|v‹℅↨Ｓθ？mＹ,ＫＶ}⟧⎇Φ/◨7⁹¶↧πºwT～B0⁸!✳[➙↘↨cjf^{Ｍg‽bQⅉ→↥Za？↶⁶⊖J↘Ｄ⁻D⟲σ7r⬤？φ'⟦6f▷M↖¡[i⌊⊟\2ν｜¶x2;¹±＆~⁴K∨ρ‽↨⌕ＨMν(T‖β→⁵ⅈÞ↑«…i⊟Ｄ»”0⊟⊟ι×Cφ⊟⊟ιφ›³⁸⊟θ

```

Try it online! Link is to verbose version of code. Takes input as a nested array where `S` is represented by `[0]` so e.g. `S(SS)` is represented by `[[[0], [[0], [0]]]]` (note that an extra set of `[]`s is required to input an array to Charcoal since it accepts an array of arguments). Explanation: Based on the look-up table on p. 16 of http://www.cs.ru.nl/~henk/BEKW.pdf but with the values translated to make the resulting table more compressible.

```
⊞υθＦυＦ⊖ＬιＦι⊞υλ

```

Perform a breadth-first traversal to collect all of the nodes.

```
Ｆ⮌υＦ⊖Ｌι

```

Loop through the non-leaf nodes in reverse order. This effectively produces a depth-first traversal.

```
⊞ι⍘§⁺§⪪”...”0⊟⊟ι×Cφ⊟⊟ιφ

```

Turn the node into a leaf by replacing its children with the value from the compressed lookup table.

```
›³⁸⊟θ

```

If the value is still less than `38` then the expression halts.

The following rearrangement of the table values is used as this places as many `38`s at the bottom of each column as possible. These are then discarded from the compressed string and reconstructed afterwards.

```
Rearranged  Original
         0   0
        20   1
        19   2
         3   3
         4   4
        16   5
        17   6
         7   7
         1   8
        18   9
         2  10
         9  11
         5  12
        10  13
        12  14
         8  15
        13  16
        14  17
        15  18
        21  19
         6  20
        11  21
        24  22
        23  23
        25  24
        28  25
        27  26
        22  27
        26  28
        35  29
        37  30
        32  31
        30  32
        33  33
        36  34
        34  35
        29  36
        31  37
        38  ∞

```
> 9 votes

# Answer
# Jelly, 248 bytes

```
Œœżs2Œṙ$€}¥/F^Ị$;0xȷ¤s36
“ƙŀṂƒḂʂŻ⁷Ȧ¿ẏƑ<ọṭẹọ\Ṿ!µɗ⁻ȥƭĊƊġȯ;ŻxḂøCFO)1ɲŒṅ€+ṪʂU-Ɲ¿Ụ£þ^¶ ẹZ361PHc&ẓḟẉẹ⁴Ƒ@G⁶W6ṭ⁽A2K%Ṿ{ẉȯaỊ;ṆẊ:ḄtJ&ß>r³ɲȮ=Ŀ⁼ıɗt¦ÄɦñṙÇ⁹]ḷṡ⁸\]*<f6<U⁷ƲṬðẸG¬db⁾ƭɠ⁹S®w|XƈẎḤ⁴Ȯ⁺2BæƤḋ§Ḷọapæ4%ỊḞḟ¬v⁴ṇW^ŀ$ƈİƥX÷Ð{ṛƈ⁼T4\®ZṆ’b39ṣ0µṪ’s2;"Ç;€0
,ß€ŒḊ’$¿œị¢ʋ/

```

Try it online!

A full program that takes a single argument consisting of a list of S terms. S is represented by 1, and the parentheses are represented using nested lists. For example, \\$S(SS)(SS)(S(SS)(SS))\\$ becomes `[1, [1, 1], [1, 1], [1, [1, 1], [1, 1]]]`.

Returns 0 for inputs that do not halt and a positive integer (which is regarded as truthy by Jelly) for ones that halt.

This uses a rearranged version of the table found by @Neil for his answer. Most of the work and the bytes were spent on optimally compressing this table from a 38 x 38 table of numbers from 1 to 38 down to 231 bytes. The code that actually solves the problem is a mere 13 bytes (not counting the newline that separates the two).

## Explanation

### Helper link 1

Expand the run-length encoded segments and append lots of zeros before splitting into 36-length rows. Takes a single argument that alternates between integers to be used as is and run-length encoded runs of integers.

```
Œœ                          | Split into lists of the odd-indexed and even-indexed members of the original argument
          ¥/                | Reduce using the following:
  ż                         | - Zip with the following:
        €}                  |   - For each member of the right-hand argument (i.e. the even-indexed members of the original list):
   s2                       |     - Split into twos
     Œṙ                     |     - Run-length decode
            F               | Flatten
             ^Ị$            | Xor with whether the numbers are <=1 (effectively turns 1s to 0s)
                ;0xȷ¤       | Append 1000 zeros
                     s36    | Split into lists of length 36
                        ;€0 | Append 0 to each

```

### Helper link 2

Niladic link that generates the look-up table to reduce a pair of S terms

```
“ƙ…Ṇ’               | Large integer
     b39            | Convert to base 39
        ṣ0          | Split at zeros
          µ         | Start a new monadic chain
           Ṫ        | Tail (which holds the first two cells for each row)
            ’       | Reduce by 1
             s2     | Split into twos
               ;"Ç  | Concatenate zipped to the result of calling helper link 2 on the other members of the list generated in the first part of this link

```

### Main link

Takes an S expression as its argument and returns 0 for non-halting and a positive integer for halting.

```
           ʋ/ | Reduce using the following:
,             | - Pair
   ŒḊ’$¿      | - While depth >1:
 ß€           |   - Recursively call the current link for each member of the pair
        œị¢   | - Multidimensional index into the look-up table generated by helper link 2

```
> 1 votes

---
Tags: code-golf, decision-problem, functional-programming, halting-problem, combinatory-logic
---


# Question
Title: Is this FEN board a Fischer random chess starting board?
# Introduction

Fischer random chess, also known as Chess960 for the 960 valid starting boards, is a variant of chess where each player's pieces are randomly shuffled at the start. As a reminder, each player gets 8 pawns, two rooks, two knights, two bishops, one queen, and one king. For this challenge, you don't need to know anything about the rules of chess, as we are only concerned with the starting positions of the pieces on a 8x8 chessboard. In particular, white's non-pawn pieces are placed randomly on the first rank (row of the chessboard). The white pawns are placed on the second rank as usual. In addition, the following rules for white's non-pawn pieces must be adhered to:

* The bishops must be placed on opposite color squares (since the chessboard has a checkerboard pattern, that means there is an odd distance between them)
* The king must be placed on a square between the rooks

Black's pieces are placed mirroring white's horizontally on the board, so that black's pieces are on the same file (column) as the corresponding white's pieces.

The input board must be given as a FEN board string, which is standard for chess programs. From the FEN specification:

> The board contents are specified starting with the eighth rank and ending with the first rank. For each rank, the squares are specified from file a to file h. White pieces are identified by uppercase SAN piece letters ("PNBRQK") and black pieces are identified by lowercase SAN piece letters ("pnbrqk"). Empty squares are represented by the digits one through eight; the digit used represents the count of contiguous empty squares along a rank. A solidus character "/" is used to separate data of adjacent ranks.

For reference, SAN piece letters are: pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q", and king = "K". White's pieces are in uppercase while black's are in lowercase.

# Task

Given a valid FEN board string, described above, output a boolean value for whether or not the input board is a Fischer random chess starting board.

# Test cases

## Valid boards

The first string is a standard board (fun fact: board 518 in the standard Fischer random chess numbering scheme).

```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
rqkbbrnn/pppppppp/8/8/8/8/PPPPPPPP/RQKBBRNN
bqrnnkrb/pppppppp/8/8/8/8/PPPPPPPP/BQRNNKRB
nrbbqnkr/pppppppp/8/8/8/8/PPPPPPPP/NRBBQNKR
bqnrnkrb/pppppppp/8/8/8/8/PPPPPPPP/BQNRNKRB
nnqrkrbb/pppppppp/8/8/8/8/PPPPPPPP/NNQRKRBB
nnbrkqrb/pppppppp/8/8/8/8/PPPPPPPP/NNBRKQRB
nbbrnkqr/pppppppp/8/8/8/8/PPPPPPPP/NBBRNKQR
rknrnbbq/pppppppp/8/8/8/8/PPPPPPPP/RKNRNBBQ
qnbbrknr/pppppppp/8/8/8/8/PPPPPPPP/QNBBRKNR

```

## Invalid boards

Everything after the board string starting with `#` is a comment for compactness and is not part of the input.

```
8/8/8/8/8/8/8/8                                # Empty board
8/8/8/8/8/8/PPPPPPPP/RNBQKBNR                  # Missing black's pieces
RNBQKBNR/PPPPPPPP/8/8/8/8/PPPPPPPP/RNBQKBNR    # Missing black's pieces and too many white pieces
rnbqkbnr/ppp1pppp/8/8/8/8/PPPPPPPP/RNBQKBNR    # Missing pawn
rnbkqbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR    # Black's pieces don't mirror white's
rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR  # Not a starting board
4q2k/2r1r3/4PR1p/p1p5/P1Bp1Q1P/1P6/6P1/6K1     # Definitely not a starting board
rkbqnnbr/pppppppp/8/8/8/8/PPPPPPPP/RKBQNNBR    # Bishops must be on opposite squares
qkrnbbrn/pppppppp/8/8/8/8/PPPPPPPP/QKRNBBRN    # King must be between rooks
rkrbbnnn/pppppppp/8/8/8/8/PPPPPPPP/RKRBBNNN    # Missing queens

```

# Answer
> 6 votes
# Jelly, 82 bytes

```
”pẋ8;⁶ẋ⁴¤“bbknnqrr”;s8;ṚŒu$$
ṣ”/8RṾ,⁶ẋ$Ɗ€Z¤yⱮµF€Ṣ€⁼¢ȧ1ịẹ”bƲSḂƊȧ8ịf⁾RKƲ⁼U$$ȧṪ⁼ḢŒu$Ɗ

```

Try it online!

```
”pẋ8;⁶ẋ⁴¤“bbknnqrr”;s8;ṚŒu$$    Helper Link (nilad)
”p                              "p"
  ẋ8                            repeated 8 times
    ;---¤                       then append
     ⁶                          " "
      ẋ⁴                        repeated 16 times
         “bbknnqrr”;            then prepend "bbknnqrr"
                    s8          slice into chunks of length 8
                      ;----$    append
                       ṚŒu$     the grid, reversed, uppercased

```

This helper link generates an 8x8 matrix representing any valid starting position if each row is sorted alphabetically.

```
ṣ”/8RṾ,⁶ẋ$Ɗ€Z¤yⱮ    Main Link - first part
ṣ”/                 split the input on "/"
   8 ---------¤      (inline niladic chain)
   8R               [1, 2, ..., 8]
     -----Ɗ€        for each of those
     Ṿ              uneval it (turn to string)
      ,             and pair with
       ⁶ẋ$          " " * (the number)
              yⱮ    apply this as a transformation to each

```

This part converts from FEN notation to an 8x8 matrix of characters, where blanks are spaces.

```
µF€Ṣ€⁼¢             Main Link - second part
µ                   start a new monadic chain (avoids chaining)
 F€                 flatten each row
   Ṣ€               sort each row
     ⁼¢             is it equal to (helper link)?

```

This part checks if the board's rows have the correct pieces.

```
ȧ1ịẹ”bƲSḂƊ          Main Link - third part
ȧ                   logical AND
 --------Ɗ
 -----Ʋ
 1ị                 1st element
   ẹ”b              find indices of bishops
       S            sum
        Ḃ           is it odd?

```

This part checks for the positioning of the bishops in the first row.

```
ȧ8ịf⁾RKƲ⁼U$$        Main Link - fourth part
ȧ                   logical AND
 ----------$
 ------Ʋ
 8ị                 8th element
   f⁾RK             filter to only keep R and K
        ⁼U$         is it equal to its reverse?

```

This part checks if the kings and rooks are in the order RKR; since we've already made sure each row's piece count is correct, the only way for it to be symmetric is to be RKR.

```
ȧṪ⁼ḢŒu$Ɗ            Main Link - fifth part
ȧ                   logical AND
 ------Ɗ
 Ṫ                  pop the last row
  ⁼                 is it equal to
   ḢŒu$             the first row uppercase?

```

This part makes sure the black and white pieces align.

# Answer
> 5 votes
# Retina 0.8.2, ~~91~~ ~~83~~ 80 bytes

```
G`^[b-r]{8}/p{8}(/8){4}/P{8}/[B-R]{8}$
Gi`^(.{8}).*\1
G`b(..)*b.*R.*K.*R
q.*N.*N

```

Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @Jakque. Explanation:

```
G`^[b-r]{8}/p{8}(/8){4}/P{8}/[B-R]{8}$

```

Check that both sides have exactly 8 pieces and pawns. The following checks then require those pieces to include at least one each of king and queen and at least two each of the other three pieces, therefore those pieces are in fact exactly one and two each of the appropriate pieces.

```
Gi`^(.{8}).*\1

```

Now that we know that the first eight pieces are Black's and the last eight are White's, check that White's pieces mirror Black's.

```
G`b(..)*b.*R.*K.*R

```

Check that Black has at least two bishops on opposite coloured squares and White has at least one king between two rooks.

```
q.*N.*N

```

Check that Black has at least one queen and White has at least two knights.

# Answer
> 4 votes
# 05AB1E, 43 bytes

Same length as a valid input ;). Very slow, generates all valid boards (8 times) and checks if the list contains the input.

```
.•5h+…Í•œʒæ…rkrå}ʒ'b¡1ègÈ}ε'p8×8D)Âu«'/ý}så

```

Try it online!

**Commented:**

```
.•5h+…Í•           # alphabet compressed string "bbknnqrr"
        œ          # all permutations of this string

                   # remove invalid configurations of black pieces:
ʒ      }           # keep a string
 æ    å            #   if its powerset contains ...
  …rkr             #   the string "rkr"
        ʒ       }  # filter on
         'b¡       #   split by the bishops
            1è     #   the substring between the bishops
              gÈ   #   has even length?

ε             }    # map over all valid configurations of blacks pieces
 'p8×              # create the row of 8 black pawns
     8D            # push two copies of 8
       )           # collect black's pieces, the pawns and both 8's into a list
        Â          # bifurcate: duplicate and reverse the copy
         u         # convert each string in the reversed to upper case
          «        # concatenate both lists
           '/ý     # join the rows by "/"

s                  # swap to the implicit input
 å                 # is it contained in the list of valid FENs?

```

---

# 05AB1E, 44 bytes

Fast version at the cost of byte, uses a lot of the same code, but only verifies the input without generating additional boards.

```
8£Ð{.•5h+…Í•Q×æ…rkrå×D'b¡1ègÈ×'p8×8D)Âu«'/ýQ

```

Try it online! or Try all cases!

```
8£               # take first 8 chars of the input (= black pieces)
  Ð              # push two copies of black pieces
   {        Q    # does the sorted string sort equal
    .•5h+…Í•     # the compressed string "bbknnqrr"?
             ×   # repeat black pieces this may times
æ…rkrå           # is the king between the rooks?
      ×D         # repeat black pieces that may times and push another copy
        'b¡1ègÈ  # are the bishops on opposite squares?
               × # repeat blacks pieces ...
'p8×8D)Âu«'/ý    # generate FEN from blacks pieces
             Q   # does this equal the input?

```

# Answer
> 4 votes
# JavaScript (ES6), 95 bytes

Similar to my original version, but with a single regular expression.

Returns either a string (truthy) or *null* (falsy).

```
s=>s.match(s.slice(35).toLowerCase()+'.p{8}[/8]{9}P{8}(?=.*B(..)*B)(?=.*R.*K.*R)(?=.*N.*N).*Q')

```

Try it online!

---

# JavaScript (ES6),  ~~105 103~~  99 bytes

Returns a Boolean value.

```
s=>[/R.*K.*R/,/B(..)*B/,/N.*N/,/p{8}[/8]{9}P{8}.*Q/,s.slice(35).toLowerCase()].every(e=>s.match(e))

```

Try it online!

### How?

As stated in the challenge, the input is guaranteed to be a valid FEN string. So once the pawn structure has been fully checked, we can safely assume that there are exactly two remaining rows that are properly formatted and just make sure that all other expected pieces are there.

We use 4 standard regular expressions:

```
/R.*K.*R/            ~> there's a white king surrounded by 2 white rooks
/B(..)*B/            ~> there are 2 white bishops with an even number of
                        squares in between
/N.*N/               ~> there are 2 white knights
/p{8}[/8]{9}P{8}.*Q/ ~> the pawn configuration is correct
                        and there's a white queen in the last row

```

Followed by this string:

```
s.slice(35).toLowerCase()

```

which is interpreted as another regex by `match()` and allows us to make sure that the first row is the last row in lower case.

# Answer
> 3 votes
# Vyxal, 56 bytes

```
\//Dh⟨\p8*|\8|\8⟩JḂv⇧J≠⅛hDs«4cð↔Ṗ«≠⅛ƛ\b=;T∑₂⅛«ƈʁ«:„↔≠⅛¾a

```

Try it Online!

```
\//Dh⟨\p8*|\8|\8⟩JḂv⇧J≠⅛ # Part 1 - is the board a mirror?
\//                      # Split on slashes
   D                     # 3 copies
    h                    # the first (black pieces)
     ⟨\p8*|\8|\8⟩J       # Prepended to eight pawns and two empty ranks
                  Ḃ      # Duplicate and get reverse
                   v⇧    # Uppercase all pieces in the revers
                     J   # Joined
                      ≠  # Is not equal to original?
                       ⅛ # Push to global array
hDs«4cð↔Ṗ«≠⅛ # Part 2 - are all the pieces here?
h            # First element
 D           # Tripled for future use
  s          # Sorted
          ≠  # Is not equal to
   «4cð↔Ṗ«   # Compressed string `bbknnqrr`?
           ⅛ # Push to global array
ƛ\b=;T∑₂⅛ # Part 3 - are the bishops on opposite color squares?
ƛ   ;     # Map to
 \b=      # Is a b?
     T∑   # Sum of truthy indices
       ₂  # Is even?
        ⅛ # Push to global array
«ƈʁ«:„↔≠⅛ # Part 4 - is the king between the rooks?
«ƈʁ«      # Compressed `rkr`
    :„    # Duplicate and put on bottom of stack
      ↔   # Remove characters that aren't `rkr`
       ≠  # Doesn't equal rkr?
        ⅛ # Push to global array
¾a # Part 5 - is everything in global array falsy?
¾  # Global array
 a # are any truthy?

```

What. A. Mess. Return 0 for valid and 1 for not.

-1 thanks to @cairdcoinheringaahing.

# Answer
> 2 votes
# Python 3, 190 bytes

```
lambda i:all([match('^[bknqr]{8}p{8}(8){4}P{8}[BKNQR]{8}$',''.join(i)),len({sub('[^rk]','',x.lower())for x in i[::7]})==1,len({sub('[^b]','.',x.lower())for x in i[::7]})==1])
from re import*

```

Try it online!

takes a list of each row in board

# Answer
> 2 votes
# Jelly,  ~~49~~ 47 bytes

-2 thanks to Nick kennedy (form valid strings in reverse and use mould for the pawns.)

```
”Pṁṭ⁾88⁸ṭṚŒl;Ɗj”/
“RNBQK”ṁ8Œ!ẹ”BSḂƊƇf⁾RKŒḂ$ƇÇ€ċ

```

A monadic Link that accepts a valid FEN string as a list of characters and yields `8` (truthy) if the FEN string is a valid Fischer random chess starting position or `0` (falsey) if not.

**Try it online!**
Or see the test-suite (to make it quicker valid boards are only built once, thus `ċ` moved to the footer)

### How?

```
”Pṁṭ⁾88⁸ṭṚŒl;Ɗj”/ - Link 1, get board: S, valid eighth rank
”Pṁ               - 'P' moulded like S      -> "PPPPPPPP"
   ṭ⁾88           - (that) tacked to ("88") -> ['8', '8', "PPPPPPPP"]
       ⁸ṭ         - (S) tacked to (that)    -> ['8', '8', "PPPPPPPP", S] = white's side
             Ɗ    - last three links as a monad - f(white's side):
         Ṛ        -   reverse
          Œl      -   to lower-case -> black's side
            ;     -   (black's side) concatenate (white's side)
              j”/ - join with '/'s

“RNBQK”ṁ8Œ!ẹ”BSḂƊƇf⁾RKŒḂ$ƇÇ€ċ - Main Link: FEN string
“RNBQK”ṁ8                     - "RNBQK" moulded like [1..8] -> "RNBQKRNB"
         Œ!                   - all permutations
                 Ƈ            - filter keep those for which:
                Ɗ             -   last three links as a monad:
           ẹ”B                -     indices of 'B'
              S               -     sum
               Ḃ              -     least significant bit (i.e. is odd?)
                         Ƈ    - filter keep those for which:
                        $     -   last two links as a monad:
                  f⁾RK        -     filter-keep if in "RK"
                      ŒḂ      -     is it a palindrome?
                          Ç€  - call Link 1 for each
                            ċ - count occurrences (of S)

```

# Answer
> 0 votes
# Charcoal, 54 bytes

```
¿⁼θ⪫⟦…θ⁸×p⁸8⁸8⁸×P⁸↥…θ⁸⟧/¿⁼rkrΦθ№krι¿⬤qbn›⊗№θι⊕κ﹪Σ⌕Ａθb²

```

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

```
¿⁼θ⪫⟦…θ⁸×p⁸8⁸8⁸×P⁸↥…θ⁸⟧/

```

Take the first 8 characters of the input, then a string of 8 `p`s, then `8` four times (mixing numeric and string to save bytes), then a string of 8 `P`s, then the first 8 characters of the input in upper case, join the whole lot together with `/`s, and check that this results in the original input.

```
¿⁼rkrΦθ№krι

```

Check that removing all characters other than `k` and `r` from the input results in the string `rkr`.

```
¿⬤qbn›⊗№θι⊕κ

```

Check that the input contains `q` at least once and `b` and `n` at least twice. (Given the other checks, this actually limits them to once and twice anyway.)

```
﹪Σ⌕Ａθb²

```

Check that the `b`s are an odd distance apart.

---
Tags: code-golf, string, decision-problem, chess
---


title: Taking the long route

text:
# Question
Title: Taking the long route
## Challenge

Your goal is to find the furthest point on a graph (from a provided start node). Your code doesn't need to handle cycles in the graph properly, but it might pose a fun challenge. For this question, you can assume the graph is actually a tree.

## Input data

Input can be provided in any suitable format for the language. It can be provided either as an adjacency matrix, a list of edges, or an adjacency list. The input data can be directed or undirected as wanted by the program. The program needs to know the starting node - this can be provided in the input data if the program doesn't calculate it.

## Output format

The program must output to stdout, in a human readable format, a list of nodes, starting from the root and leading to the furthest node. If you prefer, this order may be reversed. Your program must be consistent wrt to the ordering.

## Edge cases

If there are multiple longest paths, only return one. If there is a cycle, or the graph has disconnected components, your code may crash or return a valid or invalid output.

## Libraries

All graph related libraries, including built-in language features, are not permitted.

## Test case

Input:

```
{0: (1, 2, 3), 1: (), 2: (4, 5), 3: (6,), 4: (7,), 5: (), 6: (8,), 7: (9,), 8: (), 9: ()}
0

```

The zero on the second line is the starting node. This could be inferred from the adjacency list, but I've included it in the test data anyway, to be clear.

Output:

```
[0, 2, 4, 7, 9]

```

Image:

## Scoring

Shortest code wins.

# Answer
# Coconut, 45 bytes

Takes the graph in the format shown in the example test case

```
f=(g,s)->[s]+max(map(f$g,g[s])::[[]],key=len)

```

Try it online!

Uses Coconuts lambda syntax, `$` for partial application and `::` as an operator for `itertools.chain`. The same would be 56 bytes in Python:

```
f=lambda g,s:[s]+max([f(g,x)for x in g[s]]+[[]],key=len)

```

Try it online!
> 5 votes

# Answer
# Jelly, ~~13~~ 12 bytes

```
;ⱮịṪ¥¥€Ẏ¥ƬẎṪ

```

Try it online!

A dyadic link taking the start node as the left argument and the list of lists of child nodes as the right argument. The start node is expected to be supplied as `[[x]]` where `x` is the number of the node. Uses 1-indexing since that’s the way Jelly is written.

Thanks to @JonathanAllan for saving a byte!

## Explanation

```
        ¥Ƭ    | Starting with the start node index, do the following until there’s a repeated value:
     ¥€       | - For each member of the list:
;Ɱ            |   - Append each of the following:
  ịṪ¥         |     - The last member of the list indexed into the original right argument (actually done as index into then tail)
       Ẏ      | - Flatten lists by one level
          Ẏ   | Finally, join the top level lists together
           Ṫ  | Take the last remaining list (which will be one of the longest paths)

```
> 3 votes

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

```
a=>g=(h,...t)=>v=1/h?a[h].map((n,j)=>g[j]?0:g[j]=n&&t.push(j))[g(...t)[0]]?[h,...v]:v||[h]:0

```

Try it online!

Input the adjacency matrix of graph and the start node currily.

This one works on graphs with cycles.

---

# JavaScript (Node.js), 68 bytes

```
a=>s=>(g=(h,...t)=>v=h&&g(...t,...a[h[0]].map(j=>[j,...h]))||h)([s])

```

Try it online!

This one works on directed graph without cycles.
> 2 votes

# Answer
# Kotlin 1.4.20, 92 bytes

```
fun f(e:Map<Int,Set<Int>>,s:Int):List<Int> =(e[s]?.map{f(e,it)}?.maxBy{it.size}?:setOf())+s

```

## Usage

```
fun main() = println(f(mapOf(0 to setOf(1, 2, 3), 1 to setOf(), 2 to setOf(4, 5), 3 to setOf(6), 4 to setOf(7), 5 to setOf(), 6 to setOf(8), 7 to setOf(9), 8 to setOf(), 9 to setOf()), 0))

```

## Note

This uses a deprecated API that got removed in 1.5, so it requires Kotlin 1.4 or lower.
> 2 votes

# Answer
# Charcoal, 23 bytes

```
⊞υ⟦θ⟧ＦυＦ§η§ι⁰⊞υ⁺⟦κ⟧ιＩ⊟υ

```

Try it online! Link is to verbose version of code. Takes the root as the first input and an array of lists of adjacencies as the second input and outputs the longest route in reverse order. Explanation:

```
⊞υ⟦θ⟧

```

Start a breadth first search with a list of just the root node.

```
Ｆυ

```

Process the lists in the order they are found.

```
Ｆ§η§ι⁰

```

For each list, loop over the nodes adjacent to the first node in the list...

```
⊞υ⁺⟦κ⟧ι

```

... pushing a new list with the adjacent node at the beginning to the search.

```
Ｉ⊟υ

```

Output the last, and therefore longest, list.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
Pick[#,#,#&@@#~Level~{Depth@#-1}]//._[]:>Set@$&

```

Try it online!

Input an expression - Mathematica's expressions are trees. For example:

`Pick` almost does the job, but non-leaf nodes with successors still remain. Then we remove all empty nodes.

### Also 47 bytes

```
Select@Not@*FreeQ[#&@@#~Level~{Depth@#-2}]//@#&

```

Try it online!

Input leaves as e.g. `9[]` instead of `9`.
> 1 votes

# Answer
# PowerShell, ~~114 109 104~~ ~~103~~ 96 bytes

```
param($s,$e)$e|%{$p=($p+,"$_"*!(($a=$_[0])-$s))-replace"\b$a$",$_}
$p|sort{(-split$_).count}-b 1

```

Try it online!

Stores paths as an array of strings. Each path contains a list of vertices separated by spaces.

---

Less golfed:

```
param($startVertex,$edges)
$edges|%{
    $fromVertex = $_[0]
    $pathes += ,"$_"*($fromVertex -eq $startVertex) # add $null or an edge
    $pathes = $pathes -replace "\b$fromVertex$",$_
}
$pathes|sort{(-split$_).count} -Bottom 1

```

The dump of `$pathes` before sorting for the test case:

```
"0 1"
"0 2 4 7 9"
"0 3 6 8"

```
> 1 votes

# Answer
# Red, 95 bytes

```
f: function[x s][m: []foreach i select x s[p: f x i if(length? p)> length? m[m: p]]rejoin[m s]]

```

Try it online!

Takes input as an adjacency list plus the starting node in the same form as in challenge specification. Returns the longest path in reverse order.
> 1 votes

# Answer
# , 89 bytes

```
R=function(G,p={})`if`(!is.list(G),p,(A=lapply(G,R,c(p,el(G))))[[which.max(lengths(A))]])

```

Try it online!

Recursive function taking a tree as input (for the input format see the TIO) and returning the subtree of maximum length.
> 0 votes

---
Tags: code-golf, graph-theory, algorithm
---


title: Convert version string to pack_format

text:
# Question
Title: Convert version string to pack_format
When making a Minecraft data/resource pack, you need to include a `pack.mcmeta` file, which specifies information about it. `pack.mcmeta` contains a description, but it also contains a `pack_format` number, which tells Minecraft which versions this pack is for.

Your task is to take a version string, and output what `pack_format` number matches the string.

Your input must be a string, and you can assume it's either `1.x` or `1.x.y`.

As of when this challenge was posted, the conversion goes like so:

```
1.6.1 - 1.8.9 -> 1
1.9 - 1.10.2 -> 2
1.11 - 1.12.2 -> 3
1.13 - 1.14.4 -> 4
1.15 - 1.16.1 -> 5
1.16.2 - 1.16.5 -> 6
1.17 -> 7

```

These are all the possible inputs, and what they need to be mapped to:

```
1.6.1 -> 1
1.6.2 -> 1
1.6.4 -> 1
1.7.2 -> 1
1.7.4 -> 1
1.7.5 -> 1
1.7.6 -> 1
1.7.7 -> 1
1.7.8 -> 1
1.7.9 -> 1
1.7.10 -> 1
1.8 -> 1
1.8.1 -> 1
1.8.2 -> 1
1.8.3 -> 1
1.8.4 -> 1
1.8.5 -> 1
1.8.6 -> 1
1.8.7 -> 1
1.8.8 -> 1
1.8.9 -> 1
1.9 -> 2
1.9.1 -> 2
1.9.2 -> 2
1.9.3 -> 2
1.9.4 -> 2
1.10 -> 2
1.10.1 -> 2
1.10.2 -> 2
1.11 -> 3
1.11.1 -> 3
1.11.2 -> 3
1.12 -> 3
1.12.1 -> 3
1.12.2 -> 3
1.13.1 -> 4
1.13.2 -> 4
1.14 -> 4
1.14.1 -> 4
1.14.2 -> 4
1.14.3 -> 4
1.14.4 -> 4
1.15 -> 5
1.15.1 -> 5
1.15.2 -> 5
1.16 -> 5
1.16.1 -> 5
1.16.2 -> 6
1.16.3 -> 6
1.16.4 -> 6
1.16.5 -> 6
1.17 -> 7

```

This is code golf, so the shortest answer wins. Good luck!

# Answer
# JavaScript (ES6),  ~~43~~  42 bytes

```
s=>([,x,y]=s.split`.`,x*x+x*3+~~y)/51^x>16

```

Try it online!

### How?

Given an input string `1.x.y`, we compute:

$$\left\lfloor\frac{x^2+3x+y}{51}\right\rfloor$$

Because we're using `~~y`, we implicitly assume \\$y=0\\$ if the input string is just `1.x`.

This gives the correct result for all versions except the last one, which gives \\$6\\$ instead of \\$7\\$. This is fixed by XOR'ing with \\$1\\$ if \\$x\>16\\$.
> 25 votes

# Answer
# Excel, ~~46~~ 44 bytes

*-2 bytes change first item from 6.1 to 0*

```
=MATCH(MID(A1,3,9)*1,{0,9,11,13,15,16.2,17})

```

Since they are all 1.x or 1.x.y, this basically matches everything from the 3rd character on.
> 8 votes

# Answer
# JavaScript (ES7), 31 bytes

```
s=>s.slice(2)**2/45+.2|s[3]%1.2

```

Try it online!

TIO setup is based on Arnauld's answer.

Ignore the `1.` part and treat the input as a floating point number. For example, `1.16.1` becomes `16.1`. This formula (find out by some brute force search) works quite good (48/52 correctness).

$$\left\lfloor\frac{s^2}{45}+0.2\right\rfloor$$

And with some manually fix... It finally works.

So if you are interesting in how it works: I don't know why it work either.
> 8 votes

# Answer
# Jelly, 16 bytes

```
ṫ3V×⁵>“Ym²Ɱƙʋ‘S‘

```

Try it online!

```
ṫ3V×⁵>“Zn³Ɲɱȥ‘S‘   Main Link; take the string as required
ṫ3                 Remove the first two characters
  V                Eval it
   ×⁵              Multiply it by 10
     >“Zn³Ɲɱȥ‘     Compare (>) to each of [89, 109, 130, 149, 161, 169]
              S    Sum
               ‘   Increment

```
> 7 votes

# Answer
# Python 3, 94 60 57 bytes

```
lambda s:sum(x<=float(s[2:])for x in(0,9,11,13,15,16.2,17))

```

Try it online!

This function takes the string `s` and returns the corresponding `pack_format`.

-34 bytes thanks to Command Master (using `lambda` and `sum` instead of a basic loop + a stopping condition)

-3 bytes thanks to tsh (flipping the conditional, changing the list structure, replacing `float` with `eval`)
> 2 votes

# Answer
# C (gcc), ~~67~~ \\$\cdots\\$ ~~60~~ 58 bytes

Saved a byte thanks to ceilingcat!!!
Saved ~~4~~ 6 bytes thanks to tsh!!!
Saved 2 bytes thanks to rtpax!!!

```
y;f(p){p=(~-sscanf(p,"1.%d.%d",&p,&y)*y+p*p+3*p)/51+p/17;}

```

Try it online!

Uses a variation of Arnauld's formula from his JavaScript answer.
> 2 votes

# Answer
# Japt, 18 bytes

Port of hyper-neutrino's solution so be sure to upvote them too.

```
Ò"Ym¡©"¬mc x<¢*A

```

Try it (Includes all test cases)

```
Ò"..."¬mc x<¢*A     :Implicit input of string U
Ò                   :Negate the bitwise NOT of
 "..."              :String containing the characters at codepoints 89, 109, 130, 149, 161 & 169
      ¬             :Split
       m            :Map
        c           :  Codepoint
          x         :Reduce by addition
           <        :After checking each is less than
            ¢       :  Slice the first 2 characters off U
             *A     :  Multiply by 10

```
> 2 votes

# Answer
# Raku, 69 bytes

```
[+] Version.new($v) <<>=<<(v1.6,v1.9,v1.11,v1.13,v1.15,v1.16.2,v1.17)

```

Like Perl, Raku has native support for version string comparison. See Version for more info.

**Explanation**

* `Version.new($v)` converts from `Str` to `Version` type (it's a shame `v$v` doesn't work)
* `<<>=<<` hyper-operator converts major versions to `Bool`s
* `[+]` counts `True` values
> 2 votes

# Answer
# Java, 93 bytes

```
s->{var i=Float.valueOf(s.substring(2));return i<9?1:i<11?2:i<13?3:i<15?4:i<16.2?5:i<17?6:7;}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 18 bytes

```
¦¦T*•BÎΣÚÁÿ•Ƶζв›O>

```

Try it online!

```
¦¦T*•...•Ƶζв›O>  # trimmed program
             O   # sum of all elements of...
            ›    # is...
                 # implicit input...
¦                # excluding the first character...
 ¦               # excluding the first character...
   *             # times...
  T              # 10...
            ›    # greater than...
                 # (implicit) each element of...
           в     # list of base-10 values of base...
         Ƶζ      # 170...
           в     # digits of...
    •...•        # 12728408213639...
              >  # plus 1
                 # implicit output

```
> 1 votes

# Answer
# Vyxal, 23 bytes

```
L2$"iE₀*`-AViu}`C44+>∑›

```

Try it Online!
> 1 votes

# Answer
# Charcoal, ~~32~~ 29 bytes

```
ＩＬΦＩ⪪”#｜⊞u⦄,<q'Ｚχ=” ¬›ιＩ✂θ²χ¹

```

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

```
     ”...”              Compressed string `0 9 11 13 15 16.2 17`
    ⪪                   Split on spaces
   Ｉ                    Cast to float
  Φ                     Filtered where
             ι          Current value
           ¬›           Is not greater than
               ✂θ²χ¹    Slice of input string
              Ｉ         Cast to float
 Ｌ                      Take the length
Ｉ                       Cast to string
                        Implicitly print

```

Prefixing `0`  to the compressed string or post-incrementing both cost 1 byte. I've stuck with prefixing `0`  as it used to be shorter with the previous method. Edit: Switched to a less-than-or-equals comparison which costs a byte but saves 4 bytes from the compressed string.
> 0 votes

# Answer
# Python 3, 72 bytes

```
f=lambda p,n=0:float(p[2:])<[9,11,13,15,16.2,17,18][n]and n+1or f(p,n+1)

```

Try it online!
> 0 votes

# Answer
# BRASCA 0.5.2, 30 bytes

The G operator was added on the same day as the challenge was posted, but not specifically for this challenge.

The program assumes input as `1.x.y` at all times. Ex. `1.16` must be input as `1.16.0`.

The math is from Arnauld's JS answer, go upvote it!

```
C'.iGX$:16S>[7n@]x::*$3*++51S/

```

Try it online!

## Explanation

The second number will be called X, the third number will be called Y.

```
C                               - Set implicit output to number mode
   i                            - Turn "0-9" from char into the numbers 0-9
 '. G                           - Split stack by "."
     X                          - Remove the first number, it's not needed.
      $                         - Put X on top of the stack
       :16S>[7n@]x              - If it's more than 16, the version is 1.17.0, so print 7 and terminate.
                                - Calculate the final number:
                  ::*           -   (X**2
                     $3*+       -        + X*3
                         +      -              + Y)
                          51S/  -                  /51
<implicit>                      - Output the number

```
> 0 votes

# Answer
# Python 3, 66 bytes

```
lambda i:sum([float(i[2:])>x+8.2 for x in [.7,2,4,6.2,7.9,8.3]])+1

```

Try it online!

Explanation:

* Our input is `i`. Remove the `1.` at the start with `i[2:]`.
* Convert the rest to a number with `float`.
* For each `x` in the list, check if this is greater than `x+8.2`.
    + Why 8.2? Well, all of the finishing versions (1.8.9, 1.10.2, etc.) are greater than 8, thus saving some bytes.
    + In addition, since two of them end with .2, I can subtract that as well, saving 2 more bytes.
* Since `True` and `False` are treated as `1` and `0` by the arithmetic operators, we can use `sum` to count the number of `True`s in the list.
* This is now off by one, so we add 1.
> 0 votes

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


title: Rocket Liftoff!

text:
# Question
Title: Rocket Liftoff!
This code golf challenge is about making a rocket liftoff sequence.
Your output (STDOUT) should be equal to this:

```
Liftoff in T-10
Liftoff in T-9
Liftoff in T-8
Liftoff in T-7
Liftoff in T-6
Liftoff in T-5
Liftoff in T-4
Liftoff in T-3
Liftoff in T-2
Liftoff in T-1
LIFTOFF!

```

Rules:

* Your output must print to STDOUT.
* Your program must not raise any errors.
* This is code golf, shortest code in bytes wins.

# Answer
# Java (JDK), ~~92~~ ~~79~~ 78 bytes

```
v->{for(int i=11;i-->0;)System.out.println(i>0?"Liftoff in T-"+i:"LIFTOFF!");}

```

Try it online!

Edit: Thanks to @KevinCruijssen for -1 byte
> 5 votes

# Answer
# APL (Dyalog Unicode), 36 bytes (SBCS)

Full program.

```
↑'Liftoff in T-'∘,∘⍕¨⌽⍳10
'LIFTOFF!'

```

Try it online!

**ɩ**ndices 1 through 10
reverse them
`¨` on each number, do:
format as text
then:
`,` prepend
the entirety of:
`'Liftoff in T-'` this string
merge list of strings into character matrix (and implicitly output to stdout)

`'LIFTOFF!'` this string (implicitly output it to stdout)
> 3 votes

# Answer
# Python 2, 56 bytes

```
d=11
exec"'Liftoff in T-%d'%d;d-=1;print"*d+"'LIFTOFF!'"

```

Try it online!

Wonderful application of Using exec to remove repeated print.

-1 thanks to dingledooper who realised we can reuse the `d` variable in the exec multiplier.

## Python 2, 57 bytes

```
d=~9
while d:print"Liftoff in T%d"%d;d+=1
print"LIFTOFF!"

```

Try it online!

## Python 2, 59 bytes

```
d=10
while d:print"Liftoff in T-%d"%d+1/d*"\nLIFTOFF!";d-=1

```

Try it online!
> 3 votes

# Answer
# Ruby 2.7, 51 50 bytes

*Saved a byte using* `~9` *for* `-10`*, thanks to Sisyphus!*

```
puts (~9..-1).map{"Liftoff in T#{_1}"}<<"LIFTOFF!"

```

Try it online!

TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes.

---

# Ruby, 57 bytes

```
puts"Liftoff in T-#{11-($.+=1)}"while$.<10
puts"LIFTOFF!"

```

Try it online!
> 2 votes

# Answer
# Bash, 67 bytes

```
for i in `seq 10`;do echo Liftoff in T-$((11-i));done;echo LIFTOFF!

```

Try it online!

# Bash, 43 bytes

thanks to @Sisyphus for this suggestion.

```
seq -f'Liftoff in T%g' -10 -1;echo LIFTOFF!

```

Try it online
> 2 votes

# Answer
# Perl 5, 43 bytes

```
say"Liftoff in T$_"for-10..-1;say'LIFTOFF!'

```

Try it online!
> 1 votes

# Answer
# PowerShell Core, 37 bytes

```
10..1|%{"Liftoff in T-$_"}
"LIFTOFF!"

```

Try it online!
> 1 votes

# Answer
# Jelly, 25 24 bytes

```
“ÞÆdḂbMG:ȯ»;Ɱ⁵ṚY⁷“KçÞ»Œu

```

Try it online!

*-1 byte thanks to caird*

## Explanation

```
“ÞÆdḂbMG:ȯ»;Ɱ⁵ṚY⁷“KçÞ»Œu   Main niladic link
“ÞÆdḂbMG:ȯ»                "Liftoff in T-"
           ;               Join with
            Ɱ              each of
             ⁵             [1 to] 10
              Ṛ            Reverse
               Y           Join with newlines
                           Print and discard
                ⁷          Newline
                           Print and discard
                 “KçÞ»     "liftoff!"
                      Œu   Uppercase

```
> 1 votes

# Answer
# Nim, 54 53 bytes

```
for i in -10..<0:echo "Liftoff in T",i
echo"LIFTOFF!"

```

Try it online!

*-1 byte by using the negative numbers trick from other answers*
> 1 votes

# Answer
# 05AB1E, 30 bytes

```
TFNT-“ƒŸ€† Tÿ“'µë™ì,}’µëƒŸ!’u,

```

Try it online!

```
TFNT-“ƒŸ€† Tÿ“'µë™ì,}’µëƒŸ!’u,  # full program
 F                              # for N in [0, 1, 2, ...,
T                               # ..., 10...
 F                              # minus 1]...
                   ,            # print...
     “ƒŸ€† Tÿ“                  # "off in Tÿ"...
                                # (implicit) with ÿ replaced by...
  N                             # variable...
    -                           # minus...
   T                            # 10...
                  ì             # prepended with...
              'µë               # "lift"...
                 ™              # in title case...
                   ,            # with trailing newline
                    }           # end loop
                             ,  # print...
                     ’µëƒŸ!’    # "liftoff!"...
                            u   # in uppercase...
                             ,  # with trailing newline

```
> 0 votes

# Answer
# Deadfish~, 1402 bytes

```
{{i}ddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiicdc{{d}iiiiii}iic{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}iic{{d}iiiii}iiic{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}ic{{d}iiiiii}ddddddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}c{{d}iiiiii}dddddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}dc{{d}iiiiii}ddddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}ddc{{d}iiiiii}dddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}dddc{{d}iiiiii}ddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiiiic{{d}iiiiii}dc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiiic{{d}iiiiii}c{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiic{{d}iiiiii}ic{{i}dddd}iiiiiicdddcdddc{i}iiiicdddddc{d}icc{{d}iiiiii}iiic

```

Try it online!
> 0 votes

# Answer
# Vyxal `j`, 32 bytes

```
₀ɾṘƛ«ƛ⟇⋏∨e«¡:£` in T-`+n+;¥⇧\!+J

```

Try it Online!
> 0 votes

---
Tags: code-golf, kolmogorov-complexity
---


# Question
Title: Implement Smokey's !!/coffee command. (Part 2)
# Like the previous SmokeDetector challenge? This one is for you too ;)

> ***Note**: SmokeDetector is a bot that detects spam and offensive posts on the network and posts alerts to chat.*

# What to implement

Smokey's `!!/coffee` command uniformly at random picks one of these words (sorts of coffee):

* Espresso
* Macchiato
* Ristretto
* Americano
* Latte
* Cappuccino
* Mocha
* Affogato
* jQuery

adds it to the message: "*brews a cup of $COFFEE\_SORT for $USERNAME*"

Your task is to implement the function that takes a username as any reasonable input format, randomly (uniformly at random) picks $COFFEE\_SORT, and prints to the screen:

> *brews a cup of $COFFEE\_SORT for $USERNAME*

# Rules

Regular code-golf — the shortest answer in bytes wins ;)

*Good luck!*

# Answer
> 7 votes
# Jelly, 60 bytes

```
“¦ƘÇ=X⁸ẓÇsŻY»⁶“¢p ɼƁỴŒ?Ọi^gċ{çØLƲ`ẆĿJ$ȮȷẈv&ẋȧ>ċ8½c»ḲX⁶“Ƙa»⁶³

```

Try it online!

If you write a nilad while there's an argument Jelly just dumps it into STDOUT, which is really nice for this challenge because you don't need to worry about maintaining the list of output characters but rather just dump the outputs piece by piece.

# Explanation

```
“¦ƘÇ=X⁸ẓÇsŻY»⁶“...»ḲX⁶“Ƙa»⁶³  Main Link
“¦ƘÇ=X⁸ẓÇsŻY»                 "brews a cup of coffee for"
             ⁶                " " (dumps previous string to output)
              “...»           compressed string with space-separated coffee types
                   Ḳ          split on spaces
                    X         choose a random value
                     ⁶        " " (dumps the coffee type to output)
                      “Ƙa»    "for" (dumps the space to output)
                          ⁶   " " (dumps "for" to output)
                           ³  get the command line argument (implicit output)

```

It's the same length to compress `" for"` as to place a space and then compress `"for"`. Unfortunately Jelly compressed strings don't seem to support trailing spaces, which unlike most situations actually matters here.

# Answer
> 7 votes
# 05AB1E, ~~73~~ 72 bytes

Thanks to Kevin Cruijssen for -1 byte.

```
.•9‰dx$»w¯Ï»Å
0Ž4÷ßû‡Qβ%*mÏaQqîu<´Q™Õj•#™”„ƒoj¡¸”á9ô«Ω“brews aï›€‚ ÿ€‡ ÿ

```

Try it online!

05AB1E does have a rather small dictionary, the only words we use here are `American` and `Query`.

```
.•9‰ ... Õj•q       # compressed alphabet string
                    # "espresso macchiato ristretto latte cappuccino mocha affogato"
#                   # split on spaces
 ™                  # title case each word
  ”„ƒoj¡¸”          # compressed dictionary string "Americanoj Query"
          á         # take the letters
           9ô       # split into groups of 9
             «      # concat both lists
              Ω     # choose a random element
“brews aï›€‚ ÿ€‡ ÿ  # compressed alphabet string
                    # "brews a cup of ÿ for ÿ"
                    # where ÿ is implicitly replaced with
                    # the coffee type and the input

```

Try it with step-by-step output!

See Kevin Cruijssen's tip to understand how all these different string compression methods work.

# Answer
> 6 votes
# Charcoal, 80 bytes

```
”↶⌊<σ⪪｜ς∨▶？ρ”‽⪪”>,,↶‽¿#Ｚ\`P➙⮌\`ρL±5⭆À)⧴YQ>δＡτ1¬▶⌈…⌊$h¿ＳÀüτt9Ｗ➙β⁰№LασＵL⧴§⧴”B¦ for Ｓ

```

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

```
”↶⌊<σ⪪｜ς∨▶？ρ”

```

Print compressed string `brews a cup of` .

```
‽⪪”>,,↶‽¿#Ｚ\`P➙⮌\`ρL±5⭆À)⧴YQ>δＡτ1¬▶⌈…⌊$h¿ＳÀüτt9Ｗ➙β⁰№LασＵL⧴§⧴”B

```

Split compressed string `EspressoBMacchiatoBRistrettoBAmericanoBLatteBCappuccinoBMochaBAffogatoBjQuery` on `B` and print a random entry.

```
 for

```

Print literal string  `for` .

Print the input string.

# Answer
> 4 votes
# Python 3, ~~159~~ ~~156~~ 153 bytes

-3 bytes thanks to @Neil

-3 bytes thanks to @ovs

```
from random import*
print("brews a cup of",choice("Espresso Macchiato Ristretto Americano Latte Cappuccino Mocha Affogato jQuery".split()),"for",input())

```

Try it online!

# Answer
> 4 votes
# Retina, ~~111~~ 110 bytes

```
K`EspressOMacchiatORistrettOAmericanOLatte¶CappuccinOMocha¶AffogatOjQuery
O
o¶
@L$`.+
brews a cup of $& for $+

```

Try it online! Explanation: The `K`` stage replaces the input with a list of types of coffee, except that a byte is saved by having the next stage expand `O` to `o` followed by a newline. The `L``stage then randomly (`@` is used here as it's a random match that gets selected) selects an element of the list, and `$` tells it to output the phrase, substituting for the selected coffee and original input. Edit: I used @Leo's Retina Kolmogorov golfer to detect the duplication and save a byte.

# Answer
> 4 votes
# Scala, 150 bytes

```
s=>print("brews a cup of "+"Espresso#Macchiato#Ristretto#Americano#Latte#Cappuccino#Mocha#Affogato#jQuery".split("#")((math.random*9)toInt)+" for "+s)

```

Try it online!

# Answer
> 4 votes
# Perl 5 (`-p`), 116 bytes

```
@a=(Espresso,Macchiato,Ristretto,Americano,Latte,Cappuccino,Mocha,Affogato,jQuery);s;;brews a cup of $a[9*rand] for

```

Try it online!

114 if `$$%9` can be used instead of `9*rand`

# Answer
> 4 votes
# Bash, 123 bytes

```
a=(Espresso Macchiato Ristretto Americano Latte Cappuccino Mocha Affogato jQuery)
echo brews a cup of ${a[RANDOM%9]} for $1

```

Try it online!

119 if `$$` can be used instead of `$RANDOM`

# Answer
> 4 votes
# , ~~139~~ 137 bytes

```
cat("brews a cup of",sample(scan(,"",9),1),"for",scan(,""))
Espresso
Macchiato
Ristretto
Americano
Latte
Cappuccino
Mocha
Affogato
jQuery

```

Try it online!

-2 bytes by Dominic van Essen.

# Answer
> 4 votes
# Pyth, 104 bytes

```
%." w#5Gœz,v7‡e´‚?×ÅvNžSÒ",Oc."	y3N.Yí&öPâèq}õÑ6É«’Õ%¯ä=Ä¶/u8ƒµ;AF¢µ“€ä1•¥p.9sNšæãš<KU×Íí"\	z

```

Try it online!

Sorry for being rough on packed strings earlier, they help for shorter strings.

# Answer
> 3 votes
# JavaScript, ~~163~~ 148 bytes

-15 bytes thanks to @Arnauld

```
alert(`Brews a cup of ${'Espresso,Macchiato,Ristretto,Americano,Latte,Cappuccino,Mocha,Affogato,jQuery'.split`,`[Math.random()*9|0]} for `+prompt())
```

# Answer
> 3 votes
## Batch, 181 bytes

```
@set/ar=%random%%%9
@for %%a in (Espresso.0 Macchiato.1 Ristretto.2 Americano.3 Latte.4 Cappuccino.5 Mocha.6 Affogato.7 jQuery.8)do @if %%~xa==.%r% echo brews a cup of %%~na for %1

```

Explanation: Batch has no array type, so what I do is to loop over a list of strings and print the prefix if the suffix equals a random digit from 0-8. (Randomly choosing from 10 strings would have been slightly golfier.)

# Answer
> 3 votes
# Vyxal, 76 bytes

```
«ƛṙǐȮ:ȮGɽ≬₅⋎¶∧⊍€ƈ₄β›ɽġΠ↑∷×rv₇ṡḢ18[τ/nḞnε₴ɖ¯«ǐð\j`∞Ǔ`Wṅ⌈℅«⟑ṫrUḊ<↑5ß«$`for`⁰WṄ

```

Try it Online!

Wanna have a cup of jQuery? :P

# Answer
> 2 votes
# C (gcc), 176 bytes

```
*s[]={"Espresso","Macchiato","Ristretto","Americano","Latte","Cappuccino","Mocha","Affogato","jQuery"};f(int*u){printf("brews a cup of %s for %s",s[rand(srand(time(0)))%9],u);}

```

Try it online!

# Answer
> 2 votes
# Python 3, 154 bytes

```
from random import*
print(f"brews a cup of {choice('Espresso Macchiato Ristretto Americano Latte Cappuccino Mocha Affogato jQuery'.split())} for",input())

```

This is basically @aidan0626's code, except I used f-strings to optimize the code further. They're so useful!

# Answer
> 2 votes
# 05AB1E, 94 bytes

```
“¬àews€…ï›€‚ “’¡¾…›o î™Â¶€›o ¹´Ú•ˆÆ€„ „ƒo ¼È¶µ ¦§pÓ—Í«€¸ ›á£áa ÂÆÚƒ€›o ’™”j¡¸”á«ð¡Ω«ð«“€‡ “«s«

```

Try it online!

```
“¬àews€…ï›€‚ “                                                                   # push "brews a cup of "
              ’¡¾…›o î™Â¶€›o ¹´Ú•ˆÆ€„ „ƒo ¼È¶µ ¦§pÓ—Í«€¸ ›á£áa ÂÆÚƒ€›o ’™”j¡¸”á« # push "Espresso Macchiato Ristretto Americano Latte Cappuccino Mocha Affogato jQuery"
 ¡                                                                               # split
ð                                                                                # by spaces
   «                                                                             # concatenate top of stack with
  Ω                                                                              # random pick from list (this is $COFFEE_SORT)
         «                                                                       # concatenate top of stack with
    “€‡ “                                                                        # "for "
           «                                                                     # concatenate top of stack with
          s                                                                      # implicit input (this is $USERNAME)
                                                                                # implicit output

```

# Answer
> 1 votes
# PHP, 142 bytes

```
<?="brews a cup of ".explode(",","Espresso,Macchiato,Ristretto,Americano,Latte,Cappuccino,Mocha,Affogato,jQuery")[rand(0,8)]." for ".$argv[1];

```

Try it online!

---
Tags: code-golf, kolmogorov-complexity, random
---