# Question
Title: Expected number of rounds for this labeling scheme
# Task

Here is an interesting math problem:

> Let's say that there are \\$n\\$ indistinguishable unlabeled objects in a bin. For every "round", pull \\$k\\$ objects randomly out of the bin with equal probability, and apply a label on each object (Nothing happens to objects already having a label). Then put these \\$k\\$ objects, now all labelled, back into the bin and repeat the process until all objects have a label applied to them. What is the expected number of rounds needed to label all the objects, given \\$n\\$ and \\$k\\$?

Your task is to write a program that solves this exact math problem. Turns out, this is quite hard to calculate by hand and is better left for computers to bash out. I will list three methods of solving this problem below. You do not have to follow any of these three methods.

# Methods

### Method 1

I have asked this question on Math SE recently as I was also stumped on how to do this problem. One answer suggests the following formula: $$\sum\_{j=1}^n (-1)^{j+1} \binom{n}{j} \frac{1}{1-\binom{n-j}{k}/\binom{n}{k}}$$ I have implemented this formula in Python: Try it online!

### Method 2

Another answer from the same question provides the following formula: $${\bf e\_1}^T \left(I\_n - \left({\mathcal{1}}\_{j\geq i} {\frac{ {{n-i \choose j-i}} {i \choose k-j+i} }{n\choose k}} \right)\_{i=0,j=0}^{n-1} \right)^{-1} {\bf 1}$$ where "\\$I\_n\\$ is the \\$n \times n\\$ identity matrix, \\$\bf e\_1\\$ is the first standard basis vector of \\$\mathbb{R}^n\\$ and \\${\bf1}\\$ is the \\$n\\$-vector of all ones. And in the definition of the other matrix \\$\mathcal{1}\\$ is the indicator function, i.e. the \\$i,j\\$-element is \\$0\\$ if \\$j\<i\\$ and otherwise that quotient of binomials...," quoting from the linked answer.

I have implemented this formula in Mathematica: Try it online!

### Method 3

(This is very likely not the golfiest way for any language, but this is what I used to generate the larger test cases.)

Another way is to utilize the recursive nature of this problem, as the results of each round depends on the results of all the previous rounds. The recursive formula is as follows (\\$E\\$ is the function that actually calculates the expected value):

$$\begin{align}E(n,k)&=f(n,k,n)\\f(n,k,u)&=\begin{cases}0&\text{if }u=0\\\frac{\displaystyle\binom nk+\sum\_{i=1}^{\min(u,k)}{\binom ui\binom{n-u}{k-i}}f(n,k,u-i)}{\displaystyle\binom nk-\binom{n-u}k}&\text{otherwise}\end{cases}\end{align}$$

I have implemented this formula in Python: Try it online!

# I/O format and other rules

Your program or function should take in two positive integer values \\$n,k\\$ with \\$n\ge k\\$ and output the expected value corresponding to those values. The output can be a floating point value with an absolute/relative error under \\$10^{-6}\\$ from the true value, though the algorithm should **theoretically work** for arbitrarily large \\$n\\$ and \\$k\\$. In practice, it is acceptable if the program is limited by time, memory, or data-type size. This means that although your program may output inaccurate floating point values for certain inputs (as long as the outputs are within the allowed error as mentioned earlier), it should still theoretically be calculating the exact value of the true output.

Because the expected value is always going to be a rational number, you can also output as an exact fraction (does not need to be simplified and can be improper), if your language supports such a data type, or if you want to output a pair of numbers, the numerator and the denominator. If in doubt, always refer back to the default I/O methods.

Your program should also be **deterministic**, meaning it should always produce the same value when ran. Namely, no "running a gazillion simulations to get the experimental expected value."

# Test Cases

```
n,k -> output
1,1 -> 1
4,2 -> 3.8
6,2 -> 6.928571428571428571428571429
7,4 -> 3.779411764705882352941176471
7,7 -> 1
8,1 -> 21.74285714285714285714285714
8,5 -> 3.458181818181818181818181818
10,3 -> 9.046212999306305594338048699
12,7 -> 4.212148576244657154897357173
20,2 -> 35.30473485789483826080766262
100,7 -> 72.28020367501059456930677280
1000,69 -> 105.2447804224750397369209265
1256,5 -> 1934.893442395300917211652090

```

---

This is , so the shortest program in bytes wins!

# Answer
# 05AB1E, ~~13~~ 10 bytes

-3 thanks to @alphalpha

```
Ýsc¤/<z¹F¥

```

Attempt This Online!

Uses a variant of the first method. Ports this Jelly answer for the binomial transform.

```
Ý      calculate [0,1,...,n]
s      swap so k is on top
c      calculate [0Ck, 1Ck, ..., nCk]
¤      push the last item without poping
/      divide by it
<      subtract one
z      and inverse. Luckily for us, 05AB1E have 1/0 = 0
¹F¥    calculate the binomial transform, by calculating the differences n times.

```
> 5 votes

# Answer
Tried all three methods, with some minor changes to each for golfiness. In order:

# Wolfram Language (Mathematica), 52 bytes

```
b[i=-Range@#,++i+#].(b[-i,#2]/b@##-1)^-1&
b=Binomial

```

Try it online!

Shortest by a long shot. $$E(n,k)=\sum\_{i=1}^n{-i\choose 1-i+n}\left(\frac{i-1\choose k}{n\choose k}-1\right)^{-1}.$$

### Wolfram Language (Mathematica), 82 bytes

```
Tr@Last@Inverse@Table[Boole[i==j]-b[#-i,#2-i+j]i~b~j/b@##,{i,#},{j,#}]&
b=Binomial

```

Try it online!

Reversed both axes of the matrix, summing the last row instead.

### Wolfram Language (Mathematica), ~~85~~ ~~83~~ 82 bytes

```
{n,k}Check[1/Tr[m=b[#,i=Range@#]b[n-#,k-i]],0](n~b~k+m.#0/@(#-i))&@n
b=Binomial

```

Try it online!

Reversed the domain.
> 4 votes

# Answer
# Charcoal, ~~48~~ 42 bytes

```
ＮθＮηＩΣＥθ∕Π⁺±⊕…ιθ⁻θ…⁰η×Π…·¹⁻θι⁻Π⁻ι…⁰ηΠ⁻θ…⁰η

```

Attempt This Online! Link is to verbose version of code. Explanation: Implements a modification of a formula used by several other answers:

$$ \sum\_{i=1}^n\frac{-i\choose 1-i+n}{\left(\frac{i-1\choose k}{n\choose k}-1\right)} $$

$$ = \sum\_{i=1}^n\frac{{-i\choose n-i+1}{n\choose k}}{{i-1\choose k}-{n\choose k}} $$

$$ = \sum\_{i=0}^{n-1}\frac{{-1-i\choose n-i}{n\choose k}}{{i\choose k}-{n\choose k}} $$

$$ = \sum\_{i=0}^{n-1}\frac{\prod\_{j=i+1}^n(-j)\prod\_{j=0}^{k-1}(n-j)}{\prod\_{j=1}^{n-i}j\left(\prod\_{j=0}^{k-1}(i-j)-\prod\_{j=0}^{k-1}(n-j)\right)} $$

Previous 48-byte answer:

```
ＮθＮηＩΣＥθ∕×Ｘ±¹ιΠ⁻θ⁺…⁰η…⁰⊕ι×Π…·¹⊕ι⁻Π⁻θ…⁰ηΠ⁻⁻θ⊕ι…⁰η

```

Attempt This Online! Link is to verbose version of code. Explanation: Implements a modification of Method 1:

$$ \sum\_{j=1}^n (-1)^{j-1} \binom n j \frac 1 {1 - \binom {n-j} k / \binom n k} $$

$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \binom n j \binom n k} {\binom n k - \binom {n-j} k} $$

$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \frac {n!} {j! (n-j)!} \frac {n!} {(n-k)!}} {\frac {n!} {(n-k)!} - \frac {(n-j)!} {(n-j-k)!}} $$

$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \prod\_{i=n-j+1}^n i \prod\_{i=n-k+1}^n i} {\prod\_{i=1}^j i (\prod\_{i=n-k+1}^n i - \prod\_{i=n-j-k+1}^{n-j} i)} $$

$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \prod\_{i=0}^{j-1} (n-i) \prod\_{i=0}^{k-1} (n-i)} {\prod\_{i=1}^j i (\prod\_{i=0}^{k-1} (n-i) - \prod\_{i=0}^{k-1} (n-j-i))} $$

$$ = \sum\_{j=0}^{n-1} \frac {(-1)^j \prod\_{i=0}^j (n-i) \prod\_{i=0}^{k-1} (n-i)} {\prod\_{i=1}^{j+1} i (\prod\_{i=0}^{k-1} (n-i) - \prod\_{i=0}^{k-1} (n-j-i-1))} $$

It's then possible to factor the \\$ (-1)^j \\$ into the following product and then switch the operands of the subtraction in the denominator to correct the sign:

$$ = \sum\_{j=0}^{n-1} \frac {\prod\_{i=0}^j (i-n) \prod\_{i=0}^{k-1} (n-i)} {\prod\_{i=1}^{j+1} i (\prod\_{i=0}^{k-1} (n-j-i-1) - \prod\_{i=0}^{k-1} (n-i))} $$

However this only reduces the code to 45 bytes:

```
 ＮθＮηＩΣＥθ∕Π⁺⁻θ…⁰η⁻…⁰⊕ιθ×Π…·¹⊕ι⁻Π⁻⁻θ⊕ι…⁰ηΠ⁻θ…⁰η

```

Attempt This Online! Link is to verbose version of code.

Substituting \\$ i = n - j - 1 \\$ then results in the final formula used by the 42-byte solution.
> 4 votes

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

```
n=>g=(k,j=n,c=(a,b=k)=>!b||c(a,--b)*(a-b)/~b)=>j&&c(n,j)/(c(n-j)/c(n)-1)+g(k,j-1)

```

Try it online!

Method 1

-5 bytes from tsh

-1 from Arnauld
> 3 votes

# Answer
# Nekomata, 13 bytes

```
→r$ÇƆ/←ŗ0ɔ$ᵑ∆

```

Attempt This Online!

A port of @Command Master's 05AB1E answer. Unfortunately, Nekomata doesn't have `1/0=0`.

```
→r$ÇƆ/←ŗ0ɔ$ᵑ∆
→r              [0,1,...,n]
  $Ç            [0Ck, 1Ck, ..., nCk]
    Ɔ/          [0Ck/nCk, 1Ck/nCk, ..., (n-1)Ck/nCk]
      ←ŗ        decrement and reciprocal
        0ɔ      Append 0
          $ᵑ∆   Take the delta n times

```
> 3 votes

# Answer
# , 53 bytes

```
\(n,k,i=1:n-1)sum((`^`=choose)(-i-1,n-i)/(i^k/n^k-1))

```

Attempt This Online!

Last few test cases produce incorrect results due to numeric overflow.
> 3 votes

# Answer
# Pari/GP, ~~74~~ 64 bytes

Saved 10 bytes thanks to @alephalpha

---

Use the formula

$$E(n,k)=\sum\_{i=1}^n{-i\choose 1-i+n}\left(\frac{i-1\choose k}{n\choose k}-1\right)^{-1}.$$

---

Try it online!

```
b=binomial
E(n,k)=sum(i=1,n,b(-i,1-i+n)*(1/(b(i-1,k)/b(n,k)-1)))

```
> 1 votes

# Answer
# APL (Dyalog APL), 61 bytes

```
f←{+/(¯1*j+1)×(j!⍺)×÷1-(⍵!⍺-j←⍳⍺)÷⍵!⍺}

```

Attempt This Online!

not as efficient in bytes as possible, just a translation of formula 1.
> 1 votes

# Answer
# Maxima, ~~71~~ 70 bytes

Saved 1 byte thanks to @att

In Maxima, `binomial(-i,1-i+n)` can be written in `binomial(-i,-1-n)` to save byte(s).

---

Use the formula

$$E(n,k)=\sum\_{i=1}^n{-i\choose n+1-i}\left(\frac{i-1\choose k}{n\choose k}-1\right)^{-1}.$$

---

Try it online!

```
E(n,k):=sum(binomial(-i,-1-n)/(binomial(i-1,k)/binomial(n,k)-1),i,1,n)

```
> 1 votes

# Answer
# Jelly, 12 bytes

```
Ḷc⁹÷c’İ;0I⁸¡

```

Try it online!

A simple port of @CommandMaster’s 05AB1E answer.
> 0 votes

---
Tags: code-golf, math, combinatorics
---


title: KotH - Floating Point Prisoners Dilemma

text:
# Question
Title: KotH - Floating Point Prisoners Dilemma
## Background

So, nowadays the popular Prisoner's Dilemma variant is the Prisoner's Trilemma, where there are three options. I can easily see that being increased, so I figured

> Why settle for *three* options, when we can have ***INFINITE*** options?

Therefore, I created the Floating Point Prisoner's ?Lemma.

## Equations:

Each round, your score will be calculated as (\\$a\\$ is what Player 1 returns, \\$b\\$ is what Player 2 returns):

$$ \text{Player 1 expected score: }\quad 2ab+3(1-a)b+(1-a)(1-b) $$

$$ \text{Player 2 expected score: }\quad 2ab+3a(1-b)+(1-a)(1-b) $$

\\$3\\$ is the temptation payoff, the payoff \\$a\\$ gets if \\$a\\$ defects and \\$b\\$ cooperates. \\$2\\$ is the reward, for if both cooperate. \\$1\\$ is the punishment, for if both defect. The sucker's payoff is \\$0\\$, which is what \\$a\\$ gets when \\$a\\$ cooperates and \\$b\\$ defects.

### Explanation of what floating point numbers mean in output

Basically, an output of 0.5 means that the figurative probability (The controller is almost deterministic, only matching up contestants at random) of cooperation is 0.5. This means that since the output is closer to 1 than 0 is, the opponent gets some score, but not as much as if the output of the contestant we're focusing on was 1.

## Forbidden Stuff

* Standard Loopholes are forbidden.
* No interacting with the controller other then by returning values in the strategy function.
* No interference with other bots (with global variables, other stuff)
* Global Vars are Highly Discouraged. Instead, use the store dict.
* More stuff may be added

## Generic Stuff

It uses an equation from the wonderful fellows at https://math.stackexchange.com to determine what to do, with the floating point numbers correlating to probability of coop or defect. However, the controller is deterministic in terms of the scoring stuff, and the probabilities are not treated as probabilities. The equations are in the play function in the controller.

**NOTE:** When run, it'll sometimes print something like \[\[0, 28948.234\], \[1, 32083.23849\], \[2, 0\]\]. That's just an old debugging feature I forgot to remove.

## Technical Stuff

Create a bot that can play this Python implementation of the Prisoner's ?Lemma. Make two functions, `strategy` and `plan`, that are in a similar format as the below examples. Store is cleared after every matchup, you can change this by commenting out the line in run in the controller that says

```
self.store = {
}

```

This is a basic bot template:

```
def strategy(is_new_game, store):
  # Put Stuff Here™. is_new_game tells the function if it's a new game. returns a value between 0 and 1, where 1 = coop and 0 = defect, and in-between stuff correlates to probability of coop or defect. Store is a dict for storage.
def plan(opmove, store):
  # opmove is the opponents move last round. This function shouldn't return anything. Put pass here if you don't use this.

```

### Example Bots

♫Coop Bop Bot♫

```
#Example Contestant
def strategy(is_new_game):
  return 1

def plan(opmove):
  pass

```

Random

```
#Example Contestant
import random
def strategy(is_new_game):
  return random.random()
def plan(opmove):
  pass

```

Controller is at https://github.com/4D4850/KotH-Floating-Dilemma

Feel free to make a pull request.

# Leaderboard

```
Random, 165500.78318694307
Helped, 147835.72861717656
Cooperator, 125285.07526747975
Random Alternator, 82809.27322624522
Tit for Tat, 51139.558474789665

```

If you don't see your bot, there was an error.

Note: Helped and Random Alternator needed to be slightly modified to run without errors. Also, there was a catastrophic bug in the scoring system, that is now fixed.

# Answer
> 2 votes
# Helped

```
def strategy(is_new_game, store):
  if store and store['moves']:
    return store['moves'][-1]
  return .1
def plan(opmove, store):
  if opmove > .5:
    if store and store['moves']:
      store['moves'].append(opmove / 2)
    else:
      store['moves'] = [opmove / 2]
  else:
    if store and store['moves']:
      store['moves'].append(opmove * 2)
    else:
      store['moves'] = [opmove * 2]

```

Try it online!

`Helped` is a bot that depends on the opponent's previous moves. Picks higher next moves for lower previous moves, and lower ones for higher ones.

# Answer
> 1 votes
# Random Alternator

```
store[0] = 0
store[1] = 0
print(store)
import random
def strategy(is_new_game, store):
  if is_new_game or store[0]%100 < 10:
    store[1] += 1
    return random.random()
  else:
      store.append(store[1] + 1, (sum(store)/len(store)))
      store[1] += 1
      return sum(list(store)[1:])/len(list(store)[1:])
def plan(opmove, store):
  store.append(store[1] + 1, opmove)
  store[1] += 1
  store[0] += random.random() + random.random()
  return store

```

Randomly alternates between taking the total average of the moves and random moves in a random way (Hopefully, unexploitable).

# Answer
> 1 votes
# Tit for Tat

```
def strategy(is_new_game, store):
    if is_new_game: return 1
    return store[0]
def plan(opmove, store):
    store[0]=opmove

```

# Answer
> 1 votes
# Defector

```
def strategy(n, s):
    return 0

def plan(o, s):
    pass

```

Always defects (returns 0).

# Answer
> 1 votes
# Uppercut

```
def strategy(is_new_game,*a):
  return -1000000

def plan(opmove,*a):
  pass

```

Returns a negative number with high magnitude to get lots of points. This wasn’t disallowed in the challenge rules.

# Answer
> 1 votes
# Falling Uppercut

```
def strategy(is_new_game, store):
  if is_new_game:
    return -(1000000**2)
  return -(1000000**store["e"])

def plan(opmove, store):
  if "e" in store:
    store["e"] += 1
  else:
    store["e"] = 3

```

Modified version of Uppercut to counter bots like Helped, Random Alternator and Tit for Tat.

## Edit

This has been edited to counter the original Uppercut.

---
Tags: game, king-of-the-hill, python, floating-point
---


title: Simulate Round Robin Scheduling

text:
# Question
Title: Simulate Round Robin Scheduling
*Alternatively, guess who's doing a course on operating systems*

Round Robin scheduling is a way to schedule ready processes in an operating system. Each process in the queue is run for a certain amount of time (quantum), interrupted after that time (if not yet finished), and then added back to the ready queue for another round.

Your task today is to print the order that tasks are executed in a round robin simulation.

## The Challenge

Given a list of `[int, int]` (both \> 0), as well as a quantum, return a list of `int` representing the order that processes were executed. Assume that all the processes arrive at the same time.

The list of `[int, int]` represents a (simplified) list of processes. The two ints are the process id and service time (the time the process needs to fully run).

For example:

```
[[1, 5], [2, 10], [3, 3], [4, 12]]

```

Represents the following processes

| Process ID | Service Time |
| --- | --- |
| 1 | 5 |
| 2 | 10 |
| 3 | 3 |
| 4 | 12 |

The quantum is an integer \> 0 that represents the time slice dedicated to each process. A quantum of 4 means that each process is executed for 4 time units before being interrupted and then added to the ready queue.

If a quantum is larger than the time left on a process, then the next process is selected after the running process ends.

## Worked Example

Using the above process list (`[[1, 5], [2, 10], [3, 3], [4, 12]]`), and a quantum of `4`, the process execution order will be:

```
t = 0
             (head)     (tail)
ready queue = [1, 2, 3, 4]
time left = [5, 10, 3, 12]
Select process 1 to run for 4 time units

t = 4
interrupt process 1
              (head)  (tail)
ready queue = [2, 3, 4, 1]
time left = [10, 3, 12, 1]
Select process 2 to run for 4 time units.

t = 8
interrupt process 2
              (head)   (tail)
ready queue = [3, 4, 1, 2]
time left = [3, 12, 1, 6]
Select process 3 to run for 3 time units

t = 11
process 3 finished
             (head)  (tail)
ready queue = [4, 1, 2]
time left = [12, 1, 6]
Select process 4 to run for 4 time units

t = 15
interrupt process 4
             (head)  (tail)
ready queue = [1, 2, 4]
time left = [1, 6, 8]
Select process 1 to run for 1 time unit

t = 16
process 1 finished
              h    t
ready queue = [2, 4]
time left = [6, 8]
Select process 2 to run for 4 time units

t = 20
interrupt process 2
              h     t
ready queue = [4, 2]
time left = [8, 2]
Select process 4 to run for 4 time units

t = 24
interrupt process 4
              h     t
ready queue = [2, 4]
time left = [2, 4]
Select process 2 to run for 2 time units

t = 26
process 2 finished
              h    t
ready queue = [4]
time left = [4]
Select process 4 to run for 4 time units

t = 30
process 4 finished
no more proceses in the queue.

```

Therefore, the order of processes executed is:

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

```

## Rules

* Input can be taken as `list[list[int, int]], int`, `list[int], list[int], int`, or some other reasonable input method.
* The processes and quantum can be taken in any order.
* For example:

```
list[int: processIds]
list[int: serviceTimes]
int: quantum

```

or

```
list[int: serviceTimes]
int: quantum
list[int: processIds]

```

or any other combination.

* Output can be `list[int]`, `str` (joined on newlines, or spaces, or any constant delimiter) or some other reasonable output method.
* There will always be at least one process.
* The process ids list will always be a permutation of the range `[1, number of processes]`.
* The process ids can be 0-indexed if you want it to be for some reason. Using 0-indexing, the ids list will always be a permutation of the range `[0, number of processes]`.
* The order of the process ids list is important - processes are executed in the order they arrive (in a first come first serve manner). That is how the ready queue in an actual RR simulation works after all (FCFS selection strategy, with pre-emption on time quantums).

## Test Cases

```
processes, times, quantum => order
[1, 2, 3, 4], [5, 10, 3, 12], 4 => [1, 2, 3, 4, 1, 2, 4, 2, 4]
[5, 4, 3, 2, 1], [20, 20, 20, 20, 20], 4 => [5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5], [3, 3, 3, 3, 8], 4 => [1, 2, 3, 4, 5, 5]
[1, 2, 3, 4, 5], [3, 3, 10, 3, 8], 2 => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3, 5, 3, 5, 3]
[1], [20], 5 => [1, 1, 1, 1]
[1], [19], 4 => [1, 1, 1, 1, 1]

```

This is , so the shortest answer in each language wins.

# Answer
# Jelly, 7 bytes

```
÷Ċ⁵x"ZẎ

```

A full program that accepts `Times Quantum ProcessIds` and prints the schedule.

**Try it online!**

### How?

```
÷Ċ⁵x"ZẎ - Main Link: Times, Quantum
÷       - {Times} divided by {Quantum}
 Ċ      - ceiling -> {SlotCounts}
  ⁵     - program's third argument -> ProcessIds
    "   - {ProcessIds} zip {SlotCounts} with:
   x    -   {ProcessId} times {SlotCount}
     Z  - transpose
      Ẏ - tighten
        - implicit print

```
> 7 votes

# Answer
# Excel, 45 bytes

```
=TOCOL(IF(A2#-A3*(ROW(1:99)-1)>0,A1#,NA()),2)

```

Quantum in cell `A3`, Process IDs and Service Times in spilled, *horizontal* ranges `A1#` and `A2#` respectively.

Returns a vertical array.
> 5 votes

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

```
{0~⍨,⍉↑⍺/⍨¨⌈⍵÷⍺⍺}

```

Try it on APLgolf!

An operator that takes the quantum as `⍺⍺`, times as right argument  and 1-indexed process ids as left argument .

`⌈⍵÷⍺⍺` times divided by quantum, rounded up.
`⍺/⍨¨` For each result, make a vector with the corresponding process id repeated that many times.
Join the vectors into a rectangular matrix, padding shorter vectors with 0s.
`,⍉` Transpose matrix, then flatten into vector.
`0~⍨` Remove 0s from vector.
> 5 votes

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

```
{2*:'/-1_(#:){(1_y),(0<*|x)#,x:(*y)-0,x}[x]\y}

```

Try it online!
> 4 votes

# Answer
# Headass, 58 bytes

```
U{R])]O:]-[};{N)UO}:NE.UO[N):-E;UP^U][{N)UO}:](>):DOD]O;NE

```

Takes input as a list like `quantum, id_1, servicetime_1, id_2, servicetime_2...` with each argument on a separate line. I've gone ahead and made links for each individual test case because I know it's a bit cumbersome to translate.

Test case 1 Test case 2 Test case 3 Test case 4 Test case 5 Test case 6

### Explanation:

Pretty straightforward, just subtracts the quantum from each service time, checks if the service time has been used up, and decides whether to keep the values on the queue.

```
U{R])]O:]-[};{N)UO}:NE.  code block 0
U                        take quantum (q)
 {R])]O:]-[};            negate q and store on queue:
 {         }             loop
  R])                      if q + r2 == 0
     ]O                      store r2 on queue
       :    ;                break from loop
                           else
        ]-[                  decrement r2
                         end loop
             {N)UO}:     store the remaining inputs on the queue:
             {N)  }:     while there are still inputs
                UO         store input on queue
                    NE   go to code block 1
                      .  end code block

UO[N):-E;UP^U][{N)UO}:](>):DOD]O;NE  code block 1
UO                                   keep q at top of queue
  [                                  r2 = q
   N):                               if there are no items left on the queue
      -E                               go to block -1 (error, halt)
        ;                            endif
         UP                          print the id on top of queue
           ^                         r1 = id
            U][                      r2 = remaining service time + r2
               {N)UO}:               retain remaining values on the queue
                      ](>):          if r2 > 0
                           DO          put r1 on bottom of queue
                             D]O       put r2 on bottom of queue
                                ;    endif
                                 NE  go to code block 1

```
> 4 votes

# Answer
# Vyxal, 44 bitsv2, 5.5 bytes

```
/⌈$ẋ∩f

```

**Try it Online!**

### How?

Port of my Jelly answer.

```
/⌈$ẋ∩f - [Quantum, Times, ProcessIds]
/      - divide -> [Times/Quantum, ProcessIds]
 ⌈     - ceil -> [SlotCounts, ProcessIds]
  $    - swap -> [ProcessIds, SlotCounts]
   ẋ   - repeat -> [RepeatedProcessIds]
    ∩  - transpose -> [ProcessIdSublists]
     f - flatten -> [Schedule]

```
> 4 votes

# Answer
# K (ngn/k), ~~23~~ 21 bytes

-2 bytes from @Bubbler's improvement

```
{y[&r]@<,/!'r:-_-z%x}

```

Try it online!

Takes three arguments, `x` (quantum), `y` (processes), and `z` (times).

Based on @frasiyav's BQN answer.

* `r:-_-z%x` calculate the ceiling of the times (`z`) divided by the quantum (`x`), and store it in variable `r`
* `<,/!'` generate `0..r-1` for each value in `r`, flatten them into a list, and then grade-up them (this is related to an "occurrence count")
* `y[&r]@` use this to index into a list containing the correct number of copies of each process ID
> 4 votes

# Answer
# JavaScript (ES6), 57 bytes

Expects `(serviceTimes)(quantum)(processIds)`, using 0-indexed process IDs. Returns a space-separated string.

```
t=>q=>g=([n,...p])=>1/n?n+' '+g((t[n]-=q)>0?[...p,n]:p):p

```

Try it online!

### Commented

```
t =>            // t[] = array of service times
q =>            // q = quantum
g = ([          // g is a recursive function taking:
  n,            //   n = ID of next process
  ...p          //   p[] = array of remaining process IDs
]) =>           //
1 / n ?         // if n is defined:
  n + ' ' +     //   append n followed by a space
  g(            //   followed by the result of a recursive call:
    (t[n] -= q) //     subtract q from the n-th service time
    > 0 ?       //     if the result is positive:
      [...p, n] //       still running: put back n at the end of p[]
    :           //     else:
      p         //       kill the process by just passing p[]
  )             //   end of recursive call
:               // else:
  p             //   stop the recursion (p[] is now empty)

```
> 3 votes

# Answer
# , 21 bytes

```
(/:1#.]=]\)@#~>.@%&>/

```

Attempt This Online!

The Jelly / APL transpose approach was too verbose in J so I found a sorting based approach. Consider this example `1 2 3 4 f 5 10 3 12 ; 4`:

* `>.@%&>/` It starts the same as the APL approach dividing the times by the quantum and taking the ceiling:

```
2 3 1 3

```
* `#~` It uses that mask to duplicate the process ids in place:

```
1 1 2 2 2 3 4 4 4

```
* `(/: )@` Now we finish by applying a single sort... we just need to find the correct ordering...
* `]=]\` This creates the prefix lists with zero fill on the right, and then asks, "Where does each element equal that value?" Thus each element is compared to a row:

```
1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0
0 0 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 1 1 1

```
* `1#.` Now when we sum each row we get a running count of how many times each element has appeared so far:

```
1 2 1 2 3 1 1 2 3

```

This is exactly the ordering we need to achieve the round robin.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 56 bytes

```
f@q_=#&@@@Flatten[#~Partition~UpTo@q&/@Table@@@#,{2,1}]&

```

Try all test cases online. Defines a function named `f` that takes its arguments in a format like (for the first test case) `f[4][{{1,5},{2,10},{3,3},{4,12}}]`. The code isn't all that short, but I learned something about `Flatten` that made me want to share this approach. Using the first test case:

* `Table@@@#` evaluates to `{ {1,1,1,1,1}, {2,2,2,2,2,2,2,2,2,2}, {3,3,3}, {4,4,4,4,4,4,4,4,4,4,4,4} }`.
* `#~Partition~UpTo@q&` operates on each element of that list, yielding `{ { {1,1,1,1}, {1} }, { {2,2,2,2}, {2,2,2,2}, {2,2} }, { {3,3,3} }, { {4,4,4,4}, {4,4,4,4}, {4,4,4,4}, {4,4,4,4} } }`.
* Next we want to transpose this array (an array in which each element is a short constant list of length at most 4); but `Transpose` doesn't handle ragged lists—the idiom for that in Mathematica is `Flatten[#,{2}]`. This would yield `{ { {1,1,1,1}, {2,2,2,2}, {3,3,3}, {4,4,4,4} }, { {1}, {2,2,2,2}, {4,4,4,4} }, { {2,2}, {4,4,4,4} }, { {4,4,4,4} } }`.
* It turns out that we want to partially flatten this resulting list as well; so we could apply `Flatten[#,{1}]` to it (we could've also applied `Join` suitably). Now here's the cool bit I never realized before: `Flatten[#,{2,1}]` will cheerfully flatten the list first at the second level and then at the first level—in that "wrong" order! The result is `{ {1,1,1,1}, {2,2,2,2}, {3,3,3}, {4,4,4,4}, {1}, {2,2,2,2}, {4,4,4,4}, {2,2}, {4,4,4,4}, {4,4,4,4} }`.
* Now all that's left is to take the first element of each list (using `#&@@@`), which gives `{ 1, 2, 3, 4, 1, 2, 4, 2, 4, 4 }`.
> 3 votes

# Answer
# BQN, 16 bytes

```
{⍋∘⊒⊸⊏⌈∘÷⟜⊸/˝}

```

Try it here.

Takes the quantum as the left argument  and an array of `[serviceTimes, processIds]` as the right argument .

How it works:

```
{⍋∘⊒⊸⊏⌈∘÷⟜⊸/˝}
             ˝  # Apply between rows of the right argument:
           ⊸/    #   replicate the ids by
      ⌈∘÷⟜      #   the ceil of serviceTimes divided by the quantum.
    ⊸⊏           # Then, reorder the result according to:
   ⊒             #   the running occurrence count
 ⍋∘              #   graded by ascending order.

```
> 3 votes

# Answer
# sclin, 17 bytes

```
/ |^"*`"zip tpose

```

Try it on scline! Way simpler than I thought...

## Explanation

* `/ |^` Divide each service time by quantum and round up
* `"*`"zip` repeat each process number by previous results
* `tpose` transpose - this fortunately works with uneven lists-of-lists!

---

# sclin, 54 bytes

```
=$n.
dups"; @"&#
1_ roll0.: Q n>o0$n , -1.: Q0>"pop"|#

```

Try it on scline! Initial solution.

## Explanation

Prettified code:

```
=$n.
dups ( ; @ ) &#
  1_ roll 0.: Q n>o 0 $n , - 1.: Q 0> \pop |#

```

Takes processes input as a list of `[int int]`.

* `=$n` quantum as *n*
* `dups ( ; @ ) &#` if stack is not empty, execute next line and loop...
    + `1_ roll` rotate bottom of stack to the top
    + `0.: Q n>o` output process number
    + `0 $n , -` decrement service time by *n*
    + `1.: Q 0> \pop |#` if service time \<= 0, then pop from the stack
> 2 votes

# Answer
# 05AB1E, ~~10~~ 9 bytes

```
/îδиÅ\ζ˜þ

```

-1 thanks to Kevin Cruijssen

Try it online!
> 2 votes

# Answer
# Python, 61 bytes

```
lambda q,i:[I for Q in range(max(i)[0])for C,I in i if C>q*Q]

```

Attempt This Online!

Expects quantum,list of cost-id pairs.

## How?

Instead of updating the remaining cost in each pair we run through the unchanged list repeatedly and after each cycle update the threshold (0,q,2q,3q,...) by which processes are filtered.
> 2 votes

# Answer
# Charcoal, 23 bytes

```
Ｆ⌈Ｅθ§ι¹ＩＥΦθ››§κ¹ι﹪ιη§κ⁰

```

Try it online! Link is to verbose version of code. Takes input as a list of pairs of (process id, service time) and the quantum. Explanation:

```
Ｆ⌈Ｅθ§ι¹

```

Loop up to the maximum service time.

```
ＩＥΦθ››§κ¹ι﹪ιη§κ⁰

```

Output any processes due to be serviced at this time (i.e. their service time is higher and this is actually a multiple of the quantum.)

Would be 17 bytes if dictionary order was guaranteed:

```
Ｆ⌈ＥθιＩＥΦθ››κι﹪ιηλ

```

Attempt This Online! Link is to verbose version of code. Takes input as a dictionary and a number. Explanation:

```
Ｆ⌈Ｅθι

```

Loop up to the maximum service time.

```
ＩＥΦθ››κι﹪ιηλ

```

Output any processes due to be serviced at this time (i.e. their service time is higher and this is actually a multiple of the quantum.)
> 2 votes

# Answer
# Retina 0.8.2, ~~76~~ 75 bytes

```
\d+(?=,|$)
$*#
(?=.*, (#)+)(?<-1>#)+
@
S`,
rM!&`.+@
O$^`.+: (@+)
$1_
: @+

```

Try it online! Link includes test cases. Takes input as a list of pairs and an integer. Explanation:

```
\d+(?=,|$)
$*#

```

Convert the durations to unary.

```
(?=.*, (#)+)(?<-1>#)+
@

```

Calculate the number of times each process gets scheduled.

```
S`,

```

Split each process to its own line.

```
rM!&`.+@

```

Match each process once for each tick. This has to be done in reverse for the overlapping matches to work properly, so the processes actually come out in the wrong order.

```
O$^`.+: (@+)
$1_

```

Sort them according to the tick count and fix up the ordering.

```
: @+

```

Delete the tick counts.

(Out of interest I did try a repeat/transpose/flatten approach but the best I could do in Retina 1 was 79 bytes.)
> 2 votes

# Answer
# Scala 3, 72 bytes

A port of @loopy walt's Python answer in Scala.

---

Golfed version. Attempt This Online!

```
(q,i)=>(for{Q<-0 to i.map(_._1).max-1;p<-i;if p._1>q*Q}yield p._2).toSeq

```

Ungolfed version. Attempt This Online!

```
def f(q: Int, i: List[(Int, Int)]): List[Int] = {
    val maxC = i.maxBy(_._1)._1
    (for {
      Q <- 0 until maxC
      pair <- i
      if pair._1 > q * Q
    } yield pair._2).toList
}

```
> 2 votes

# Answer
# Uiua, 11 bytes

```
▽±.♭⍉⬚0≡↯⌈÷

```

Try it online!

```
▽±.♭⍉⬚0≡↯⌈÷    input: quantum, times, IDs
            ⌈÷     divide times by quantum and take ceiling -> occurrence count
        ⬚0≡↯      duplicate each ID that many times forming a row in a matrix,
                   padding short rows with zeros
                   for the first example, [[1,1,0], [2,2,2], [3,0,0], [4,4,4]]
    ♭⍉           transpose and flatten
▽±.               keep nonzero elements

```

Some 12- and 13-byte solutions:

```
⊏⍏⊐/⊂⊃⊐∵⇡▽⌈÷   # 12
               ⌈÷    same as the above
       ⊃            run two functions over two stack items(repetitions, ids):
   ⊐/⊂  ⊐∵⇡       ranges of repetitions concatenated; [0, 1, 0, 1, 2, 0, 0, 1, 2]
             ▽      duplicate each ID in a vector; [1, 1, 2, 2, 2, 3, 4, 4, 4]
⊏⍏                 reorder the IDs by the ascending order of the ranges

⊏⍏-⊗⊃.⍏⊃⊚▽⌈÷  # 12
⊏⍏        ⊃ ▽⌈÷    same as above
            ⊚        duplicate indices by values; [0, 0, 1, 1, 1, 2, 3, 3, 3]
    ⊗⊃.⍏           self-index and sorting order: [0, 0, 2, 2, 2, 5, 6, 6, 6],
                      [0, 1, 2, 3, 4, 5, 6, 7, 8]
   -                  subtract first from second: [0, 1, 0, 1, 2, 0, 0, 1, 2]

⊏⍏⍜⊕□⊐≡⍏..▽⌈÷   # 13
⊏⍏          .▽⌈÷     same as above, but using just duplicated ids
   ⍜⊕□⊐≡⍏.          group by itself and replace each group with range of that length

```
> 2 votes

# Answer
# Python3, 83 bytes:

```
def R(p,t,q):
 Q,s=[*zip(p,t)],[]
 for a,b in Q:s+=[a];Q+=[(a,b-q)]*(b>q)
 return s

```

Try it online!
> 1 votes

# Answer
# AWK, 68 bytes

```
a=$1{for(b=1;b<NF;){$++c=$++b;if(0<d=$++b-c){$++NF=$c;$++NF=d}}}NF=c

```

Try it online!

This program expects the first commandline argument to give the quantum. And the arguments after that are pairs of pid/service-time values. It works by iterating through the pid/time pairs, adding the pid to an output list. Then if the service time remaining is larger than the quantum, the pid and remaining time are appended to the argument. So it essentially extends the commandline arguments as needed. And the "output list" is stored at the beginning of the argument list. Each iteration consumes two values from the argument list but only adds one (the pid) to the front of the argument list. So once the all the arguments have been processed, all that's left to do is set the number of arguments to the size of the output list. The pid list if printed automatically since the "test" that sets the number of arguments has no associated code.

```
a=$1{ ... }               -- set "a" to the quantum (first arg)
.. for( ... ){ ... }      -- loop to process pairs of args
.. .. b=1;b<NF;           -- stops when at the end of args
.. .. .. $++c=$++b;       -- copy the "pid" to the output list and increment
.. .. .. if( ... ){ ... } -- "true" when service time > quantum
.. .. .. .. 0<d=$++b-c    -- set "d" to remaining service time
.. .. .. .. .. $++NF=$c;  -- append pid to end of args
.. .. .. .. .. $++NF=d    -- append remaining service time
NF=c                      -- set the number of pids to print

```
> 1 votes

# Answer
# C++ (gcc), ~~97~~ 93 bytes

```
[](auto&l,int q,auto o){for(int m;m=0,q;q=m<q?m:q)for(auto&[p,t]:l)m=t>m?t:m,t>0?o=p:o,t-=q;}

```

Try it online!

4 bytes shaved off thanks to ceilingcat. Takes a list of pairs as input, and uses an insert iterator to return the results. Explanation:

```
[](auto& l, int q, auto o) {   // Process list, quantum, output iterator
    for (int m; m = 0,         // Will track maximum time of all processes
           q;                  // As long as quantum is still non-zero
           q = m < q ? m : q)  // Limit quantum to the maximum process time
       for (auto& [p, t]: l)   // Loop over all processes
           m = t > m ? t : m,  // Update the maximum time
           t > 0 ? o = p : o,  // Output process number if time left is positive
           t -= q;             // Subtract the quantum from the time
}

```
> 1 votes

---
Tags: code-golf
---


title: Directional Run Length Decoding

text:
# Question
Title: Directional Run Length Decoding
We all know run-length decoding: A list of character-length pairs expands to a string of that many characters, so `A1B4C2` expands to `ABBBBCC`. But what if we stretch this concept to 2 dimensions?

Instead of character-length pairs, in this challenge you will be given character-length-direction triples. For example, using N/S/E/W to indicate direction, the input `A4E B5S C3W D3N E1W` should yield the output

```
AAAAB
    B
 E  B
 D  B
 D  B
 DCCC

```

You can take input in any reasonable format (such as a list of `(char, length, N/E/S/W)` like shown here, or perhaps `(0/1/2/3, length, char)`).

The input will not overlap itself, so `A5E B3W` or `A5E B4S C4W D4N` is invalid input.

The input will also not expand past the left or top edges of the string, only the bottom and right edges will be expanded.

The character will always be within the printable ASCII range.

Consistent trailing or leading whitespace that does not affect the presentation of the output is fine.

This is , so the shortest submission per language, measured in bytes, wins.

Here are a couple cases to test your entry against:

```
A4E B5S C3W D3N E1W
AAAAB
    B
 E  B
 D  B
 D  B
 DCCC

A4E B5S C3W D3N -2E -1N  2W |1S
AAAAB
 |  B
 ---B
 D  B
 D  B
 DCCC

.3S  2E ,3N  2E .5S
.   .
. , .
. , .
  , .
    .

>6E v3S <6W ^2N >5E v1S <5W
>>>>>>v
>>>>>vv
^<<<<<v
^<<<<<<

```

And here's an example implementation in JavaScript.

# Answer
> 8 votes
# Python, 120 bytes

```
def f(A):
 G=[];X=Y=0
 for c,n,(x,y)in A:
  for _ in" "*n:G+=[[]];G[Y]+=[_]*(X-~len(G[Y]));G[Y][X]=c;X+=x;Y+=y
 return G

```

Attempt This Online!

<sup> </sup>

# Answer
> 7 votes
# Charcoal, 14 bytes

```
ＷＳ✳§ι⁰×§ι¹Ｉ✂ι²

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated triples using a leading `UDLR` instead of a trailing `NSEW`. Explanation:

```
ＷＳ

```

Loop over each triple.

```
✳§ι⁰

```

Output in the direction given by the first character.

```
×§ι¹Ｉ✂ι²

```

Output the required character repeated by the length.

# Answer
> 5 votes
# Vyxal, 13 bytes

```
ṫ⅛ƛy›Y;¾J⟑÷ø∧

```

Try it Online!

Vyxal does have a built-in canvas (fork of 05AB1E's canvas element), but it partially overwrites the drawn characters, so the input has to be modified. Takes in input as a list of `[char, length, direction (0/2/4/6)]`.

```
ṫ⅛ƛy›Y;¾J⟑÷ø∧
ṫ⅛              # Push tail to global array
  ƛ   ;         # For all other elements ...
   y›Y          # Uninterleave, increment, interleave (increment the middle)
       ¾J       # Push global array (wraps tail in list), join with rest
         ⟑      # Map through list
          ÷ø∧   # Draw modified input to canvas

```

# Answer
> 4 votes
# Perl 5, 156 bytes

```
sub f{($o,$p,$c,$n,$d,@r)=@_;@_%3?$n?do{$$o[$p]=$c;f($o,$p+1+{N,-99,S,97,W,-2}->{$d},--$n?($c,$n,$d):(),@r)}:"@$o"=~s/.{98}/$&\n/gr:f([(' ')x1e4],$"='',@_)}

```

Try it online!

# Answer
> 4 votes
# , 42 bytes

```
1 :'#&u@[[`]`(u:@32$~1+>./@])}[:}:0+/\@,#'

```

Attempt This Online!

A J adverb, which modifies the list of characters to produce a verb that takes the counts as a left arg and the directions as the right arg, as complex numbers in list form.

* `[:}:0+/\@,#` Duplicate each direction by the counts, add `0 0` as a starting point, scan sum, and remove last.
* `#&u@[` Also duplicate the characters by the counts.
* `u:@32$~1+>./@]` Create a canvas of spaces of the appropriate size.
* `[`]`...)}` Update the canvas at the points computed by the scan sum, using the duplicated characters.

# Answer
> 2 votes
# Scala 3, ~~207~~ ~~166~~ 149 bytes

Port of @hyper-neutrino♦'s Python answer in Scala.

Saved so many bytes thanks to the comment of @noodle man and @Kjetil S

---

Golfed version. Attempt This Online!

```
a=>{var(g,i,j)=(Seq[Seq[Char]](),0,0);for((c,n,(x,y))<-a;_<-0to n-1){g=g:+List[Char]();g=g.updated(j,g(j).padTo(1+i,' ').updated(i,c));i+=x;j+=y;};g}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def f(A: List[(Char, Int, (Int, Int))]): List[List[Char]] = {
    var G = List[List[Char]]()
    var X = 0
    var Y = 0
    for ((c, n, (x, y)) <- A) {
      for (_ <- 0 until n) {
        if (G.length <= Y) G = G :+ List[Char]()
        while (G(Y).length <= X) G = G.updated(Y, G(Y) :+ ' ')
        G = G.updated(Y, G(Y).updated(X, c))
        X += x
        Y += y
      }
    }
    G
  }

  def main(args: Array[String]): Unit = {
    val directionMap = Map(
      "E" -> (1, 0),
      "W" -> (-1, 0),
      "S" -> (0, 1),
      "N" -> (0, -1)
    )
    val instructions = List("A4E", "B5S", "C3W", "D3N", "E1W")
    val grid = f(for (x <- instructions) yield (x(0), x.slice(1, x.length - 1).toInt, directionMap(x.last.toString)))
    for (row <- grid) println(row.mkString)
  }
}

```

# Answer
> 2 votes
# AWK, 131 bytes

```
{for(;$2--;y+=/S$/-/N$/){g[+x,+y]=$1;x>X&&X=x;y>Y&&Y=y;x+=/E$/-/W$/}}END{for(y=-1;y++<Y;print"")for(x=0;x<=X;)printf"%1s",g[x++,y]}

```

Try it online!

# Answer
> 2 votes
# BQN, 29 bytes

```
{/⟜{⌾(⊸⊑)""↑˜1+⌈´}·+`⊸-/}

```

Try it here.

Defines a 1-modifier which takes the lengths as left argument, the directions (as a list of `⟨dx,dy⟩` pairs) as right argument, and the characters as a list (string) in the role of the function  being modified.

Explanation:

The basic idea is to replicate both the characters and the directions by the lengths, do a prefix sum on the directions to get the list of indices corresponding to each character, and then use structural under to index into a blank array and place the characters at their corresponding indices.

```
{/⟜{⌾(⊸⊑)""↑˜1+⌈´}·+`⊸-/} #
                           /  # The directions replicated by lengths
                       +`⊸-   # subtracted from its own prefix sum (shifts right so starts with 0‿0)
                     }·       # becomes right argument  to inner function.
 /⟜                          # The characters replicated by lengths
    {                         # becomes left argument  to inner function.
                  ⌈´         # Get the maximum x,y values from the indices,
                1+            # add 1 to get the shape of the output,
            ""↑˜              # and take from empty string to get the blank character array.
      ⌾(⊸⊑)                  # Pick out the indices in the array
                             # and place the characters.

```

# Answer
> 1 votes
# JavaScript (Node.js), ~~119~~ 116 bytes

```
A=>A.map(([c,n,[x,y]])=>{for(_=0;_<n;_++){G[Y]=[...(G[Y]??[]).join``.padEnd(X)];G[Y][X]=c;X+=x;Y+=y}},G=[],X=Y=0)&&G

```

Attempt This Online!

This is a golfed version of the example implementation I provided. It takes the input as a list of `[char, length, [dx, dy]]`.

Explanation:

```
A.map(([c,n,[x,y]])=>{ ... },G=[],X=Y=0)&&G

```

This first assigns G (a 2d array of characters) to an empty list and X and Y both to 0. It returns G after first running the following on each character `c`, length `n`, dx `x`, and dy `y`:

```
for(_=0;_<n;_++){ ... }

```

Run `n` times:

```
G[Y]=[...(G[Y]??[]).join``.padEnd(X)];

```

Pad the Y'th list in G to length X with spaces.

```
G[Y][X]=c;

```

Set the X'th character of the Y'th list in G to `c`.

```
X+=x;Y+=y

```

Add `x` to X and `y` to Y.

# Answer
> 1 votes
# 05AB1E, ~~7~~ 6 bytes

```
ā¤Ê+ŠΛ

```

-1 byte thanks to *@CommandMaster*

Inputs as three separated lists of the same length: \\$lengths,directions,characters\\$, where the \\$directions\\$ are `0246` for `NESW` respectively.

Try it online.

If the input as a list of triplets is mandatory, it's **8 bytes** instead:

```
ø`ā¤Ê+rΛ

```

Inputs as a list of triplets \\$\[direction,char,length\]\\$, where the \\$directions\\$ are again `0246` for `NESW` respectively.

Try it online.

**Explanation:**

```
ā        # Implicitly push the first input-list of lengths, and then
         # push a list in the range [1,list-length], without popping the list
 ¤       # Push its last item (the list-length) without popping the list
  Ê      # NOT-equals check on each value, so we'll have a list of [1,1,...,1,0]
   +     # Add the values at the same positions of the top two lists together
    Š    # Triple-swap to push the list of characters and directions from the third and
         # second inputs implicitly
     Λ   # Use the Canvas builtin with these three lists as arguments
         # (after which the result is output immediately)

```

```
ø        # Zip/transpose; swapping rows/columns of the implicit input-list of triplets
 `       # Pop and push all three lists separately to the stack
  ā¤Ê+   # Same as above to change the top list of lengths
      r  # Reverse the order of the three lists on the stack
       Λ # Use the Canvas builtin with these three lists as arguments
         # (after which the result is output immediately)

```

See this 05AB1E tip of mine to understand how the Canvas builtin works, and why we increase the lengths (except for the last one) by 1 first.

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


title: Hello world! with NO repetition

text:
# Question
Title: Hello world! with NO repetition
In any programming language that existed before this question was asked, write a program (not a function) that outputs the characters `Hello world!` followed by a newline. Your program:

* should not use any character more than once (including whitespace)
* should only use ASCII characters
* should not use any built-in libraries
* should not get input (user, file, filename, system variable, internet, anything)
* should not output anything else

Winner is whoever has the most votes after 14 days and abides to the six rules.

The sixth rule is that you cannot use H9+, HQ9+, HQ9+B, HQ9++, HQ9+2D, Hello, Hello+, Hello++, Hexish, CHIQRSX9+, or Fugue. Also, all answers which require implementations that are newer than this challenge must be marked as non-competing.

---

**Disclaimer:** This question was posted with the assumption that Hello world! with limited repetition did not cause any damage to your computer or your brain in the process of coming up with the answers.

# Answer
> 38 votes
# Raku (~~29~~ 28 characters)

This was somewhat annoying, but I finally managed to make a program for this task. Thanks go to the great #perl6 community, for helping me with this task. It took me two hours, hope you enjoy. The output is completely up to specification, including a newline.

```
say
Q[@A`DO world!]~|<HeLhg>

```

There are four tokens of interest.

* `say`

This outputs the argument with new line at end. The new line after the command itself is needed as a space replacement.
* `Q[@A`DO world!]`

This is the first string. `Q[]` is for raw strings (like `r""` in Python). It can take any delimiter (or pair of them), in this case `[]`. In this case, I use this for quotes, I don't need raw string behavior.
* `~|`

This is stringwise (`~`) bitwise or (`|`) operator.
* `<HeLhg>`

`<>` is list literal, which takes space separated list of elements. In this case, it has one element, and used as a scalar, it gives a string.

# Answer
> 15 votes
# Perl 5.10+: 24 chars

```
say+He,YZX^q(567 world!)

```

OK, I think this is as short as it gets in Perl.

Run with `perl -M5.010` (or just `perl -E`) to enable the Perl 5.10+ `say` feature.

# Answer
> 14 votes
# Perl 5 with `-M5.010`, 29 bytes

```
say+He.v108
x2,q(O world!)^$"

```

Try it online!

I've gained a lot of knowledge since I first attempted this. Still not as short as the other answers, but the best I can come up with!

# Answer
> 12 votes
# Vim 7.3, 18 keystrokes

```
:h-cu
9j3wy$<C-^>P<End>r!o

```

Copies the string `Hello world` from this helpfile, which unfortunately has been removed in never versions of Vim.

# Answer
> 10 votes
# Golfscript 42 33

I might as well golf this, considering that I had to fit some of the code and all of the data in the same block with no way of delimiting the two I think this is a pretty short result. Unlike my first submission the block code is now a fully integrated part of the data, thus `{1` do not only begin the block and put a `1` on the stack, it is also the data that defines the `H`, and so forth. The array creation now includes the empty input string, which means that I don't have to crop the beginning as there is only one character between the empty string and the `H`, that character is cut away when I take every second character, and the empty string eventually is output as nothing.

```
{1wZ$Qei^Ak 3h-)ulmsogr7}.`*]2%n+

```

Online demo: http://golfscript.apphb.com/?c=ezF3WiRRZWleQWsgM2gtKXVsbXNvZ3I3fS5gKl0yJW4r

```
[{1$^(r iFNGDJUHv98oIMgtplbh4m}.`\*]6>2%n+

```

Defines a code block. Makes a copy of the code block and converts it to string. Uses the code block to iterate over the string. For each iteration the code will make a copy of the previous char value, xor it with the current char value, and subtract 1. The resulting string then has the first 6 characters removed, and every second character removed. Finally a line feed is appended.

"r iFNGDJUHv98oIMgtplbh4m" is just two undeclared variables, they do nothing, but they are carefully constructed to produce the desired result.

Online demo: http://golfscript.apphb.com/?c=W3sxJF4ociBpRk5HREpVSHY5OG9JTWd0cGxiaDRtfS5gXCpdNj4yJW4r

# Answer
> 7 votes
# Befunge-98, ~~34~~ 31 bytes

```
f"v!dlrow
+c<>a,kb@#*98e':g05-3

```

Try it online!

Uses quite a few different methods to avoid duplicated characters.

First, we use wrapping string literal to avoid using two `"`s. This adds " world!" to the stack.

Going left on the second line, we add 9 to the extra `f` to make the `o` of the "Hello". We `g`et the character from cell 5,0 (`l`) and then duplicate it. The `'` is used to fetch the letter `e`. Multiply 9 by 8 to get 72, the ASCII value of `H`. We then print it everything using `ck,`, and flip the direction with the `>` to reuse the `,` to print the newline (`a`).

# Answer
> 6 votes
# Elixir, 37 bytes

```
IO.puts~c(He#{[?n-2,108]}\x6f world!)

```

Try it online!

I can't guarantee that this would have worked back in 2014 when this challenge was posted, and Elixir was still pre-1.0 (and thus, whether it is formally "competing", but looking at their release notes, I think it should be OK). Anyway, I'm happy that I finally found a valid solution to this task using a conventional general purpose language other than Perl!

### Walkthrough

```
IO.puts     #Print with trailing newline
~c(...)     #Sigil: charlist with interpolation
He          #Start of literal string...
#{...}      #Interpolated block
[?n-2,108]  #A list of codepoints for 2 'l's
\x6f        #Hex code for 'o'
world!      #...and done!

```

# Answer
> 4 votes
# Keg, 17 bytes

```
Hel:o Wn1+rp4-d\!

```

Try it online!

# Answer
> 1 votes
# Vyxal, 6 bytes

```
kh\!+,

```

Try it Online!

Basically the normal way of printing "Hello World!" in Vyxal.

# Answer
> 1 votes
# Vim, 21 keystrokes

```
2iHelo WORLD!Escgu8h10X

```

Try it online!

Vim adds a newline at the end of the file so there's no need to add it explicitly.

### To run it locally:

1. Save the code to a file *(here hello\_world.vim)* replacing `Esc` with \`\` (`\x1b`).
2. run `vim -u NONE -s hello_world.vim hello_world.txt`.
3. exit Vim.

# Answer
> 1 votes
# Uiua, 30 bytes

```
&p+mod107\*-,:@$ H`eFMbv/5la

```

Try it online! (Note that the formatter automatically converts some ASCII tokens to Unicode equivalents, but you can verify the solution by copy-pasting the code above and running it manually.)

Verify the restrictions!

Contains two ASCII control characters; I'm assuming this is valid based on the existing Vim answers.

This code solves the duplicate character problem by finding an integer `p` and a list of integers `L` such that the cumulative product of `L` modulo `p` gives the desired string. Also, a character literal is used twice because both "convert string to a list of charcodes" and "convert a list of charcodes to string" require a character literal, and it is chosen so that the resulting `p` and `L` meet the no-duplicates requirement.

`$ <string>` is a multiline string literal that continues through lines that start with `$`  and ends at a newline after that.

```
&p+mod107\*-,:@$ H`eFMbv/5la
                $ H`eFMbv/5la    push a string literal, S
              @                  push a character literal, c
            ,:   swap and over; c S c
           -     S-c; convert S to charcodes and subtract c's charcode
         \*      cumulative product
   mod107        % 107
  +              add c; add c's charcode and convert to string
&p               print with newline

```

# Answer
> 0 votes
# Stax, 8 bytes

```
`dx/&\p4

```

Try it online!

Just a compressed string literal. Luckily Stax lets me go without the closing backtick.

# Answer
> 0 votes
An answer from https://codegolf.stackexchange.com/a/55425/118820:

> **Stuck, 0 bytes**
>
> Well, can't get shorter than that... An empty program will output `Hello, World!` in Stuck.

Even Stuck comes with 3 plugins, but we don't need they.

# Answer
> 0 votes
# Gol\>\<\>, 25 bytes

```
"v!dlrow
H>{7-5k:`e01ga}

```

Try it online!

```
"v!dlrow      push "v!dlrow " where v is the bottom of the stack
 >{           bring v to the top
 7-           subtract 7 from v to get o
 5k:          fetch 5th number down the stack which is l, and duplicate it
 `e           push e
 01g          fetch H from the code area
 a}           put 10 (newline) at the bottom of the stack
H             print the whole stack as chars from top to bottom and halt

```

# Gol\>\<\>, 30 bytes

```
"\>mX.RMkp
r<;|%q`*o+a:Fd~

```

Try it online!

Same strategy as my own Uiua answer applied to Gol\>\<\>.

Uses printing offset of 10 (`a+o`) so that the newline can be printed without an explicit stack item.

```
"\...    push a backslash and the string, and then reflect down
r<   ~   reverse stack and discard the backslash
|...Fd   repeat the loop 13 times:
o+a:       print the current number plus 10 as char
%q`*       multiply modulo 113
;        halt

```

---
Tags: popularity-contest, restricted-source, hello-world
---


title: Compile TailwindCSS to CSS

text:
# Question
Title: Compile TailwindCSS to CSS
TailwindCSS is a utility that lets one write CSS code using only HTML classes, which are then converted to CSS code with the Tailwind compiler. Ordinarily, one would write CSS in a separate file from the HTML, and reference named classes:

```
<!-- without Tailwind -->
<p class="crazy-monologue">Crazy? I was crazy once. They locked me in a room…</p>

```

```
.crazy-monologue {
  background: black;
  color: red;
  opacity: 0.5;
}

```

With Tailwind, the CSS is auto-generated:

```
<!-- with Tailwind -->
<p class="background-[black] color-[red] opacity-[0.5]">
  Crazy? I was crazy once. They locked me in a room…
</p>

```

```
/* auto-generated by Tailwind */
.background-\[black\]{background:black;}
.color-\[red\]{color:red;}
.opacity-\[0\.5\]{opacity:0.5;}

```

This is a simplified version of Tailwind; for the purposes of this challenge, all class names will be in the format `property-name-[value]`. The property name will be a `kebab-case` string, and the value will be an string consisting of alphanumeric characters and the period `.`. Note that the brackets `[` and `]` must be escaped as `\[` and `\]` in the outputted CSS selector, and the period `.` must be escaped as `\.`.

## Task

Given a class name in the above format, output the corresponding CSS. The CSS output is flexible; you may have any amount of whitespace before and after the curly braces and colons, and the semicolon is optional.

This is , so the shortest answer in each language wins.

## Test cases

Note that since the CSS output is flexible, your output does not have to be formatted exactly as these are.

```
/* in: opacity-[0.5] */
/* out: */
.opacity-\[0\.5\] { opacity: 0.5 }

/* in: background-color-[lightgoldenrodyellow] */
/* out: */
.background-color-\[lightgoldenrodyellow\] {
  background-color: lightgoldenrodyellow;
}

```

# Answer
> 6 votes
# Vyxal, 236 bitsv2, 29.5 bytes

```
\-/÷₍λ\.øBf:\\vpĿ;‡ḢṪMf`%-%{%:%}`$%

```

Try it Online!

Truly among sus.

"But lyxal what does that have to do with the challenge?"

Nothing. That's just how golfing at 11:52pm be like.

## Explained

```
\-/÷₍λ\.øBf:\\vpĿ;‡ḢṪMf`%-%{%:%}`$%
\-/÷                                 # Split input on '-' and dump
    ₍λ           ;‡                  # Parallel apply the following:
                                     #
      \.øBf:\\vpĿ                    #   Escape '[', '.' and ']'
                   ḢṪ                #   Remove the square brackets
                     M               # Prepend the property to each
                      f              # And flatten
                                 $%  # Formatting into the string
                       `%-%{%:%}`    # "%-%{%:%}"

```

Created with the help of Luminespire.

# Answer
> 4 votes
# Python, 67 bytes

```
import re
lambda x:f'.{re.escape(x)}{{{x.replace("-[",":")[:-1]}}}'

```

Attempt This Online!

The "-" is also escaped, but that's still legal CSS.

# Answer
> 3 votes
# Retina 0.8.2, ~~37~~ 36 bytes

```
-\[(.+)]
$&{$`:$1}
\W(?=.*{)
\$&
^
.

```

Try it online! Link includes test cases. Explanation:

```
-\[(.+)]
$&{$`:$1}

```

Append the CSS declaration block.

```
\W(?=.*{)
\$&

```

Escape non-word characters in the class name.

```
^
.

```

Prefix the `.` class selector.

Edit: Saved 1 byte thanks to @noodleman pointing out that the `;` is optional. 41 bytes to include the `;` and not escape `-`s:

```
-\[(.+)]
$&{$`:$1;}
[^-\w](?=.*{)
\$&
^
.

```

Try it online! Link includes test cases.

29 bytes in Retina 1.0:

```
((.+)-\[(.+))]
.$\$1\]{$2:$3}

```

Try it online! Link includes test cases. Explanation: `$\` quotes `.` and `[` characters in its argument, but the `]` needs to be quoted manually.

# Answer
> 3 votes
# JavaScript (ES6), 68 bytes

```
s=>s.replace(/[[\].]/g,"\\$&")+`{${[a,b]=s.split(/-\[|\]/),a}:${b}}`

```

Try it online!

# Answer
> 3 votes
# Ruby `-pl`, 44 bytes

After a lot of optimization it effectively became SuperStormer's Python solution.

```
$_=".#{Regexp.escape$_}{#{sub'-[',?:;chop}}"

```

Attempt This Online!

# Answer
> 2 votes
# Charcoal, 34 bytes

```
≔⪪⁻Ｓ]¦-[θ.§θ⁰-\[⪫⪪§θ¹.¦\.¦\]{⪫θ:¦}

```

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

```
≔⪪⁻Ｓ]¦-[θ

```

Remove the trailing `]` from the input string, then split it on `-[`.

```
.

```

Output the CSS class selector.

```
§θ⁰

```

Output the property name.

```
-\[

```

Output the trailing `-` and the quoted opening `[`.

```
⪫⪪§θ¹.¦\.

```

Output the property value with `.`s quoted.

```
\]{

```

Output the quoted closing `]` and the opening `{` of the declaration block.

```
⪫θ:

```

Join the property and value into a declaration and output it.

```
}

```

Output the closing `}` of the declaration block.

# Answer
> 1 votes
# 05AB1E, 24 bytes

```
…]-[ā£':æ:…{ÿ}«„[]SD'\ì‡

```

Outputs without the optional `;` to save a byte.

Try it online or verify all test cases.

**Explanation:**

```
…]-[        # Push string "]-["
    ā       # Push a list in the range [1,length] (without popping): [1,2,3]
     £      # Split the string into parts of those sizes: ["]","-[",""]
      ':   '# Push ":"
        æ   # Pop and push its powerset: ["",":"]
         :  # Replace the values in the (implicit) input-string:
            #  All "]" are replaced with "", so basically removed
            #  And all "-[" are replaced with ":"
            #  (the trailing "" of the first list is ignored)
…{ÿ}        # Surround it with curly brackets
    «       # Append it to the (implicit) input-string
„[]S        # Push "[]" as a pair of characters: ["[","]"]
    D       # Duplicate it
     '\ì   '# Prepend an "\" in front of each: ["\[","\]"]
        ‡   # Transliterate all "[" to "\[" and "]" to "\]"
            # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Scala 3, 67 bytes

```
x=>s".${x.replaceAll("\\W","\\\\$0")}{${x.replace("-[",":").init}}"

```

Attempt This Online!

# Answer
> 0 votes
# Scala 3, 180 bytes

A port of @SuperStormer's Python answer in Scala.

---

```
x=>{val e=x.replaceAllLiterally("-","\\-").replaceAllLiterally("[","\\[").replaceAllLiterally("]","\\]").replaceAllLiterally(".","\\.");s".$e{${x.replace("-[",":").dropRight(1)}}"}

```

Attempt This Online!

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


title: Befunge Comment Outline Creator

text:
# Question
Title: Befunge Comment Outline Creator
Befunge is a 2-dimensional programming language, with an instruction pointer (IP). In Befunge-98, the `;` character tells the IP to skip characters up until the next `;` (Let us call it skipping mode when the IP is skipping characters). Here is an example:

```
"This part is read into the stack" ; this part is not ; @

```

I would like to generate a `w` wide, `h` high comment outline for a Befunge-98 program. This means that an IP in normal mode (not in string mode nor in skipping mode) should enter the comment, skip over the comment and then exit in normal mode, no matter which row or column it arrives from. Additionally, the outline must be at most one character thick. That is, the bounding box of the entire comment (including outline) must be no more than `w+2` wide and no more than `h+2` high.

## Example

If `w = 5, h = 3` then a valid comment outline would be:

```
;;;;;;
;     ;
;     ;
;     ;
 ;;;;;;

```

Note that this would not be a valid comment outline:

```
;;;;;;;
;     ;
;     ;
;     ;
;;;;;;;

```

This is because in the first column, the IP would enter in normal mode, but exit in skipping mode, potentially skipping crucial code. (The same thing would happen in the 7th column, 1st row and 5th row)

This is not valid either:

```

```

This would result in the comment being interpreted as code.

## Challenge

Write a program or function that, given a width and height as input, outputs any valid Befunge-98 comment outline for that size. The width and height are guaranteed to be at least 1.

* You must output in spaces, semicolons and line breaks, unless your chosen programming language is unable to
* You may have trailing whitespace, however they can only be spaces and line breaks
* Each line may have trailing spaces
* You may alternatively take input as `w+2` and `h+2` instead of `w` and `h`
    + You may also mix between the two e.g. you can input `w+2` and `h`
* As stated above, the width of the outline must be at most 1
* There must be a `w` by `h` area inside the outline made of only spaces

## More examples

`w = 2, h = 2`

```
;;;;
;  ;
;  ;
;;;;

```

`w = 3, h = 2`

```
 ;;;;
;   ;
;   ;
 ;;;;

```

`w = 2, h = 3`

```
 ;;
;  ;
;  ;
;  ;
;;;;

```

`w = 5, h = 1`

```
;;;;;;
;     ;
 ;;;;;;

```

# Answer
> 6 votes
# Python, ~~93~~ ~~89~~ ~~85~~ ~~79~~ ~~74~~ 73 bytes

```
lambda w,h:';'*(w|1)+(';\n;'+' '*w)*h+';\n'+h%2*' '+';'*(w+~h%2+~(w^h)%2)

```

Attempt This Online!

-7 bytes thanks to Arnauld and bsoelch.

The last row is built from four parts:

1. a space if the height is odd
2. `w` semicolons
3. one additional semicolon if `h` is even
4. one additional semicolon if `w` and `h` have the same evenness.

# Answer
> 5 votes
# Jelly,  ~~23~~  19 bytes

```
aþ¬So1;Ʋ€ZṚƊ4¡ị⁾; Y

```

A dyadic Link that accepts \\$w\\$ on the left and \\$h\\$ on the right and yields a list of characters (or a full program that prints the result).

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

### How?

```
aþ¬So1;Ʋ€ZṚƊ4¡ị⁾; Y - Link: integer, W; integer, H
 þ                  - [1..W] table [1..H] with:
a                   -   logical AND
  ¬                 - logical NOT
                       -> W×H zeros
             ¡      - repeat...
            4       - ...times: four
           Ɗ        - ...action: last three links as a monad:
        €           -              for each Row:
       Ʋ            -                last four links as a monad:
   S                -                sum {Row}
     1              -                one
    o               -                {sum} logical OR {one}
      ;             -                {that} concatenate {Row}
         Z          -              transpose }
          Ṛ         -              reverse   } - rotate a quarter
              ị⁾;   - index into "; " (1-based and modular)
                  Y - join with newline characters

```

# Answer
> 4 votes
# Rust, ~~109~~ ~~100~~ ~~129~~ ~~120~~ ~~113~~ ~~112~~ 108 bytes

-4 bytes thanks to @corvus\_192

Is this what people mean when they say Rust's syntax is unreadable?

```
|w,h|{let r=str::repeat;r(";",w|1)+&r(&(r(";\n;",1)+&r(" ",w)),h)+";\n"+&r(" ",h%2)+&r(";",w+!h%2+!(w^h)%2)}

```

Attempt This Online!

At the end of the program, I have to calculate the number of semicolons to output for the last line. This forms a decision tree that can be visualized in the following table:

| w | h | result |
| --- | --- | --- |
| odd | odd | w + 1 |
| odd | even | w + 1 |
| even | odd | w |
| even | even | w + 2 |

First, I used an actual array and indexing with `n%2` to get the result, but this takes too many characters.

~~I have now converged to `w+(w&1)+2*(!(w|h)&1)` (first taking `w`, adding `1` if `w` is odd and then adding 2 if both `w` and `h` are even), but this can't be optimal.~~

~~I have now converged to `w+(!h&1)+(!(w^h)&1)` (first taking `w`, adding `1` if `h` is even and then again adding 1 the parity of `w` and `h` is equal, but that also can't be optimal. Just look at the amount of parens!~~

`w+!h%2+!(w^h)%2` seems to be the best option. Completely forgot about precedence whoops

# Answer
> 4 votes
# Charcoal, ~~22~~ 21 bytes

```
Ｆ⁴«§; ⁺ι⁺ⅈⅉ×;Ｉ§⟦θη⟧ι↷

```

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

```
Ｆ⁴«

```

Loop over the four sides of the rectangle.

```
§; ⁺ι⁺ⅈⅉ

```

Output a space if the sum of the previous dimensions is odd but a semicolon if it is even.

```
×;Ｉ§⟦θη⟧ι

```

Output the appropriate number of semicolons.

Pivot 90° so that the next iteration draws the next side of the rectangle.

(Would have saved 4 bytes to input the width and height as a tuple instead of separate values.)

# Answer
> 3 votes
# , 53 53 41 36 35 31 30 26 24 bytes

```
'; '{~1=3|+/&(3,$&5,2&|)

```

Attempt This Online!

Finally found a decent approach based on an addition table of the appropriate lists. Say our `m rows x n cols` input is `1 x 3`, which represents the dimensions of the inner box.

We construct lists for each dimension of an addition table as follows:

```
going down:

Initial number
is always 3, followed
by m 5s, followed by....
v
3
5
1     <-- Final number is 1
          since m = 1 is odd.
          Otherwise would be 0.

going across:

3 followed by n=3 fives
v
3 5 5 5 1 <-- Final number is
              is 1 again, since n=3
              is odd

```

Let's see what happens when we make a addition table:

```
  | 3  5  5  5  1
--+--------------
3 | 6  8  8  8  4
5 | 8 10 10 10  6
1 | 4  6  6  6  2

```

Next we mod by 3, and check if the result is 1, which it will be only for cells that should be a space:

```
0 0 0 0 1
0 1 1 1 0
1 0 0 0 0

```

And finally convert to spaces/semicolons:

```
;;;;
;   ;
 ;;;;

```

This procedure gives the correct result for all 4 possible even/odd combos.

# Answer
> 1 votes
# 05AB1E, 29 bytes

```
«';Ž9¦S.ΛIÉ©нi¨}®θið®OÉǝ}®Oi¦

```

Can definitely be golfed by using a different approach..

Input as pair \\$\[w+2,h+2\]\\$.

Try it online or verify all test cases.

**Explanation:**

Step 1: Create a \\$w+2\\$ by \\$h+2\\$ box of `;`, filled with spaces:

```
«         # Merge the (implicit) input-pair to itself: [w+2,h+2,w+2,h+2]
 ';      '# Push character ";"
   Ž9¦    # Push compressed integer 2460
      S   # Convert it to a list of digits [2,4,6,0]
       .Λ # Use the (modifiable) Canvas builtin with these three arguments

```

Try just step 1 online.

Step 2: Do the following actions based on whether the \\$w\\$ and \\$h\\$ are odd:

| \\$h\\$=even,\\$w\\$=even | \\$h\\$=even,\\$w\\$=odd | \\$h\\$=odd,\\$w\\$=even | \\$h\\$=odd,\\$w\\$=odd |
| --- | --- | --- | --- |
| Do nothing | Insert a space at index 1;
Remove the first character | Remove the first character
Remove the last character | Insert a space at index 0;
Remove the last character |

: Removing the first character of the multiline string basically empties the top-right corner.

Combining those actions, we have the following three things to do:

| Remove the first character | Remove the last character | Insert a space at index \\$((w+h)=odd)\\$ |
| --- | --- | --- |
| If \\$w+h\\$=odd | If \\$w\\$=odd | If \\$h\\$=odd |

Which translates to the following code:

```
I         # Push the input-pair again
 É        # Check for both whether they're odd (1 if odd; 0 if even)
  ©       # Store this pair in variable `®` (without popping)
   н      # Pop and push the first item
    i }   # If w is odd:
     ¨    #  Remove the last character of the box
®         # Push pair `®` again
 θ        # Pop and push its last item
  i     } # If h is odd:
   ð      #  Push a space character " "
    ®O    #  Push the sum of pair `®`
      É   #  Check if this sum is odd
       ǝ  #  Insert the space at that (0-based) index
®O        #  Push the sum of pair `®` yet again
  i       # If this sum is 1 (so either w or h is odd, and the other is even):
   ¦      #  Remove the first character of the box†
          # (after which the result is output implicitly)

```

See this 05AB1E tip of mine to understand how the Canvas builtin `Λ` works.
See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž9¦` is `2460`.

# Answer
> 1 votes
# Ruby, 66 bytes

```
->w,h{(a="; "*w*h)[w+h]+?;*w+a[h]+"
;#{' '*w};"*h+"
"+a[w]+?;*-~w}

```

Try it online!

We use "; " repeated (`w` * `h`) times to get the character at the corners (by indexing) without using reminder operations.

The character at the top left corner is `;` if both or none of `w` and `h` are odd so we add them together, that's why we need a loooong "; ; ; ..." string

# Answer
> 0 votes
# JavaScript (Node.js), 96 bytes

```
f=(x,y,h=y++,w=x++)=>~x?f(x-1,y,h,w)+' ;'[(Y=y>h|!y)^(x>w|!x)|Y&!x*h+!y*w+1]:y?f(w,y-1,h)+`
`:''

```

Try it online!

# Answer
> 0 votes
# sed `-E`, 158 bytes

Input is taken as `51` for w=5 and h=1. The first line adds a cheat sheet to teach `sed` counting down (of course you'd need some extra bytes for comments larger than 9) and produces the solution for w=1/h=1. Then the `w` loop adds two `;` and one  while counting down the first field. The `h` loop duplicates a line with a whitespace while counting down the second field. The next-to-last line adds a semicolon for a odd number of them. Not very slim, but probably the best to achieve with `sed`.

```
s/$/987654321\n;;\n; ;\n;;\n/
:w
s/^(.)(..*\1(\S).*;;)(.* )(.*;)/\3\2;\4 \5;/
tw
:h
s/^.(.)(.*\1(\S).*)(\n.* ;)/-\3\2\4\4/
th
s/(\n(;;)+)(;\n)/\1;\3/g
s/.*1//

```

Try it online!

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


title: 404 - Unique 404 page not found

text:
# Question
Title: 404 - Unique 404 page not found
Inspired by a polyglot ~~on the Stack Overflow 404 page~~:

# Goal

Your goal is simple, to create a polyglot that outputs the number **404**, and then terminate, in as many languages as possible.

# Restrictions

Here's the twist, there's a restriction to make it harder:

You have to write **N** programs and pick **N** languages in a particular order. the **i**th program needs to print `404` in the first **i** languages, but not in any language after the **i**th. This is to prevent very simple solutions from destroying competition

# Scoring:

* The first criterion for determining a winner is the number of languages the main program runs in.
* The second criterion is byte count, where the programs with more languages have more importance for this criterion.
* The third and final criterion is time of submission

# Clarifications:

The source codes of the programs do not need to have any relation. They're run as separate programs. Any of the programs can output trailing and/or leading whitespace. **THE PROGRAMS DO NOT HAVE TO BE SUBSEQUENCES OF EACH OTHER!**

Thanks to @MartinEnder for a better explanation!

# Answer
> 30 votes
# 54 Languages, 1331 bytes

\>\<\>, Gol\>\<\>, Foo, Befunge-93, Befunge-98, brainfuck, Brain-Flak, Python 2, Python 3, Hexagony, Perl, Ruby, Julia, Cardinal, Brainbash, Turtlèd, Deadfish~, Whitespace, Braille, Rail, Fission, ETA, Trigger, Self-modifying Brainfuck, Numberwang, Actually, Emoji, Symbolic Brainfuck, TinCan, Alphuck, Shove, Cood, Wise, Width, Whispers, Thue, Surface, Stones, evil, Set, Prelude, Gaot++, Cubix, Cubically, PATH, Commercial, Brian & Chuck, Monkeys, Nhohnhehr, Beam, AsciiDots, Alumin, Alice, Whirl

This is getting very long, so at @MDXF's suggestion, I'm moving the subprograms and comments to a gist. The program here is only the final program. Thanks to MDXF again for providing the TIO test driver.

# 54. Whirl

<pre><code>##\$"404"#N#S# , ,,#$#?@\404!?@GJlICJlGCC*G^+0%=%=+0%x&fqpqqqiipsoddddoiipsohphhhhyhhhh? 	  ?nnn4$4#!000110000011110000100000100000110000011001100000111100001110011000111000110000
#?\++++:----:++++:H@((((4O0O4O@((((()()()){}){x}x){}x()){}){}()){}){})<[-]>[-]-[<+>-----]<+x%"404"?.⌂----.++++.>11
#i(N/"404"ooo@ENTHOEONHSSEONTHOEONSETssipceaiiiiiscejiiiijeeeejapmzaeeaeueewzaeeeaeewzaeeaeueewqs??|?)999|997+|++++!999777+++++!999997+++++!
print(404)

__DATA__=1
# \"404"*CC'[-][ .-$_"404"&]
"""pp
I want 404 of this
How much is it
#  -52, Z, -1                          #
#  -48, Y, -1                          #
#  -52, X, -1                          #
[-][
x::=~404
::=
x
]<<<
> 404
>> Output 1
red up two blue up red up one blue up red up two blue up
baaaaa bleeeeeeeeet bleeeeeeeeet baaaaa bleeeeeeeeet
a now 404 dollar off!
a has been selling out worldwide!
2 LEFT
2 LEFT
2 UP
2 LEFT
2 TEACH
1 LEFT
1 RIGHT
1 BOND
1 BOND
1 TEACH
2 YELL
1 FIGHT
2 YELL
1 TEACH
2 YELL
set ! 52
set ! 48
set ! 52
+------+
|$0011\|
|/000\0|
|0/0@11|
|00  10|
|0\10/0|
|\1100/|
+------+
$'main'
 \-444o000o444omm^

[-][$++++++++++++++++++++++++++++++++++++++++++++++++++++.----.++++.#
<<<<<<```>>>>.>.>.
]
ss"""
#7777777777777777777777777777724091557093543643404➡77▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡⠎⡆⡎⡆⢐⠣⠃s&&&&~-<<:<<:<<<:<:>>>>>>>>:^||||G<>
</code></pre>

Try it online!

Whirl is described as a Turning Tarpit \[sic\], which uses only two instructions, 1 and 0. 1 rotates the current wheel of instructions (either the math wheel or the operations wheel), 0 swaps the rotation of the wheel, and two 0s executes the instruction and switches wheels. The relevant instructions are on the first line:

`000110000011110000100000100000110000011001100000111100001110011000111000110000`

```
000110000 Switch to math wheel and execute math.not (math.val = 1)
011110000 Execute math.store, (memval = math.val = 1)
10000     Execute math.add, (math.val = math.val+memval = 1+1 = 2)
010000    Execute math.store (memval = math.val = 2)
0110000   Execute math.multiply, (math.val = math.val*memval = 2*2 = 4)
01100     Execute math.store (memval=math.val) and switch to the ops ring
110000    Execute ops.one (ops.val = 1)
011110000 Executes ops.intio, printing memval (4)
11100     Add one to memory pointer (memval=0)
1100      Execute maths.nop to switch back to ops ring
011100    Execute ops.intio, printing memval (0)
01100     Execute maths.store, (memval=maths.val=4)
00        Execute maths.intio, printing memval (4)

```

The leading 01s cancel each other out, and the trailing 01s cause a floating point exception.

Edit: fixed a *bunch* of broken stuff

(Commands to be careful about in the future: `UDLR%"[.]o473psjw`)

If any programs work for future languages or don't work for current or previous languages, please comment.

# Answer
> 20 votes
# 53 languages, 2789 bytes

Bash, Foo, Implicit, Charcoal, Emoji, \>\<\>, rk, Brain-Flak, C, Set, Cood, Arcyou, TRANSCRIPT, S.I.L.O.S, Commercial, C++, Braille, Deadfish~, Memescript 1.0, ETA, Python 1, Python 3, PARI/GP, Lily, Fission, Decimal, Cubically, Bitwise, TinCan, Whispers, Thue, Emotinomicon, what??!, Ook!, evil, Lennyfuck, Blablafuck, Stones, TacO, COW, Symbolic Brainfuck, Underload, Rail, Reticular, Gaot++, PATH, axo, Monkeys, Nhohnhehr, xEec, VTFF, K-on Fuck, Churro, and Forked. Try everything online in the test driver!

Join us in the chatroom for this challenge!

---

This post got way too large so here's a gist containing my progress. Current final program:

# Forked

```
#undef l" 404"p;((((\)0)0)0)0;(4⏬0⏬4⏬«404»[:5*11-1/1]%&)(404)S^/*NNNNTNNEONHSSEONTHOEONiisoddddoiisohOok! Ook! Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook? Ook! Ook? Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. ????!?!!?!??!!!???????????????!?!!!?!????!??????????????!!??!??!??!????!⎚404»404➡ to for the and of to to to to to is the and  a to to to to a and and and and a ;n4n0n4
#11404D301          \4%0%p%&
""""echo 404|| rk:start int x = 404 print: x rk:end R"404"*
exit;
#;
OUT &52 &1
OUT &48 &1
OUT &52 &1 */
#include<stdio.h>
main(){char aA[]={37,100,0};printf(aA,404);}/*<<<<<mzaeeeaeeaaaawuuuuwaaaa what the frick frack backtrack snick snack tic tac snick snack patty wack diddily dack tic tac diddily dack frick frack quarterback frick frack
x::=~404
::=
x #
set ! 52
#;⠎⡆⡎⡆⢐⠣⠃▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡(♥ ͜ʖ♥)( ͡°((∩ ͡° ͜ʖ ͡°)⊃━☆ﾟ.*( ͡° ͜ʖ ͡°)ᕦ( ͡°ヮ ͡°)ᕥ(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)) ͡°)(∩ ͡° ͜ʖ ͡°)⊃━☆ﾟ.*( ͡° ͜ʖ ͡°)(> ͜ʖ<)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(♥ ͜ʖ♥)(> ͜ʖ<)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)(> ͜ʖ<)うんうんうんうんたんたんたんたんうんうんうんたんうんたんうんうんうんうんうんたんたんうんたんたんうんたんたんうんたんたんうんたんたんたんたんたんうんうんたんうんたんうんたんうんうんうんたんたんうんたんたんうんたんたんうんたんたんたんうんうんうんたんうんうんたんうんうんたんうんうんたんうんたんうんうん {o}===}{======={o}{o}}{======={o}{o}===}{======={o}
> 404
>> Output 1
I want 404 of this.
How much is it?
Ju is here.
>Ju, 404
>X Ju
b = 404
printInt b ;
set ! 48 MoOMoOMoO
set ! 52 MoOOOMmoO
+--------+
|$00110\ |
|/00001/ |
|\11000\ |
|/11000/ |
|\0100 \ |
|        | baaaaa bleeeeeeeeet
|  404p@ |
|        |
+--------+
$'main': OOMmOoOOM ;
 \-444o000o444o-{<$$^- >}+{-----v}+.----.++++.#
#  bleeeeeeeeet baaaaa ^        < bleeeeeeeeet >
2 LEFT
2 LEFT
2 UP
2 LEFT
2 TEACH
1 LEFT
1 RIGHT
1 BOND
1 BOND
1 TEACH
2 YELL
1 FIGHT
2 YELL
1 TEACH
2 YELL
red up two blue up red up one blue up red up two blue up ;
o now 404 dollars off!
o has been selling out worldwide!
#  -52, Z, -1                          #
#  -48, Y, -1                          #
#  -52, X, -1                          #
⡆⡎⡆⢐⠣⠃((((p 404)((()(((()()()){}){}){}){}){}){}){}) h#4 o# h#0 o# h#4 o# """
print(404)#"*/

```

Try it online!

My new (-ly implemented) esolang!

# Answer
> 13 votes
# 34 Languages, 387 characters

**Jelly, , Pyon, Proton, Python 3, Python 2, Python 1, Perl 6, Perl 5, Ruby, bc, Pari/GP, brainfuck, Emoji, Emotinmicon, Charcoal, Braingolf, Whitespace, Deadfish~, Deadfish, Self-modifying Brainfuck, Symbolic Brainfuck, Numberwang, Cardinal, Actually, Fission, Prelude, Brain-Flak (BrainHack), Alphuck, Deadfish x, TacO, Braille, rk, evil**

This answer is getting very long so here is the full answer. From now on only the last program will be kept here.

If anyone finds that one of the programs is broken for one language or one program works for a language it shouldn't, let me know.

```
print(404)
+1#<[-]>--[<+>-----]"404".⌂<+.----.++++.404➡⎚404»___pppissiiiisiiiio▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡sipceaiiiiiscejiiiijeeeejaxxcxxxcxxxKddddKcxxxx7777777724091557093543643%R"404";77999++++++++!++++++++6+1+!++++++5++++!> @p404 sp7 rk:start print: "404"77szaeeaeueewzaeeeaeewzaeeaeueew

+1#((a(()a((()(((()()())a{})a{})a{})a{})a{})a{})a{})

+1#ṛ“Nạç»⠎⡆⡎⡆⢐⠣⠃

```

Try it online!

# Answer
> 11 votes
# 11 languages, 10 bytes

### Pyon

```
print(404

```

### Pyon, Python 2

```
print 808//2

```

### Pyon, Python 2, Python 1

```
print None or 404

```

### Pyon, Python 2, Python 1, Python 3

```
die=0
print(die or 404);

```

### Pyon, Python 2, Python 1, Python 3, Lua

```
print(None or 404)

```

### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5

```
print(404 or 0)

```

### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby

```
;print("40"+"4")

```

### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4

```
print("40"+"4")

```

### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4, Perl 6

```
print(404**1)

```

### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4, Perl 6, Julia

```
print(404);

```

### Pyon, Python 2, Python 1, Python 3, Lua, Perl 5, Ruby, Swift 4, Perl 6, Julia, Lily

```
print(404)

```

# Answer
> 6 votes
# 4 Languages: CJam, Python, Underload, \>\<\>

The following works in CJam but not Python, Underload, or \>\<\>:

```
404

```
* To CJam: This pushes the literal `404` to the stack. The program ends, and the `404` is output.
* To Python: This program consists of a single expression `404`. The expression is evaluated, and the program terminates.
* To Underload: `4` and `0` are invalid commands, so the TIO interpreter simply ignores them, and the program terminates.
* To \>\<\>: `404` pushes `4`, `0` and `4` to the stack. The IP wraps around to the beginning, and the program repeats infinitely.

---

The following works in CJam or Underload (though it errors) but not Python or \>\<\>:

```
N(404)S;(\

```
* To CJam: `N` pushes a string (array of characters) containing a newline to the stack. `(` pops the single character (a newline) out of the string. `404` pushes `404` to the stack, and then `)` increments it to give `405`. `S;` pushes a spaces and then immediately deletes it. `(` decrements again to get `404`, and then `\` swaps the newline and the `404`. `404\n` is output (the empty array is displayed as nothing).
* To Underload: `N` is ignored. `(404)` pushes the string `404` to the stack. `S` outputs it. `;` is ignored. `(` causes the interpreter to try to look for a closing `)`, but as none is found, the program segfaults.
* To Python: This is invalid syntax (the expression `N(404)` is followed by an identifier `S`, which is malformed), so the program errors.
* To \>\<\>: `N` is an invalid instruction, so the program errors.

---

The following works in CJam (though it errors), Underload, or Python, but not \>\<\>:

```
[]
Le=404
+Le#(404)S
(print(404))

```
* To CJam: `[]` pushes the empty array to the stack, and `L` pushes the empty array to the stack. `e=` counts the number of occurrences of `[]` in `[]`, giving `0`. `404` pushes `404` to the stack. `+` adds the two numbers together, giving `404`. `L` pushes the empty array to the stack again, and `e#` creates a comment that lasts until the end of the line. `(` tries to pop an element out of an array, but since the top stack element is the empty array `[]`, the program errors. `404` is still output.
* To Python: `[]` is a statement consisting of a no-op instruction. `Le=404` defines a variable `Le` to be equal to `404`. `+Le` takes the unary plus of the variable `Le` (a rather useless operation) and the result is discarded. `#(404)S` is a line comment. `(print(404))` prints 404.
* To Underload: The only relevant part is `(404)S`, which pushes `404` to the stack and outputs it. `(print(404))` pushes `print(404)` to the stack, but nothing is done with it and the program terminates.
* To \>\<\>: `[` tries to pop a number off the top stack on the metastack, and then pop that many elements off that stack and make them into a new stack which is then pushed to the metastack. There is no number on the stack, so the program errors.

---

The following works in CJam (though it errors), Python, Underload, and \>\<\>:

```
"404nnn;\
"
Le=404
+Le#(404)S
(print(404))

```
* To CJam: Most of what I said last time applies here. Instead of being `[]`, we now have a string literal, but the content is still unimportant.
* To Python: Most of what I said last time applies here. Instead of being `[]`, the unused first expression is now a string literal, but the content is still unimportant.
* To Underload: Everything I said last time applies here. All of the commands are still ignored.
* To \>\<\>: The `"` begins string mode, and the IP wraps around the first row pushing every character code it sees to the stack (this is unimportant). The IP wraps around and hits `"` again, which exits string mode. `404` pushes the digits `404` to the stack, and then `nnn` outputs each of them (technically, this happens in reverse order, but since 404 is a palindrome this doesn't matter). `;` ends the program.

# Answer
> 6 votes
# 8 Languages, 498 Bytes

## BFFuck

```
outc(52)
outc(48)
outc(52)

```

## BFFuck, Python

```
print(404)

```

`print` prints a number in Python, while using `print()` with a string without quotes it prints out the string in BFFuck.

## BFFuck, Python, Brainfuck

```
print(404)#+++++++[>+++++++<-]>+++.----.++++.

```

BFFuck and Python both support `#` as comments.

## BFFuck, Python, Brainfuck, Befunge-93

```
#["404",,,@]
print(404)#+++++++[>+++++++<-]>+++.----.++++.

```

## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus

```
#["404",,,@]
print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+.-+++++.-

```

`-` in PlusOrMinus is the same as `.-` in BF, while `.` is an ignored character in PlusOrMinus

## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus, Deadfish

```
#["404",,,@]iisoddddoiiso
print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+.-+++++.-

```

## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus, Deadfish, Alphuck

```
#["404",,,@]pppiisoddddoiisosaeaeaepaepiceeeasccsajiiiijeeeej
print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+.-+++++.-s

```

The hardest, because it mixes up with Python and Deadfish.

## BFFuck, Python, Brainfuck, Befunge-93, PlusOrMinus, Deadfish, Alphuck, oOo CODE

```
#["404",,,@]pppiisoddddoiisosaeaeaepaepiceeeasccsajiiiijeeeej
print(404)#++++++++++++++++++++++++++++++++++++++++++++++++++++.-+++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+.-+++++.-saazzzZzZzzzZzZzzzZzZzZzzzzZzZzZzZzzzzZZzZZzZZzZzzzzZZzzZzzZzZZzzzZZz
#ZzzZzzZzzZzzZZzZzZZzZZzZZzZZZz

```

# Answer
> 4 votes
# 6 Languages Brain-Hack, Brain-Flak, Brain-Fuck, Foo, Javascript, Alphuck

More to come!

## Brain-Hack

```
#(((()((()(((()()()){}){}){}){}){}){}){})

```

Prints 404 in Brain-Hack

## Brain-Hack, Brain-Flak

```
(((()((()(((()()()){}){}){}){}){}){}){})

```

## Brain-Hack, Brain-Flak, Brain-Fuck

```
(((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++.

```

Uses comments in Brain-Flak to print it

## Brain-Hack, Brain-Flak, Brain-Fuck, Foo

```
"404"
(((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++.

```

## Brain-Hack, Brain-Flak, Brain-Fuck, Foo, Javascript

```
console.log("404")
//(((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++.

```

## Brain-Hack, Brain-Flak, Brain-Fuck, Foo, Javascript, Alphuck

```
console.log("404")
//(((()((()(((()()()){}){}){}){}){}){}){})#-[<+>-----]<+.----.++++.>-.++++.iaipiiiiiaecsaejiiiijeeeej

```

# Answer
> 3 votes
# 5 languages (87 bytes)

### Pyon

```
print(404

```

Try it online!

### Python 2

```
print(404)

```

Try it online!

### Brain-Flak (BrainHack)

```
print(404)#(((()((()(((()()()){}){}){}){}){}){}){})

```

Try it online!

### brainfuck

Taken from Jo King's answer because I wasn't able to come up with a brainfuck code that had the brackets balanced (Brain-flak restriction).

```
print(404)#(((()((()(((()()()){}){}){}){}){}){}){})-[<+>-----]<+.----.++++.>

```

Try it online!

### 05AB1E

Note that this also works with Ohm.

```
#404q
print(404)#(((()((()(((()()()){}){}){}){}){}){}){})-[<+>-----]<+.----.++++.>

```

Try it online!

Thanks to Jo King for -6 bytes.

# Answer
> 1 votes
# 2 Languages, 24 bytes, Python and Batch

# Program 1: Python 3

```
print('404')

```

# Program 2: Python 3 and Batch

```
print('404')#|echo 404

```

After the the hash comments the rest of the code in python, and the | is a statement in bash to do this if the other command fails.

# Answer
> 0 votes
# 2 Languages, 53 bytes: C and Python

Let's start things off with something simple.

## Program 1: C

```
int main(){printf("404");}

```

## Program 2: C and Python

```
#define print(X)int main(){printf("404");}
print(404)

```

TIO links:

This is just an example, and will probably be beaten **many** times over.

# Answer
> 0 votes
# 4 languages, 91 bytes

# C++

```
#ifdef __cplusplus
#include "stdio.h"
int main(){printf("%d",404);}
#endif

```

# C++, C

```
#include "stdio.h"
int main(){printf("%d",404);}

```

Removes the C++ macro

# C++, C, Befunge

```
#define A "404",,,@
#include "stdio.h"
int main(){printf("%d",404);}

```

Adds a macro that will be ignored in C++, but read as code in Befunge.

# C++, C, Befunge, Python

```
#define A "404",,,@
#include "stdio.h"//\
print(404);'''
int main(){printf("%d",404);}//'''

```

Ads a piece of code that causes the next line to be a comment in C, but not in Python (`//<backslash>`)

---
Tags: code-golf, polyglot, rosetta-stone
---


# Question
Title: Convert a Gaussian integer to its positive form
We already have a challenge for computing the GCD of two Gaussian integers, but that challenge explicitly allows to choose any of the four possible values.

Your task now is to bring the Gaussian integer computed by the GCD in the following normal form:

1. The result differs from the original number by a factor of `1`,`i`,`-1` or `-i`
2. The result is zero, or the real part is positive
3. The imaginary part is non-negative

Input: A Gaussian integer (complex number with integer real and imaginary parts)
Output: The normal form (see above) of that Gaussian integer

## Examples:

```
0 -> 0
5 -> 5
2i -> 2
1+i -> 1+i
1-i -> 1+i
3-5i -> 5+3i
-3+5i -> 5+3i
3+5i -> 3+5i
-3-5i -> 3+5i

```

## Rules

* You can use pairs instead of complex numbers for input/output
* If your language has a built-in for this operation consider adding a non built-in solution as well
* This is the shortest solution wins

# Answer
# , 14 bytes

Takes input as a complex number.

```
(0,o.%2)&|&.*.

```

Attempt This Online!

Convert to polar coordinates, take the angle modulo \\$\frac\pi2\\$, convert back.

The first rule allows for 90˚ or \\$\frac\pi2\\$ rotations on the complex plane, the other two rules specify the result should be in the upper-right quadrant or on the non-negative part of the real axis.
This means the resulting complex number should have an angle in \\$\left\[0,\frac\pi2\right)\\$ and the same magnitude as the input.

---

# , 12 bytes

Takes input as a pair of integers.

```
||.~1=2|@#.*

```

Attempt This Online!

Take the absolute value of both values and swap them if:

* one is negative, the other positive, or
* the first (real) part is zero.
> 10 votes

# Answer
# Python, 46 bytes

```
f=lambda x,y:f(-y,x)if(x|y)*(y|x-1<0)else(x,y)

```

Attempt This Online!

* -25 bytes thanks to Arnould and Bsoelch
* -3 bytes thanks to Arnould
* -1 byte thanks to The Thonnu
> 5 votes

# Answer
# Jelly, 9 bytes

```
×ƬıÆiṠ$ÞṪ

```

A monadic Link that accepts the Gaussian integer as a complex number and yields a complex number.

**Try it online!**

### How?

```
×ƬıÆiṠ$ÞṪ - Link: Gaussian integer, G
  ı       - imaginary unit
 Ƭ        - starting with G, collect up while distinct applying:
×         -   multiply by {imaginary unit}
       Þ  - sort by:
      $   -   last two links as a monad:
   Æi     -     convert to [real, imaginary] parts
     Ṡ    -     signs (-x:-1, 0:0, x:1)
        Ṫ - tail

```
> 4 votes

# Answer
# JavaScript (ES6), 32 bytes

*-3 bytes thanks to alephalpha*

Expects `(real, imaginary)`. Returns `[real, imaginary]`.

```
f=(r,i)=>r<!!i|i<0?f(-i,r):[r,i]

```

Try it online!
> 3 votes

# Answer
# Vyxal, 6 bytes

```
±BṅßǓȧ

```

Try it Online!

Port of jelly with conditional execute rather than repeating 0 or 1 times
> 3 votes

# Answer
# Retina 0.8.2, 76 bytes

```
\bi
1i
^-?(\d+)i?$
$1
^-(\d+)([+-].*)
$1-$2
--
+
(.+)-\+?(.+)i
$2+$1i
\b1i
i

```

Try it online! Link includes test cases. Explanation:

```
\bi
1i

```

Change `i`, `+i` and `-i` to `1i`, `+1i` and `-1i`.

```
^-?(\d+)i?$
$1

```

Change multiples of powers of `i` to their absolute value.

```
^-(\d+)([+-].*)
$1-$2

```

If the real part is negative then negate the whole value.

```
--
+

```

Fix up a double negation of the imaginary part.

```
(.+)-\+?(.+)i
$2+$1i

```

If the imaginary part is negative then multiply by `i`.

```
\b1i
i

```

Change `+1i` to `+i`. (It can't be `i` or `-i` at this point.)
> 2 votes

# Answer
# Jelly, 6 bytes

Input and output as a pair of integers. Port of my second J answer.

```
ṠḄỊṙ@A

```

Try it online!

```
Ṡ        -- sign of each integer
 Ḅ       -- convert from binary
  Ị      -- insignificant / absolute value <= 1
   ṙ@    -- this number of times (0 or 1), rotate ...
     A   -- the absolute value of each integer

```
> 2 votes

# Answer
# , 37 bytes

```
\(x)complex(,,,Mod(x),Arg(x)%%(pi/2))

```

Attempt This Online!

Port of the first approach in J answer by ovs.

Inputs and outputs complex numbers.
> 2 votes

# Answer
# Charcoal, 32 bytes

```
≔Ｅ²ＮθＦ⁴«⊞υθ≔Ｅ⮌θ⎇λκ±κθ»Ｉ⌈Φυ¬›⁰§ι¹

```

Try it online! Link is to verbose version of code. I/O is a pair of integers. Explanation:

```
≔Ｅ²Ｎθ

```

Input the Gaussian integer.

```
Ｆ⁴«⊞υθ≔Ｅ⮌θ⎇λκ±κθ»

```

Multiply it by the powers of `i`.

```
Ｉ⌈Φυ¬›⁰§ι¹

```

Filter out those values with negative imaginary parts and take the remaining value with the largest real part.

There are three cases:

* If the Gaussian integer is zero, then all of the values will be zero, and so the output will be zero.
* If the Gaussian integer is a non-zero multiple of a power of `i`, then only one of the values will have a positive real part, and this is the value we want.
* If the Gaussian integer has neither real nor complex part zero, then there will be two values with positive real parts, but one will have a negative imaginary part which will have been filtered out, so we obtain the value with both parts positive.
> 1 votes

# Answer
# PARI/GP, 35 bytes

```
f(x,y)=if(x<!!y||y<0,f(y,-x),[x,y])

```

Attempt This Online!

Takes input as `real,imag` and outputs `[real,imag]`.
> 1 votes

# Answer
# Nekomata, 7 bytes

```
±đZ≠nŘA

```

Attempt This Online!

A port of @ovs's Jelly answer.

Takes a pair of integers as input, and outputs a pair of integers.

```
±đZ≠nŘA
±           Sign
 đ          Split the pair into two integers
  Z         Check if the second integer is non-zero
   ≠        Check if the two integers are not equal
    n       Return 0 if the check fails, 1 if it passes
     Ř      Rotate the input that many times
      A     Absolute value

```
> 1 votes

# Answer
# ARM64 machine code, 28 bytes

```
 b40000a1
 aa0003e2
 cb0103e0
 aa0203e1
 b7ffffa1
 b7ffff80
 d65f03c0

```

Assembly source:

```
    .text
    .global make_positive
    .balign 4
make_positive:
    // If z is already real, jump directly to check if the real part is nonnegative
    cbz x1, check_real_part

multiply_again:
    // multiply by i
    mov x2, x0
    neg x0, x1
    mov x1, x2

    // see if both parts nonnegative

    tbnz x1, #63, multiply_again
check_real_part:
    tbnz x0, #63, multiply_again
    ret

```

This function takes the real and imaginary parts as 64-bit signed integers in x0 and x1 respectively, and returns the result in the same two registers. This is in keeping with usual ARM64 calling conventions for something like `struct complex { int64_t re, im; };` passed by value.

The basic algorithm is:

```
do {
    z *= i;
} while (z.im < 0 || z.re < 0);

```

The only case for which this doesn't work is if the starting value of `z` is positive real. So if z is pure real (`z.im == 0`), we jump directly to the `z.re < 0` test; if that branch is not taken then `z` is already nonnegative real and we are done.

Spending three instructions to multiply by `i` seems like a lot, but the issue is that we have to do it in place, and there's no "swap registers" instruction so we need a temporary third register.

Note that if either part of the input is -2^63 (`LONG_MIN`) then the function will enter an infinite loop. However this should be disallowed anyway since the normal form of such a number cannot be represented in signed 64-bit.

## Branchless version, 36 bytes

As a bonus, I also tried writing a branchless version, but so far have only been able to get down to 36 bytes. The idea is to conditionally multiply by `-1` and `i` in turn

```
        .text
        .global make_positive_branchless
        .balign 4
make_positive_branchless:
        // if real part is negative, multiply by -1
        cmp x0, #0
        cneg x2, x0, lt
        cneg x3, x1, lt
        // if real part was zero and imaginary part now positive, we must negate again
        // so that multiplication by i gives a positive real result
        ccmp x3, #0, #4, eq // nZcv, for which GT is false
        cneg x3, x3, gt
        // now if imaginary part is negative, multiply by i
        cmp x3, #0
        csneg x0, x2, x3, ge
        csel x1, x3, x2, ge
        ret

```
> 1 votes

# Answer
# Scala, 67 bytes

Fixed underlying error thanks to the comment of @bsoelch

---

Port of @mousetail's Python answer in Scala.

---

```
def f(x:Int,y:Int):(Int,Int)=if((x|y)!=0&(y|x-1)<0)f(-y,x)else(x,y)

```

Try it online!
> 0 votes

---
Tags: code-golf, complex-numbers
---