title: Sample the Pareto Distribution

text:
# Question
Title: Sample the Pareto Distribution
The Pareto Distribution is a probability distribution that comes up a lot in nature. It has lots of special properties, such as an infinite mean. In this challenge, you will output a number sampled from this distribution.

The Pareto Distribution is defined to be greater than or equal to `x` with probability `1/x`, for all `x` greater than or equal to 1.

Therefore, a number sampled from this distribution is greater than or equal to 1 with probability 1, greater than or equal to 2 with probability exactly 1/2, greater than or equal to 3 with probability exactly 1/3, greater than or equal to 11.4 with probability exactly 1/11.4, and so on.

Since you will sample this distribution, your program or function will take no input, and output a random number, with the above probabilities. However, if your program doesn't perfectly match the above probabilities due to floating-point impression, that's OK. See the bottom of the challenge for more details.

(This is called the Pareto Distribution with alpha 1 and lower bound 1, to be exact)

Here's 10 example draws from this distribution:

```
1.1540029602790338
52.86156818209856
3.003306506971116
1.4875532217142287
1.3604286212876546
57.5263129600285
1.3139866916055676
20.25125817471419
2.8105749663695208
1.1528212409680156

```

Notice how 5 of them are below 2, and 5 are above 2. Since this is the average result, it could have been higher or lower, of course.

Your answer only needs to be correct up to the limits of your floating point type, real number type, or whatever else you use, but you must be able to represent numbers at at least 3 decimal digits of precision, and represent numbers up to 1,000,000. If you're not sure whether something is OK, feel free to ask.

This is code golf.

---

Details about imprecision:

* For each range `[a, b]`, where `1 <= a < b`, the ideal probability that the sample would fall in that range is `1/a - 1/b`. The probability that your program produces a number in that range must be with `0.001` of `1/a - 1/b`. If `X` is the output of your program, it is required that `|P(a <= X <= b) - (1/a - 1/b)| < 0.001`.
* Note that by applying the above rule with `a=1` and `b` sufficiently large, it is the case that your program must output a number greater than or equal to 1 with at least probability 0.999. The rest of the time it may crash, output `Infinity`, or do whatever else.

I'm fairly certain that the existing submissions of the form `1/1-x` or `1/x`, where `x` is a random float in `[0, 1)` or `(0, 1)` or `[0, 1]`, all satisfy this requirement.

# Answer
# MATL, 3 bytes

```
1r/

```

Try it online! Or estimate the resulting probabilities by running it 10000 times.

### Explanation

```
1    % Push 1
r    % Push random number uniformly distributed on the open interval (0,1)
/    % Divide. Implicitly display

```
> 6 votes

# Answer
# Actually, 4 bytes

```
G1-ì

```

Try it online!

Explanation:

```
G1-ì
G     random()
 1-   1-random()
   ì  1/(1-random())

```
> 5 votes

# Answer
# R, 10 bytes

```
1/runif(1)

```

Pretty straightforward.
> 5 votes

# Answer
# TI-Basic, 2 bytes

```
rand^-1      (AB 0C in hex)

```

For anyone who is wondering, `rand` returns a random value in (0,1\]. "Due to specifics of the random number generating algorithm, the smallest number possible to generate is slightly greater than 0. The largest number possible is actually 1 ..." (source). For example, seeding rand with 196164532 yields 1.
> 4 votes

# Answer
# , 12 bytes

```
exp(rexp(1))

```

Try it online!

Verify the distribution

This takes a different approach, exploiting the fact that if `Y~exp(alpha)`, then `X=x_m*e^Y` is a Pareto with parameters `x_m,alpha`. Since both parameters are 1, and the default rate parameter for `rexp` is 1, this results in the appropriate Pareto distribution.

While this answer is a fairly R- specific approach, it's sadly less golfy than plannapus'.

# , 14 bytes

```
1/rbeta(1,1,1)

```

Try it online!

Even less golfy, but another way of getting at the answer.

Another property of the exponential distribution is that if `X ~ Exp(λ) then e^−X ~ Beta(λ, 1)`, hence `1/Beta(1,1)` is a `Pareto(1,1)`.

Additionally, a keen observer would recall that if `X ~ Beta(a,b)` and `a=b=1`, then `X~Unif(0,1)`, so this truly is `1/runif(1)`.
> 4 votes

# Answer
# Charcoal, 10 bytes

```
Ｉ∕Ｘφ²⊕‽Ｘφ²

```

Try it online!

Link is to the verbose version:

```
Print(Cast(Divide(Power(f, 2), ++(Random(Power(f, 2))))));

```

Comments:

* Charcoal only has methods to get random integer numbers, so in order to get a random floating-point number between 0 and 1 we have to get a random integer between 0 and N and divide by N.
* Previous version of this answer that used the `1/(1-R)` formula: In this case, N is set to 1000000 as the OP asks it to be the minimum. To get this number Charcoal provides a preset variable `f`=1000. So just calculating `f^2` we get 1000000. In the event that the random number is 999999 (the maximum), `1/(1-0.999999)=1000000`.
* Neil's tip (saving 3 bytes): If I have `1/(1-R/N)` where `R` is a random number between 0 and N, it is the same as just calculate `N/(N-R)`. But considering that the random integers `N-R` and `R` have the same probability to occur, that is the same as just calculating `N/R` (being `R` in this last case a number between 1 and N inclusive to avoid division by zero).
> 3 votes

# Answer
# Mathematica, 10 bytes

```
1/Random[]

```

Try it online!

-4 bytes from M.Stern
> 3 votes

# Answer
# Haskell, ~~61~~ 56 bytes

The function `randomIO :: IO Float` produces random numbers in the interval `[0,1)`, so transforming them using `x -> 1/(1-x)` will produce pareto realizations.

```
import System.Random
randomIO>>=print.(1/).((1::Float)-)

```

Try it online!
> 3 votes

# Answer
# Excel, 9 bytes

```
=1/rand()

```

Yay, Excel is (semi-)competitive for a change!
> 3 votes

# Answer
# Ruby, ~~14~~ 8 bytes

```
p 1/rand

```

Trivial program, I don't think it can get any shorter.
> 2 votes

# Answer
# Excel VBA, 6 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window

```
?1/Rnd

```
> 2 votes

# Answer
# JavaScript REPL, 15 ~~19~~ bytes

```
1/Math.random()

```
> 1 votes

# Answer
# Python, 41 bytes

```
lambda:1/(1-random())
from random import*

```

Try it online!

---

Using the builtin is actually longer:

# Python, 43 bytes

```
lambda:paretovariate(1)
from random import*

```

Try it online!

Both solutions work in both Python 2 and Python 3.
> 1 votes

# Answer
# , 5 bytes

```
%-.?0

```

## How ot works:

`?0` generates a random value greater than 0 and less than 1

`-.` subtract from 1

`%` reciprocal

Try it online!
> 1 votes

# Answer
# Japt, 6 bytes

`1/1-Mr` is the same length but this felt a little less boring!

```
°T/aMr

```

Try it

---

## Explanation

Increment (`°`) zero (`T`) and divide by (`/`) its absolute difference (`a`) with `Math.random()`.
> 1 votes

# Answer
# Red, 19 bytes

```
1 /(1 - random 1.0)

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~22~~ 18 bytes

```
v->1/Math.random()

```

(Old answer before the rules changed: `v->1/(1-Math.random())`)

Try it here.
> 1 votes

# Answer
# APL (Dyalog), 5 bytes

```
÷1-?0

```

Try it online!

**How?**

```
 ÷   1-     ?0
1÷  (1-  random 0..1)

```
> 1 votes

# Answer
# Jelly, 5 bytes

Jelly also doesn't have random float, so this uses `x/n` where `x` is an random integer in range `[1, n]` (inclusive) to emulate a random float in range `(0, 1]`. In this program `n` is set to be `10<sup>8</sup>`.

```
ȷ8µ÷X

```

Try it online!

## Explanation

```
ȷ8     Literal 10^8.
  µ    New monad.
   ÷   Divide by
    X  random integer.

```

---

# Enlist, 3 bytes

```
ØXİ

```

Try it online!

Enlist beats Jelly! (TI-Basic not yet)

## Explanation

```
  İ    The inverse of...
ØX     a random float in [0, 1)

```

Of course this has nonzero probability of take the inverse of 0.
> 1 votes

# Answer
# IBM/Lotus Notes Formula, 13 bytes

```
1/(1-@Random)

```

**Sample (10 runs)**
> 1 votes

# Answer
# Pyt, 2 bytes

```
ṛ⅟

```

Explanation:

```
ṛ           Random number in [0,1)
 ⅟          Multiplicative inverse
            Implicit print

```

Try it online!
> 1 votes

# Answer
# Pyth, 4 bytes

```
c1O0

```

Try it here!

Alternative: `c1h_O0`.
> 0 votes

# Answer
# J, 9 Bytes

```
p=:%@?@0:

```

I couldn't figure out how to make it take no input, since p=:%?0 would evaluate immediately and remain fixed. Because of this its sort of long.

### How it works:

```
p=:        | Define the verb p
       0:  | Constant function. Returns 0 regardless of input.
     ?@    | When applied to 0, returns a random float in the range (0,1)
   %@      | Reciprocal

```

Evaluated 20 times:

```
    p"0 i.20
1.27056 1.86233 1.05387 16.8991 5.77882 3.42535 12.8681 17.4852 2.09133 1.82233 2.28139 1.58133 1.79701 1.09794 1.18695 1.07028 3.38721 2.88339 2.06632 2.0793

```
> 0 votes

# Answer
# Clean, 91 bytes

```
import StdEnv,Math.Random,System.Time
Start w=1.0/(1.0-hd(genRandReal(toInt(fst(time w)))))

```

Clean doesn't like random numbers.

Because the random generator (a Mersenne Twister) *needs* to be given a seed, I have to take the system timestamp to get something that differs passively per-run, and to do anything IO-related I *need* to use a whole `Start` declaration because it's the only place to obtain a `World`.

Try it online!
> 0 votes

---
Tags: code-golf, number, random, probability-theory
---


# Question
Title: The sequence of range-exponentiated integers
Consider a triangle where the **N**th row (1-indexed) is the array of the first **N** positive integer powers of **N**. Here are the first few rows:

```
N | Triangle

1 | 1
2 | 2 4
3 | 3 9 27
4 | 4 16 64 256
5 | 5 25 125 625 3125
...

```

Now if we concatenate those powers into a single sequence, we get OEIS A075363:

```
1, 2, 4, 3, 9, 27, 4, 16, 64, 256, 5, 25, 125, 625, 3125, 6, 36, 216, 1296, 7776, 46656 ...

```

---

Given an integer **N**, your task is to return the **N**th term of this sequence. You can choose either 0 or 1-indexing.

## Test cases

**1-indexed:**

```
N  -> Output

1  -> 1
2  -> 2
3  -> 4
5  -> 9
10 -> 256
12 -> 25
15 -> 3125

```

**0-indexed:**

```
N  -> Output

0  -> 1
1  -> 2
2  -> 4
4  -> 9
9  -> 256
11 -> 25
14 -> 3125

```

Note that these loopholes are forbidden by default. This is , thus the shortest valid submission in each language wins!

# Answer
> 7 votes
# Python 3, 39 bytes

**1-indexed**

```
f=lambda x,n=1:n**x*(x<=n)or f(x-n,n+1)

```

Try it online!

# Answer
> 7 votes
# Husk, 7 bytes

```
!ṁṠM^ḣN

```

Try it online!

1-indexed

### Explanation:

```
      N   Get the list of all natural numbers
 ṁ        Map over each n in that list and then concatenate
  Ṡ  ḣ      Create the range [1,n] then ...
   M^       raise n to the power of each
!         Index into that sequence

```

# Answer
> 5 votes
## Wolfram Language (Mathematica), 32 bytes

```
r=Range;Flatten[r@#^r@r@#][[#]]&

```

Try it online!

Ranges to the power of ranges of ranges...

# Answer
> 4 votes
# , 40 bytes

*-2 bytes porting Halvard Hummel's answer*

```
function(N){while(N>T){N=N-T;T=T+1};T^N}

```

Try it online!

# , (original answer) 42 bytes

```
function(N)(rep(1:N,1:N)^sequence(1:N))[N]

```

Try it online!

1-indexed.

# Answer
> 4 votes
# APL (Dyalog), ~~15~~ ~~13~~ 10 bytes

*3 bytes saved thanks to @Adám*

```
⊢⊃∘∊⍳*⍳¨∘⍳

```

Try it online!

**How?**

`⍳¨∘⍳` \- create a range for each number in the range of input

`⍳*` \- raise each number in the range of input to the corresponding powers

\- flatten

`⊢⊃` \- pick the nth element

# Answer
> 3 votes
# Jelly, 7 bytes

```
*R$€Ẏ⁸ị

```

Try it online!

-1 thanks to Mr. Xcoder.

1-indexed.

# Answer
> 3 votes
# Haskell, ~~30~~ 28 bytes

Saved 2 bytes thanks to xnor.

```
([n^m|n<-[1..],m<-[1..n]]!!)

```

Try it online!

0-indexed

# Answer
> 3 votes
# APL (Dyalog), ~~14~~ 12 bytes

```
{⍵⌷∊*∘⍳⍨¨⍳⍵}

```

Try it online!

Uses 1-indexing

Saved 2 bytes with `↑,/ → ∊`, taken from Graham's answer

Note that in the test link, the code requires an extra `f←`, but this is not counted as per our rules.

# Answer
> 3 votes
# MATL, 9 bytes

```
:t!^RXzG)

```

Indexing is 1-based. Try it online! Or verify all test cases.

### Explanation

Consider input `5` as an example.

```
:     % Implcit input n. Push range [1 2 ... n]
      % STACK: [1 2 3 4 5]
t!^   % Matrix of all pair-wise powers
      % STACK: [1    2    3    4    5;
                1    4    9   16   25;
                1    8   27   64  125;
                1   16   81  256  625;
                1   32  243 1024 3125]
R     % Upper triangular matrix
      % STACK: [1    2    3    4    5;
                0    4    9   16   25;
                0    0   27   64  125;
                0    0    0  256  625;
                0    0    0    0 3125]
Xz    % Nonzeros. Reads values in column-major order
      % STACK: [1; 2; 4; 3; 9; ...; 625; 3125]
G)    % Get n-th entry (1-based). Implcit display
      % STACK: 9

```

# Answer
> 3 votes
# Pyth, 8 bytes

```
@s^RSdSh

```

Try it here.

-1 thanks to Steven H..

0-indexed.

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
ƒNDLm`}I@

```

Try it online!

**Explanation**

1-indexed.

```
ƒ           # for N in range [0 ... input]
 N          # push N
  DL        # push range [1 ... N]
    m       # raise N to the power of each in [1 ... N]
     `      # flatten to stack
      }     # end loop
       I@   # get the element at index (input)

```

**Alternative solution over a list instead of a loop**

```
ÝεDLm}˜sè

```

# Answer
> 1 votes
# JavaScript, 30 bytes

*-1 byte thanks to Nahuel Fouilleul*

```
f=(x,n=1)=>x>n?f(x-n,n+1):n**x

```

Try it online!

# Answer
> 1 votes
# Perl 6, 29 bytes

```
{({|($++X**1..$++)}...*)[$_]}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  (  # generate the sequence

    {  # code block used to generate each value in the sequence

      |(         # slip the values into the outer sequence

        $++      # post-incremented anonymous state value
        X**      # cross using &infix:«**»
        1 .. $++ # from 1 to post-incremented anonymous state value

      )
    }

    ...          # keep generating values until

    *            # never stop

  )[ $_ ]        # index into the sequence (0-based)
}

```

# Answer
> 1 votes
# Ruby, 34 bytes

```
->n{w=0;n-=w+=1until n<0;w**=w-~n}

```

Try it online!

# Answer
> 0 votes
# Python 2, 57 bytes

```
lambda N:[n**-~e for n in range(N+2)for e in range(n)][N]

```

Try it online! (0-indexed.)

*0-indexed alternative 74 bytes long version*.

# Answer
> 0 votes
# Jelly,  ~~15~~  12 bytes

<sub>~~Probably~~ not optimal.</sub>

-3 thanks to Erik the Outgolfer's golfing.

```
=RṁR€T€µT*FḢ

```

**Try it online!**

# Answer
> 0 votes
# APL+WIN, 23 bytes

```
(∊n↑¨⊂[2]n∘.*n←⍳n)[n←⎕]

```

Explanation:

```
[n←⎕] prompts for screen input and selects the nth element of the concatenated vector
see below

n←⍳n creates a vector of 1 to n

∘.* outer product with exponentiation as the operator

⊂[2] enclose each row of the resulting array as an element of a nested array

∊n↑¨ take 1 to n elements from the 1 to nth row of the matrix and concatenate into a vector

```

# Answer
> 0 votes
# Perl 5, 30+1 (-p) bytes

```
$_-=$.++until$.>$_;$_=$.**++$_

```

try it online

# Answer
> 0 votes
# , 20 bytes

```
{1,[:;[:(^&.><\)1+i.

```

1-indexed

Try it online!

# Answer
> 0 votes
# S.I.L.O.S, 45 bytes

```
readIO
lblb
a+1
i-a
if i b
i+a
a^i
printInt a

```

Try it online!

# Answer
> 0 votes
## Clojure 51 bytes

0-indexed, for example input `9` returns `256.0`.

```
#(nth(for[i(range)j(range i)](Math/pow i(inc j)))%)

```

# Answer
> 0 votes
# C ~~76~~, 62 bytes

```
y;f(n){for(y=0;n>y*++y/2;);return(int)pow(y-1,n+y*(3-y)/2-1);}

```

~~y;f(n){y=(int)(-.5+sqrt(1+8\*~-n)/2)+2;n+=y\*(3-y)/2-1;return(int)pow(y-1,n);}~~

I based it on this code

Try it on ideone

# Answer
> 0 votes
# Pyt, ~~39~~ 37 bytes

1-indexed

```
←000`ŕŕ⁺ĐĐř^Đ04Ș↔+⇹Ł-Đ↔3Ș0>łŕ0↔⇹+⁻⦋↔ŕ

```

Explanation:

Briefly, it calculates each row. If the requested number is in that row, return it; otherwise, go to the next row.

---
Tags: code-golf, math, number, sequence
---


title: The working time calculator

text:
# Question
Title: The working time calculator
This is based on how my company deals with the monitoring of the working times for every employee. Each one of us has a card that can be passed in front of a sensor, so that a clock registers the times at which the employees check in or out the office. Every time register is linked to a code:

* Code 0: the employee arrives at (or returns to) the office.
* Code 1: the employee leaves the office for lunch.
* Code 2: the employee leaves the office at the end of the day.
* Code 3: the employee leaves the office for work reasons.
* Code 4: the employee leaves the office for personal reasons.

Code 0 registers will sometimes be referred to as "zero registers", and code 1 to code 4 registers will sometimes be referred to as "non-zero registers".

So, a normal day for a worker would generate a register list like this:

```
Code/Time
------------
0   8:17  // The employee arrives at the office
4  11:34  // The employee leaves the office to smoke
0  11:41  // The employee returns to the office
1  13:37  // The employee leaves the office to have lunch
0  14:11  // The employee returns to the office
3  15:02  // The employee leaves the office to visit a client
0  16:48  // The employee returns to the office
2  17:29  // The employee leaves the office to go home

```

Nonetheless, the employees sometimes make mistakes. The following errors are automatically fixed by the system:

* There are two consecutive non-zero records. If the first non-zero record has a code 4, an automatic code 0 register is added 15 minutes after, or 1 minute before the next registers if it has been registered less than 15 minutes after. If the first non-zero record has a code 3, an automatic code 0 register is always added 1 minute before the next register. Every other case produces an error. Examples:

```
Code/Time
------------
0   8:17  // The employee arrives at the office
4  11:34  // The employee leaves the office to smoke
1  13:37  // The employee leaves the office to have lunch
// Automatic register with code 0 added at 11:49.

Code/Time
------------
0   8:17  // The employee arrives at the office
4  11:34  // The employee leaves the office to smoke
4  11:39  // The employee leaves again the office for personal reasons
// Automatic register with code 0 added at 11:38.

Code/Time
------------
0   8:17  // The employee arrives at the office
3  11:34  // The employee leaves the office to visit a client
1  14:09  // The employee leaves the office to have lunch
// Automatic register with code 0 added at 14:08.

```
* The employee registered two code 1 registers or two code 2 registers. As these two are in fact interchangeable, that does not count as an error. If the code 1 or code 2 registers sum more than 2 registers, that produces an error.

**The challenge**

The main objective is to calculate how many hours and minutes the employee has spent in the office. This is done after fixing (if needed and possible) the input register list. Note that a proper register list will alternate zero registers with non-zero registers.

So, the algorithm will receive the list of registers for an employee and a give day, and will return the time spent working for that day. If the time cannot calculate the time spent in case of errors, it will return 0 hours, 0 minutes.

Rules:

* The time spent is the sum of the time spent between every code 0 register and the following non-zero register. If the non-zero code is a 3, the time spent between that register and the following code 0 register will also be counted.
* You can assume that the input register list will be in ascending time order, and that all the registers will be from the same day (nobody will work beyond midnight).
* The input register won't be empty.
* The input format can be anything your code needs, as long as the time is expressed with the hour value and the minute value (a floating-point number of hours won't be a valid input). Examples: A list with the codes and a list with the time as strings, both lists being the same lenght; a list of lists of integers, being the integers the code, the hour and the minutes of the registers...
* The output can be a string with the time (in any format you want: H:mm, HH:mm, H:m...); a list of two integers with the hours and minutes calculated; anything that can be interpreted as an hour-minute tuple (a floating-point number with the hours spent won't be allowed). Or you can print the result to STDOUT.

**Test cases**

```
Code/Time
------------
0   8:17  // Check in
4  11:34  // Check out. Time spent since check in:  3:17
0  11:41  // Check in
1  13:37  // Check out. Time spent since check in:  1:56
0  14:11  // Check in
3  15:02  // Check out. Time spent since check in:  0:51
0  16:48  // Check in.  Time spent working outside: 1:46
2  17:29  // Check out. Time spent since check in:  0:41
// Total time (value returned): 8:31

Code/Time
------------
0   8:17
4  11:34  // Time spent: 3:17
1  15:52  // Time spent since 11:49 (automatic register 15 minutes after
          // a code 4 register): 4:03
// Total time: 7:20

Code/Time
------------
0   8:17
4  15:47  // Time spent: 7:30
1  15:52  // Time spent since 15:51 (automatic register after a code 4
          // register 1 minute before the next register as it is too
          // close in time): 0:01
// Total time: 7:31

Code/Time
------------
0   8:17
1  13:34  // Time spent: 5:17
0  14:04
1  17:55  // Time spent: 3:51 (last code 1 should be a code 2 but it does not matter)
// Total time: 9:08

Code/Time
------------
0   8:17
1  13:34
0  14:04
1  17:05
0  17:08
2  17:44
// Total time: 0:00 (too many code 1 and code 2 registers)

Code/Time
------------
0   8:17
1  13:34  // A code 1 register does not generate an automatic code 0 register
2  17:41
// Total time: 0:00 (there's a code 0 register missing)

Code/Time
------------
0   8:17
0  13:34  // what happened between these two check in registers?
2  17:41
// Total time: 0:00 (there's a check out register missing)

Code/Time
------------
0   8:17
0  13:37  // This should probably be a code 1 register, but we cannot be sure
0  14:11
2  17:29
// Total time: 0:00

```

I know this can be confusing (the real-world problem had even more cases to consider, so I do know that). Please, do not hesitate to ask for more examples.

This is , so may the shortest code for each language win!

---

You can comment how to improve the system if you want, but that's not the point. My boss is not prone to spend time changing it. :-)

# Answer
> 3 votes
# Python 3, 327 322 318 317 bytes

Thanks for @JonathanFrech and @Mr.Xcoder for getting rid of some bytes.

Takes input as list of codes (`C`) and list of times (`T`) (`(hours, minutes)` tuples). Returns a `(hours, minutes)` tuple.

```
def f(C,T):
 T,L=[m+h*60for h,m in T],C.count
 for z in range(len(C))[::-1]:
  c=C[~-z]
  if c*C[z]:
   if c<3:return 0,0
   C.insert(z,0);b=~-T[z];T.insert(z,b if c-4else min(T[~-z]+15,b))
 while L(3):i=C.index(3);del C[i:i+2],T[i:i+2]
 return(0,0)if L(1)+L(2)>2or 0in C[1::2]else divmod(sum(T[1::2])-sum(T[::2]),60)

```

Verified against given examples.

## Ungolfed

```
def f(C, T):
    # use minutes since midnight instead of (hours, minutes)
    T=[m+h*60 for h,m in T]

    # error correction
    for z in range(len(C))[::-1]:
        if C[z-1] and C[z]:
            if C[z-1]<3:
                return 0,0

            C.insert(z,0)
            b=T[z]-1
            T.insert(z, b if C[z-1] != 4 else min(T[z-1]+15, b))

    # simplification (remove work trips (code 3))
    while L(3): # 3 in C
        i=C.index(3)
        del C[i:i+2]
        del T[i:i+2]

    # error check
    if 0 in C[1::2] or 2 < C.count(1) + C.count(2):
        return 0,0

    # sum
    s = sum(T[1::2])-sum(T[::2])

    # to (hours, minutes)
    return divmod(s, 60)

```

---
Tags: code-golf, math, arithmetic, date
---


title: Is it a Satisfying Number?

text:
# Question
Title: Is it a Satisfying Number?
inspired by this chat conversation

A *satisfying number* is a number whose decimal representation is of the form `abx`, with the following properties:

* `x` is the longest trailing repeating suffix, or the last digit if there is no repetition at the end (`123333` -\> `3333`, `545656` -\> `5656`, `123` -\> `3`)
* `b` is the single digit prior to `x` (`123333` -\> `2`, `55545656` -\> `4`)
* `a` is the remaining prefix (`123333` -\> `1`, `55545656` -\> `555`)
* `a == c**b` (`**` denotes exponentation), where `c` is the number of repetitions of the smallest repeating portion of `x` (`1623333` -\> `4` (`3 3 3 3`, not `33 33`))

For example, `8300` is a satisfying number with `a = 8`, `b = 3`, `c = 2`, and `x = 00`. `24651` is not a satisfying number, because `x = 1`, `b = 5`, `a = 246`, and there is no integer `c` that satisfies `c^5 = 246`. `1222` is also not a satisfying number, because with `x = 222` and `b = 1`, there are no remaining digits for `a`.

Given a positive integer `n >= 100`, output whether or not `n` is a satisfying number.

## Examples

```
8300: True (a=8, b=3, c=2, x=00)
24651: False
1222: False
92555: True (a=9, b=2, c=3, x=555)
64633: True (a=64, b=6, c=2, x=33)
512944: True (a=512, b=9, c=2, x=44)
123: True (a=1, b=2, c=1, x=3)
822809: False
376664: False
723799: False
1234: False
34330000000: True (a=343, b=3, c=7, x=0000000)
92313131: True (a=9, b=2, c=3, x=313131)
16424442444: True (a=16, b=4, c=2, x=24442444)

```

# Answer
> 3 votes
# Jelly, 26 bytes

feels too long

```
DŒṖṖEÐƤḄ$ÐṀLÐṂṪµḢ*@0¦LµṪ⁼Ḍ

```

A monadic link taking an integer and returning `1` if the input is satisfying and `0` if not.

**Try it online!** or see a test-suite

### How?

```
DŒṖṖEÐƤḄ$ÐṀLÐṂṪµḢ*@0¦LµṪ⁼Ḍ - Link: integer, n    e.g. 8300
D                          - to decimal list          [8,3,0,0]
 ŒṖ                        - all partitions           [[[8],[3],[0],[0]],[[8],[3],[0,0]],[[8],[3,0],[0]],[[8],[3,0,0]],[[8,3],[0],[0]],[[8,3],[0,0]],[[8,3,0],[0]],[[8,3,0,0]]]
   Ṗ                       - pop (the "no tail" one)  [[[8],[3],[0],[0]],[[8],[3],[0,0]],[[8],[3,0],[0]],[[8],[3,0,0]],[[8,3],[0],[0]],[[8,3],[0,0]],[[8,3,0],[0]]]
         ÐṀ                - keep maximal under the operation: e.g. for [[8,3],[0],[0]]
        $                  -   last two links as a monad:
     ÐƤ                    -     for suffixes:   i.e. [[[8,3],[0],[0]],[[0],[0]],[[0]]]
    E                      -       all equal?         [0              ,1        ,1]
       Ḅ                   -     convert from binary  3
                           -          ...which yields [[[8],[3],[0],[0]],[[8,3],[0],[0]]]
            ÐṂ             - keep minimal under the operation:
           L               -   length
                           -          ...which yields [[[8,3],[0],[0]]]
              Ṫ            - tail (rightmost)         [[8,3],[0],[0]]
               µ           - monadic chain separation
                Ḣ          - yield head and modify    [8,3]   ...leaving [[0],[0]]
                     L     - length (of modified)     2
                    ¦      - sparse application       (to the [8,3])
                   0       -   ...to index: 0         (to the rightmost digit, the 3)
                 *@        -   power (sw@p args)      [8,8]  ([8, 3*@2] = [8, 2*3] = [8,8])
                      µ    - monadic chain separation
                       Ṫ   - yield tail and modify    8   ...leaving [8]
                         Ḍ - from decimal (modified)  8
                        ⁼  - equal?                   1

```

# Answer
> 1 votes
# Python 3, 141 bytes

```
a=b=0;k=[]
c=[*input()];l=len(c)
while c[1:]>[]==k:a=a*10+b;b=int(c.pop(0));k=[i for i in range(2,l)if c==i*c[:l//i]];l-=1
a==(k+[1])[0]**b>q

```

Try it online!

# Python 3, 144 bytes

```
a=b='';k=[]
c=[*input()];l=len(c)
while c[1:]>[]==k:a+=b;b,*c=c;k=[i for i in range(2,l)if c==i*c[:l//i]];l-=1
int(a or-1)==(k+[1])[0]**int(b)>q

```

Try it online!

output is via exit code

# Answer
> 0 votes
# Perl 6, 66 bytes

```
{/^(\d+?)(\d)((\d+?)$0+||\d)$/&&($2.comb/($2[0]||1).comb)**$1==$0}

```

Try it online!

# Answer
> 0 votes
# JavaScript (ES6), ~~282~~ 268 bytes

```
t=(d,n,l,i,r)=>d.slice((m=-l*i)-l,m).join``!=n?r:t(d,n,l,i+1,{p:r.p+n,r:r.r+1});p=(d,l,r)=>l<1?r:p(d,l-1,r.r<(z=t(d,(m=d.slice(-l).join``),l,1,{p:m,r:1})).r&&(z.r>1|l==1)?z:r);u=n=>(d=[...n]).slice(0,(q=(s=d.length)-(m=p(d,s,{p:"",r:0})).p.length-1)).join``==m.r**d[q]

function onChange() {
  var value = document.getElementById("input").value;
  console.log("%s => %s", value, u(value));
}
```

```
<input id="input" type="number" onchange="onChange()" />
```

# Answer
> 0 votes
# Python 3, 101 bytes

```
import re
x,_,b,a=re.findall(r"((.+?)\2+)(.)(.*)",input()[::-1])[0]
if int(a[::-1])!=len(x)**int(b):d

```

# Python 3, 107 bytes

```
import re
x,_,b,a=re.findall(r"((.+?)\2+)(.)(.*)",input()[::-1])[0]
if int(a[::-1])!=len(x)**int(b):int('')

```

Output is by exit code.

This code doesn't run properly on Tio due to a range error. Works perfectly in IDLE.

# Answer
> 0 votes
## Python 2, 286 bytes

*yeesh.*

```
n=`input()`
N=lambda p,l=0:N(n[:-len(p)],p,l+1)if n[-len(p):]==p else l
try:
    s=[(N(n[-i-1:]),n[-i-1:])for i,_ in enumerate(n)if N(n[-i-1:])!=1]
    if len(s)==0:s=[(1,n[-1])]
    q=max(s,key=lambda a:len(a[0]*a[1]))
    i=len(q[0]*q[1])
    print n[:-i-1]==`min(s)[0]**int(n[-i-1])`
except:print 0

```

`N` is a recursive function that finds the number of times a suffix substring is repeated in a string. This basically loops through all possible suffixes, finding the number of times each is repeated using `N`; this excludes all values where `N==1` because they refer to no repeats; if the list ends up being empty, the suffix of the last character is appended to the list.

Then, the longest suffix is taken, (`q`), the number of characters it takes up is found (`i`), and `a==c**b` is checked (`print ...`).

If an error occurs along the way (which it often will), it is caught in the `except` block.

Any suggestions are more than welcome!

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


title: Grow Some Flowers!

text:
# Question
Title: Grow Some Flowers!
Spring has recently arrived, and it is almost the time when flowers start to sprout. So I want you to help them grow.

**Your task:**

Given two numbers, `m`, and `n`, output `m` flowers randomly placed on an `n*n` grid.

A single flower looks like this:

```
&
|

```

A flower's position is defined by where its `&` is. When randomly placing two flowers, no two can be in the same place. If one flower's `&` overlaps another flower's `|`, display the `&`. The bottom row of flowers may not contain any `&`.

Input can be as a number or a string, through any of the standard methods.

Output can be a list of strings, each string representing one row of the grid, or a delimited string following the same guideline as the list. Standard methods of output. Trailing whatevers are allowed, and you can use tabs to separate your flowers. Note that every grid must be completely filled, with spaces or something.

Note that the input will always be valid, you will always be able to legally fit the `m` flowers into the `n` by `n` grid.

**Test cases:**

Since only very tight test cases can be guaranteed, due to the whole "random placement" bit, that will be the only kind of test case with an answer provided. But I will try all submissions online to make sure that they are valid using some test cases too.

Input for the test cases is given in the form `m, n`.

```
Input: 2, 2
Output:

&&
||
--------------
Input: 6, 3
Output:

&&&
&&&
|||

```

Note that the newline after the word `Output:` in the test cases is optional.

Other test cases:

1. 1, 10
2. 0, 100
3. 5, 8
4. 6, 3

Code golf so shortest code wins!

Thank you to ComradeSparklePony for making this challenge and posting it in the Secret Santa's gift box!. Sandbox post

# Answer
# Jelly, 33 bytes

```
²‘;⁹R¤ṬṖs⁸×’¤Ẋ€ṙ2B¤F€ZḄị“&|& ”s⁸Y

```

**Try it online!**

### How?

```
²‘;⁹R¤ṬṖs⁸×’¤Ẋ€ṙ2B¤F€ZḄị“&|& ”s⁸Y - Main link: n, m        e.g. 3, 2
²                                 - square n                    9
 ‘                                - increment                   10
     ¤                            - nilad followed by link(s) as a nilad:
   ⁹                              -     link's right argument   2
    R                             -     range                   [1,2]
  ;                               - concatenate                 [10,1,2]
      Ṭ                           - untruth (1s at indexes)     [1,1,0,0,0,0,0,0,0,1]
       Ṗ                          - pop                         [1,1,0,0,0,0,0,0,0]
            ¤                     - nilad followed by link(s) as a nilad:
         ⁸                        -     link's left argument    3
           ’                      -     decrement               2
          ×                       -     multiply                6
        s                         - split into chunks           [[1,1,0,0,0,0],[0,0,0]]
             Ẋ€                   - shuffle €ach       (maybe:) [[0,1,0,0,1,0],[0,0,0]]
                  ¤               - nilad followed by link(s) as a nilad:
                2B                -     2 in binary             [1,0]
               ṙ                  - rotate (vectorises)         [[[0,0,0],[0,1,0,0,1,0]],[[0,1,0,0,1,0],[0,0,0]]]
                   F€             - flatten €ach                [[0,0,0,0,1,0,0,1,0],[0,1,0,0,1,0,0,0,0]]
                     Z            - transpose                   [[0,0],[0,1],[0,0],[0,0],[1,1],[0,0],[0,0],[1,0],[0,0]]
                      Ḅ           - from binary (vectorises)    [0,1,0,0,3,0,0,2,0]
                        “&|& ”    - literal                     ['&','|','&',' ']
                       ị          - index into                  [' ','&',' ',' ','&',' ',' ','|',' ']
                               ⁸  - link's left argument        3
                              s   - split into chunks           [[' ','&',' '],[' ','&',' '],[' ','|',' ']]
                                Y - join with newlines          [' ','&',' ','\n',' ','&',' ','\n',' ','|',' ']
                                  - implicit print

```
> 5 votes

# Answer
# PHP (\>=7.1), ~~135 131 128 116 110~~ 109 bytes

```
for([,$m,$n]=$argv,$z=$q=$n*$n;$q;)echo" |&"[$m&&rand(0,--$z-$n)<$m?$s[$q]=2+!$m--:$s[$q+$n]/2],"
"[--$q%$n];

```

takes input from command line arguments; run with `-nr` or test it online.

**breakdown**

```
for([,$m,$n]=$argv,     # import arguments
    $z=$q=$n*$n;        # $q = number of total fields, $z-$n = available for flowers
    $q;                 # loop $q down to 0
)
    echo" |&"[              # print:
        $m&&rand(0,--$z-$n)<$m  # if (probability $m/($z-$n)), decrement $z
            ?$s[$q]=2+!$m--     # then index 2 (flower), set $s[$q], decrement $m
            :$s[$q+$n]/2        # else if flower above, then 1 (stalk), else 0 (space)
        ],
        "\n"[--$q%$n]           # print newline every $n characters
    ;

```
> 4 votes

# Answer
# Python 2, 150 bytes

```
from random import*
n,m=input()
b=[1]*m+[0]*(n*~-n-m)
shuffle(b)
for r in range(n):print''.join(' &|'[f^-s]for s,f in zip([0]*n+b,b+[0]*n)[r*n:r*n+n])

```

**Try it online!**

### How?

Takes `input()` from STDIN and unpacks the tuple provided (a comma separated string of decimal integers like `3,6`) into `n` and `m`.

Creates an ordered, one dimensional `n*(n-1)` long "flowerbed", `b`, by concatenating:
\- a list containing a "flower" `[1]` repeated `m` times; and
\- a list containing a "space" `[0]` repeated `n*~-n-m` times\*.

* The tadpole operator `~` (`~x=-1-x`) saves 2 bytes with `n*~-n-m` in place of the more normal looking `n*(n-1)-m`.

Shuffles (using `random`'s `shuffle` function) this flowerbed to place the flowers and spaces randomly amongst the `n*(n-1)` positions.

Steps through the 0-indexed rows, `r`, and `prints` each in turn to create a two dimensional flowerbed from the one dimensional one...

The final two dimensional (`n*n`) flowerbed has stalks, `s`, one row below flower heads, `f`, if and only if there is no flower head to show. This is achieved by XORing (`^`) `f` with `-s` where `f` and `s` are the `1`s and `0`s from before and using the result to index into the length 3 string `' &|'`:

```
f   s   f^-s   ' &|'[f^-s]
0   0    0     ' '
0   1   -1     '|'  < negative indexing used here
1   0    1     '&'
1   1   -2     '&'  < ...and here.

```

To get `f` and `s` the `zip` function is used with two copies of the one dimensional flowerbed, one with `n` trailing spaces (the flower heads) and one with `n` leading spaces (the stalks). The whole thing is created for each row (to save bytes), and the row required is sliced out using `[r*n:r*n+n]`.
> 3 votes

# Answer
# Python 2, ~~184~~ 179 bytes

```
from random import*
m,n=input()
s,a=' &'
l=[s]*n*-~n
while s.count(a)<m:x=randrange(n*n-n);l[x]=a;l[x+n]='|&'[l[x+n]==a];s='\n'.join(''.join(l[i*n:][:n])for i in range(n))
print s

```

Try it online!
> 2 votes

# Answer
# Python 2, 129 bytes

```
from random import*
n,m=input();d=n*n-n
s=''
while d+n:b=0<random()*d<m;m-=b;d-=1;s+=' |&'[-b|(s[~n:-n]=='&')]+'\n'[d%n:]
print s

```

Try it online!

Generates the output string one character at a time. Randomly chooses whether the current cell is a flower with probability equal to the number `m` of remaining flowers divided by the number of remaining spaces. Adds a newline every `n` characters. A blank cell is filled with a stem `|` if the symbol `n` from the end is a `&`.
> 2 votes

# Answer
# PHP, 111 Bytes

```
for([,$b,$s]=$argv;$i<$s**2;)echo${+$i}="| &"[(rand(1,$s**2-$s-$i)>$b?0:$b--)>0?2:${$i-$s}!="&"],"\n"[++$i%$s];

```

Online Version

-1 Byte for a physical Newline

a solution 115 Bytes using max

```
for([,$b,$s]=$argv;$i<$s**2;)echo${+$i}="&| "[rand(1,max($s**2-$s-$i,1))>$b?1+(${$i-$s}!="&"):!$b--],"\n"[++$i%$s];

```

This way with 137 Bytes shuffles the first part of the string

```
for([,$b,$s]=$argv,$a=str_shuffle(($p=str_pad)($p("",$b,_),$s**2-$s));$i<$s**2;)echo$a[$i]<_?" |"[$a[$i-$s]==_&$i>=$s]:"&","\n"[++$i%$s];

```
> 1 votes

# Answer
## JavaScript (ES6), 157 bytes

```
f=(n,m,a=[...(` `.repeat(n)+`
`).repeat(n)],r=Math.random()*-~n*~-n|0)=>m?(a[r]==` `?a[m--,r]=`&`:0,f(n,m,a)):a.map((c,i)=>c==` `&&a[i+~n]==`&`?`|`:c).join``
```

```
<div oninput=o.textContent=f(n.value,m.value)><input id=n type=number min=2 value=2><input id=m type=number min=1><pre id=o>
```

Explanation: Creates an array representing the grid of flowers plus newlines. Recursively randomly searches for empty squares in which to place flowers until the desired number of flowers is reached. Finally the stems of the flowers are generated where there is space for them.
> 1 votes

# Answer
# Charcoal, 27 bytes

```
Ｎθ↷ＦＮ«Ｊ‽θ‽⊖θＷ⁼ＫＫ&Ｊ‽θ‽⊖θ&¬ＫＫ

```

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

```
Ｎθ

```

Input `n`.

Change the default printing direction to downwards.

```
ＦＮ«

```

Input `m` and loop that many times.

```
Ｊ‽θ‽⊖θ

```

Jump to a random location on the grid.

```
Ｗ⁼ＫＫ&Ｊ‽θ‽⊖θ

```

If there is already a flower, keep jumping to random locations until a suitable spot is found.

```
&

```

Print the flower head.

```
¬ＫＫ

```

Print the stalk if there is not already a flower head below.
> 1 votes

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


title: Ants on a Natural Log

text:
# Question
Title: Ants on a Natural Log
**This is a good beginner challenge and a good time killer.**

*I only said a -natural- log because the title was too short, this has nothing to do with logarithms.*

Given 2 variables:

* The number of ants `n`.
* The width of the log `w`.

Output a log of width `w` with `n` ants (Example shown `w=3`, `n=6`)

```
|             |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
|  ^   ^   ^  |
|             |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
|  ^   ^   ^  |
|             |

```

A single ant looks like this:

```
\O/ # Upper-case O
-O- # Upper-case O
/o\ # Lower-case o
 ^

```

***A few ant laws:***

1. Ants may not touch each other nor the edge of the log directly, they prefer to touch spaces.
2. Each row of ants must be `w` wide, with `n/w` rows of ants.
3. Ants always need a log, the log width is greater than 0, guaranteed.
4. Ants also... well, need ants, the number of ants is greater than 0, guaranteed.
5. Ants are also surprisingly well organized, they will fill a log from left to right, top to bottom; as if they were reading a book.

***Ant-xamples***

**w=3, n=5**

```
|             |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
|  ^   ^   ^  |
|             |
| \O/ \O/     |
| -O- -O-     |
| /o\ /o\     |
|  ^   ^      |
|             |

```

**w=1, n=1**

```
|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |

```

**w=1, n=3**

```
|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |

```

This is , the person with the smallest bytecount wins.

# Answer
> 4 votes
# Jelly,  ~~44~~  43 bytes

*Crossed out 44 is not 44 with use of* ` `

```
⁶ṁ;⁶jÐ€“\-/“OOo^ ”;UṖz⁶¤Y
sÇ€⁶;YỴz⁶Zj@€⁾||Y

```

**Try it online!**

### How?

```
⁶ṁ;⁶jÐ€“\-/“OOo^ ”;UṖz⁶¤Y - Link 1, make a row of ants: list x (could be integer = length)
⁶                         - literal ' '
 ṁ                        - mould like x (makes a list of that many spaces)
  ;⁶                      - concatenate one more space
                       ¤  - nilad followed by link(s) as a nilad
       “\-/“OOo^ ”        -   literal      ["\-/","OOo^ "] ("..." a list of chars really)
                   U      -   reverse each [" ^oOO","/-\"]
                  ;       -   concatenate  ["\-/","OOo^ "," ^oOO","/-\"]
                    Ṗ     -   pop          ["\-/","OOo^ "," ^oOO"]
                      ⁶   -   literal ' '
                     z    -   transpose & fill ["\O/","-O-","/o\"," ^ ","   "]
    jÐ€                   - join left mapped over right
                          -   (join the spaces with each of the ant parts in turn)
                        Y - join with newlines

sÇ€⁶;YỴz⁶Zj@€⁾||Y - Main link: n, w
s                 - split n into chunks of length w (implicitly makes a range of length n)
 Ç€               - call the last link (1) as a monad for €ach
   ⁶;             - a space concatenated with that
     Y            - join with newlines
      Ỵ           - split at newlines (both the ones we just joined with AND the others!)
       z⁶         - transpose & fill with space characters (making the shorter rows,
                  -   including the single space as long as the longest one)
         Z        - transpose it back the right way
             ⁾||  - literal ['|','|']
          j@€     - join with reverse arguments for €ach (put each row between pipes)
                Y - join back up with newlines
                  - implicit print

```

---

I have asked about `w<n` in a comment since it's slightly ambiguous.
If the log needs to be `w` ants wide rather than just the ants being `w` wide, it costs two bytes:

```
⁶ṁ;⁶jÐ€“\-/“OOo^ ”;UṖz⁶¤Y
+RsÇ€YỴz⁶Zj@€⁾||ṫ5Y

```

This does the same as before except rather than prepending a single space to make the first, blank line it creates a whole extra row of ants and chops off all but its trailing blank line.

# Answer
> 5 votes
# PHP\>=7.1, 150 Bytes

```
for([,$w,$n]=$argv;$i<ceil($n/$w)*5+1;)echo str_pad("| ".str_repeat(["","\O/ ","-O- ","/o\ "," ^  "][$i%5],$n<$w*ceil($i++/5)?$n%$w:$w),$w*4+2)."|\n";

```

Online Version

# Answer
> 5 votes
# , ~~70~~, 68 bytes

```
i \O/
 -O-
 /o\
  ^  Àä{ò@bf }C GïpòÇÓ/d
HÄÒ çÞ/ÙÒ
ëI|yê$p

```

Try it online!

```
00000000: 6920 5c4f 2f20 0a20 2d4f 2d20 0a20 2f6f  i \O/ . -O- . /o
00000010: 5c20 0a20 205e 2020 1bc0 e416 7bf2 4062  \ .  ^  ....{.@b
00000020: 6620 167d 4320 1b47 ef70 f2c7 d32f 640a  f .}C .G.p.../d.
00000030: 48c4 d220 e7de 2fd9 d220 0a16 eb49 7c1b  H.. ../.. ...I|.
00000040: 79ea 2470                                y.$p

```

This has never happened to me before, but a known bug has actually saved me bytes!

It's kinda hard to explain exactly what's going on, but unfortunately when you try to duplicate something by columns, V will move one column over before duplicating. Which is why originally I did:

```
h<C-v>{dÀp

```

which doesn't use the duplicate operator. However, because we already needed to move one line over, we can simply do

```
hÀä<C-v>{

```

# Answer
> 5 votes
# Python 2, 144 bytes

```
n,w=input()
s=' ';k='|';a=k+s*w*4+s+k;print a
while n>0:
 for i in['\\O/','-O-','/o\\',' ^ ']:print k+s+(i+s)*min(w,n)+s*4*(w-n)+k
 n-=w;print a

```

Try it Online!

# Answer
> 4 votes
# SOGL, ~~74~~ ~~71~~ 74 bytes

```
 |pe4*I@*o |o→L:"╔O¦‘2n;"nΤ↕¬┐α┐PΝld‘*┼eG-’⁵@**┼ |4*┼OL→ALbe÷:?{eA}}be%:?A

```

First part: function which outputs an empty log part

```
             →L  define function L
 |p              output in a newline "|"
   e4*           multiply width by 4
      I          increace that
       @*        get that many spaces
         o       append [to current line] that
           |o    append "|"

```

The second part has a compressed string `"nΤ↕¬┐α┐PΝld‘`, which is the ant. It decompresses to `\-/ OOo^/-\` . That's the ant (with spacing to the right), but taken top-to-down then to right like

```
159d
26ae
37bf
48cg

```

It's stored like that because the  function appends strings like that (that's because then you can multiply the string to add multiple instances to it). The part itself: function which asks for a number on stack denoting how many ants to draw.

```
                                    Example input: width 3, on stack 2
:                                   duplicate the input                             [2,2]
 "╔O¦‘                              push "| | | | "                                 [2,2,"| | | | "]
      2n                            split into chunks of two                        [2,2,["| ","| ","| ","| "]]
        ;                           put one of the input copies ontop of the stack  [2,["| ","| ","| ","| "], 2]
         "...‘*                     multiply that many ants                         [2,["| ","| ","| ","| "], "\\-/ OOo^/-\\     \\-/ OOo^/-\\     "]
               ┼                    add horizontally the ants                       ["| \O/ \O/ \O/ ",
                                                                                "| -O- -O- -O- ",
                                                                                "| /o\ /o\ /o\ ",
                                                                                "|  ^   ^   ^  "]
                e                   get the width                                   [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "|  ^   ^   ^  "], 3]
                 G-                 subtract input from it                          [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "|  ^   ^   ^  "], 1]
                   ’⁵@*             push 16 spaces                                  [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "|  ^   ^   ^  "], 1, "                "]
                       *            multiply [the 16 spaces and empty place count]  [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "|  ^   ^   ^  "], "                "]
                        ┼           add that horizontally                           [["| \\O/ \\O/ \\O/     ", "| -O- -O- -O-     ", "| /o\\ /o\\ /o\\     ", "|  ^   ^   ^      "]]
                          |4*┼      add 4 vertical bars to the array                [["| \\O/ \\O/ \\O/     |", "| -O- -O- -O-     |", "| /o\\ /o\\ /o\\     |", "|  ^   ^   ^      |"]]
                              O     output the array                                []
                               L    call the empty line function                    []
                                →A  define as A

```

And the main function:

```
L                  call the empty line drawing function
 be÷               push floor(b/e) (the amount of full lines)
    :?{eA}}        that many times call A with the full width on the stack
           be%     push b%e (the leftovers)
              :?   if truthy (aka !=0)
                A   call A with for the leftovers

```

# Answer
> 4 votes
# 05AB1E, 47 bytes

```
"   \O/-O-/o\ ^ "5äðìI.D)IôvyøJ'|ì})˜¬¸«.B„ |«»

```

Try it online!

**Explanation**

```
"   \O/-O-/o\ ^ "                                # push the ant-string
                 5ä                              # split into 5 parts
                   ðì                            # prepend a space to each
                     I.D                         # copy input-1 number of times
                        )                        # wrap in a list
                         Iô                      # split into parts each the size of input-2
                           v                     # for each row of ants
                            yø                   # zip, so body parts are on the same row
                              J'|ì               # join to string and prepend a pipe to each
                                  }              # end loop
                                   )˜            # wrap in a flattened list
                                     ¬¸«         # append a copy of the first row (spaces)
                                        .B       # pad rows to equal length with spaces
                                          „ |«   # append " |" to each row
                                              »  # merge on newlines

```

# Answer
> 2 votes
# Perl 5, 159 bytes

```
($w,$n)=@ARGV;
print
$_%$w?"":"| ",
['   \O/-O-/o\\ ^ '=~/.../g]->[($_<5*$w*int$n/$w||$_%$w<$n%$w?$_/$w:0)%5],
($_+1)%$w?" ":" |\n"
for 0..$w*(6+5*int(($n-1)/$w))-1

```

Try it online!

# Perl 5, 152 bytes

Another one based on the Python solution:

```
($w,$n)=@ARGV;
$b=' 'x($w*4+1);$j=$a="|\n|";
map$j.=' '."$_ "x($w<$n?$w:$n).'    'x($w-$n).$a,'\\O/','-O-','/o\\',' ^ 'and$n-=$w
while$n>0;
print"|$b$j$b|"

```

Try it online!

# Answer
> 0 votes
## Mathematica 210 Bytes

```
StringRiffle[If[#2==c||#2==1,"|",If[r-#1<6&&#2>2+4 (a+w-h w),Table[" ",5,4],Characters@"    \\O/ -O- /o\\  ^  "~Partition~4][[1+Mod[#1-1,5],1+Mod[#2+1,4]]]]&~Array~{r=5(h=⌈(a=#)/(w=#2)⌉)+1,c=4w+3},"\n",""]&

```

Thinking I need to make a Mathematica based golfing language.

# Answer
> 0 votes
## Python 2, 166 bytes

```
w,n=input()
print'\n'.join(['|'+' '*w*4+' |']+[' '.join(['|']+[p]*r+['   ']*(w-r)+['|'])for r in[w]*(n/w)+[[],[n%w]][n%w>0] for p in['\O/','-O-','/o\\',' ^ ','   ']])

```

# Answer
> 0 votes
# Charcoal, 43 bytes

```
ＮθＦ⪪× Ｎθ«←Ｐ↓⁶Ｍ⊗⊕⊗θ→Ｐ↓⁶⸿Ｅ⪪\O/-O-/o\ ^ ³⭆ι⁺μκ

```

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

```
Ｎθ

```

Input `w`.

```
Ｆ⪪× Ｎθ«

```

Input `n`, then create a string of `n` spaces and split it into rows of length `w` (except the last piece which may be smaller). Loop over those rows.

```
←Ｐ↓⁶Ｍ⊗⊕⊗θ→Ｐ↓⁶⸿

```

Print the sides of the log section.

```
  \O/-O-/o\ ^           Literal string
 ⪪            ³         Split into (4) pieces of length 3
Ｅ                       Map over each piece
               ⭆ι       Map over each row space
                 ⁺μκ    Appending the piece
                        Implicitly print the results on separate lines

```

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


# Question
Title: Advent Challenge 5: Move the presents to the transport docks!
\<\< Prev Next \>\>

Thanks to the PPCG community, Santa has managed to remanufacture all of his presents and after the assembly line, the presents are now ready to be moved into the transport docks!

Each of Santa's transport docks only holds a range of present sizes because the transport sleighs are specialized for a specific size (any lighter and it would be wasteful, any heavier and the sleigh wouldn't be able to handle the load). Thus, he needs you to help him take his presents and sort them into the correct transport docks.

# Challenge

Given a list and the transport dock ranges, stably organize the presents into the correct order.

Let's take this for example: the presents are `[5, 3, 8, 6, 2, 7]` and the dock ranges are `[[1, 5] and [6, 10]]`.

The presents `5`, `3`, and `2` go into the first dock and the presents `8`, `6`, and `7` go into the second dock. This can be shown as `[[5, 3, 2], [8, 6, 7]]`. This list will be closer to being sorted than the input, but `stably` means that within each dock, the order of the presents must be the same as the order of the input (otherwise you could just sort the entire list).

Your final output for this case would be `[5, 3, 2, 8, 6, 7]` (as a flat list).

# Formatting Specifications

You will be given input as a flat list of integers and a list of ranges in any reasonable format (for example, the range for the above case could be given as `[[1, 5], [6, 10]]`, `[1, 5, 6, 10]`, or `[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]`). Your output should be a flat list of integers in any reasonable format.

The input can contain duplicate values; in this case, you need to return all instances of them. All present sizes will be in exactly one size range, and you can assume that the ranges will never overlap. There can be gaps in the ranges as long as all present sizes are covered.

# Rules

* Standard Loopholes Apply
* This is , so the shortest answer in bytes wins
* No answer will be accepted
* You can assume that there will be no empty ranges (`[7, 4]` would be invalid because ranges go up)

# Test Cases

```
[1, 2, 3, 4, 5, 6, 7] ; [[1, 3], [4, 7]] => [1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7] ; [[4, 7], [1, 3]] => [4, 5, 6, 7, 1, 2, 3]
[7, 3, 5, 4, 6, 1, 2] ; [[1, 3], [4, 5], [6, 7]] => [3, 1, 2, 5, 4, 7, 6]
[4, 7, 6, 3, 5, 2, 1] ; [[1, 4], [5, 7]] => [4, 3, 2, 1, 7, 6, 5]
[1, 1, 3, 3, 6, 4, 7] ; [[1, 4], [6, 7]] => [1, 1, 3, 3, 4, 6, 7]

```

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

# Answer
> 5 votes
# Haskell, 26 bytes

```
a#s=[x|r<-s,x<-a,elem x r]

```

Try it online! Example usage: `[1,2,3,4,5,6,7] # [[1,2,3],[4,5,6,7]]` yields `[1,2,3,4,5,6,7]`.

# Answer
> 4 votes
# Mathematica, 39 bytes

```
x##&@@Cases[x,#|##&@@Range@##]&@@@#&

```

-22 bytes from JungHwan Min
-4 bytes from Martin

Try it online!

# Answer
> 4 votes
# Jelly, 4 bytes

```
fÐ€Ẏ

```

Try it online!

Takes input as present list, full ranges.

# Answer
> 4 votes
# 05AB1E, 3 bytes

```
δÃ˜

```

Try it online! (thanks to Adnan for letting me know `δ` exists, -1 byte)

### How it works

```
δÃ˜  | Full program.

δ    | Double-vectorize the next command (something like an outer product).
 Ã   | List intersection. Since this is a dyad, the first input is automatically
     | used to fill the missing argument (as far as I know).
  ˜  | Flatten.

```

# Answer
> 3 votes
# Pyth, 5 bytes

```
s@Rvz

```

**Try it here!**

# Pyth, 10 bytes

```
s.gx}LkQ1E

```

**Try it here!**

### How they work

```
s@Rvz  | Full program.

  R    | Right map...
 @     | ... Using intersection.
   vz  | Of the first input with the second.
s      | Flatten by one level.

```

```
s.gx}LkQ1E  | Full program.

 .g      E  | Group the items in the second input by...
    }LkQ    | Map over the first input, and check if the current item is in the list.
   x    1   | Take the index of the first truthy element.
s           | Flatten.

```

Takes the docks first, with all the integers in the ranges, and then the presents on a new line.

# Answer
> 3 votes
# Python 2, ~~49~~ 46 bytes

thanks to @HyperNeutrino for -3 bytes

```
lambda p,b:[x for l in b for x in p if x in l]

```

Try it online!

---

**Ungolfed**

```
def f(presents, groups):
  result = []
  for group in groups:
    for present in presents:
      if present in group:
        result.append(present)
  return result

```

Try it online!

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

```
O$`(\d+)(?=.*¶(.*)\[.*\b\1\b)
$2
G1`

```

Try it online! Takes input as a list of presents on the first line and a list of ranges on the second line; the link includes a header to split the test cases into the desired format. Edit: Saved 1 byte thanks to @MartinEnder. Explanation: The first stage matches the presents and finds the matching dock. The presents are sorted by the substring from the start of the line to the `[`, thus grouping the presents by dock. The second stage then deletes the docks.

# Answer
> 2 votes
# APL+WIN, 29 bytes

```
(,⍉<\p←n∘.≤∊¯1↑¨⎕)/(×/⍴p)⍴n←⎕

```

Prompts for screen input for both the integers and ranges. The integers as a flat list and the ranges as a nested vector, e.g case 3:

```
(1 3) (4 5) (6 7)

```

Explanation:

```
(×/⍴p)⍴n←⎕ prompt for screen input of integers and replicate by the number of ranges

∊¯1↑¨⎕ prompt for screen input of ranges and select the top of each

p←n∘.≤ create a boolean matrix using outer product with less than the top of each range

,⍉<\ identify the first range which each element fits in and ravel into a partition vector

(.....)/.... use the partition vector to select the elements in each range in order

```

# Answer
> 2 votes
# Enlist, 3 bytes

```
f₱Ẏ

```

Try it online!

### How it works

```
f₱Ẏ  | Full program.

 ₱   | Map over right argument.
f    | Using list intersection, counting multiplicities.
  Ẏ  | Tighten (flatten by 1 level).

```

# Answer
> 2 votes
# , 26 24 bytes

2 bytes thanks to cole

```
[:;]<@#~1=-&1 0"1@[I."1]

```

# How it works:

The left argument holds the ranges.

`-&1 0"1@[` decreases the lower boundary of each range by 1

`I."1]` checks in which range fits each present

`1=` is it in the correct range

`]<@#~` copies and boxes the presents which are in the current range

`;` \- raze (unboxing)

Try it online!

# Answer
> 2 votes
# J, 15 bytes

```
[/:[:I.e.&>"0 1

```

Takes the input as the *left* argument and the ranges as the *right* argument. The ranges are boxed lists of the complete ranges.

e.g. for the first range:

```
   NB. This produces the range
   (1 2 3 ; 4 5 6 7)
┌─────┬───────┐
│1 2 3│4 5 6 7│
└─────┴───────┘

```

Try it online!

# Explanation

```
[/:[:I.e.&>”0 1
          >”0 1  Pair each element on the left with each range on the right
       e.        Is the element in the range?
     I.          Indices of ones
[/:              Sort the elements by this array

```

# Answer
> 2 votes
# C++, 127 bytes

Take input as two arrays represented by pairs of pointers `[start, end)`.

```
#import<algorithm>
[](int*A,int*x,int*B,int*y){for(;B!=y;B+=2)A=std::stable_partition(A,x,[&](int a){return a>=*B&&a<=B[1];});}

```

Try it online!

# Answer
> 2 votes
# , ~~113~~ ~~48~~ ~~55~~ 41 bytes

A previous version didn't correctly sort objects when the docks weren't in increasing order.

```
function(P,D)for(d in D)cat(P[P%in%d],"")

```

Try it online!

Takes `D` as a list of vectors of ranges, i.e., `list(4:7,1:3)` would be `[[4, 7], [1, 3]]`.

Probably the naive answer I should have arrived at ages ago; prints to stdout.

# Answer
> 2 votes
# Japt, 6 bytes

```
ñ@VbøX

```

Try it

---

## Explanation

Implicit input of array `U` (presents) and 2d-array `V` (full ranges). Sort (`ñ`) the presents by passing them through a function (`@`) that gets the index of the first element (`b`) in `V` that contains (`ø`) the current present (`X`).

# Answer
> 1 votes
# Javascript ES6, ~~53~~ ~~47~~ 45 bytes

```
p=>l=>l.map(d=>p.filter(a=>d.includes(a)))+''

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~97~~ 85 bytes

```
l,d=input()
k=lambda i,j=0:-~j*(d[j][0]<=i<=d[j][1])or k(i,j+1)
print sorted(l,key=k)

```

-11 bytes from ovs

-1 byte from Mr. Xcoder

Try it online!

Sorts the list using a recursive lambda as the key. Explanation ~~coming soon™~~ below.

Explanation:

```
l,d=input()             # l is the lsit of presents, d is the list of ranges
k=lambda i,j=0:-~j*(d[j][0]<=i<=d[j][1])or k(i,j+1)# recursive lambda to sort with
k=lambda i,j=0:                                    # i is the present
                                                   # j is the index in the list of ranges
               -~j*(d[j][0]<=i<=d[j][1])           # return the index of the list of
                                                   # ranges(plus one) if the present is
                                                   # in the range
                                        or k(i,j+1)# if the present is not in the range,
                                                   # try the next range
print sorted(i,key=k)   # print the list of presents sorted by the lambda

```

# Answer
> 1 votes
# PowerShell, 37 bytes

```
param($a,$b)$b|%{$i=$_;$a|?{$_-in$i}}

```

Try it online!

Takes `$a` as a literal array of the presents and `$b` as an array of arrays, each of which are the full range (e.g., `@(1,2,3,4,5)` instead of `@(1,5)`). We then loop over each item in `$b` with `|%{...}`. Inside, we need to set a helper `$i` to be the current item, then use a `Where-Object` clause against `$a` to pull out only those items that are `-in` the current `$b` array.

Those are left on the pipeline and output is implicit. Since the default behavior of `Write-Output` inserts a newline between array elements, that's what we get. Here is a slightly tweaked version that is `-join`ed together via commas instead of a newline, just to show differences.

# Answer
> 1 votes
# Red, 73 bytes

```
f: func[b r][n: copy[]foreach p r[foreach a b[if find p a[append n a]]]n]

```

Try it online!

# Answer
> 1 votes
# Windows Batch (CMD), ~~90~~ 79 bytes

```
set/pX=||exit
set/pY=
for %%n in (%*)do if %X% LEQ %%n if %%n LEQ %Y% %%n
%0 %*

```

Use LF end-of-line format. Each end-of-line character can be counted as 1 byte.

No TIO (because TIO uses Linux)

Take the list from command line arguments, and ranges from `stdin`.

For example, if the program is run (assume the file is named `r1.cmd`)

```
r1 7 3 5 4 6 1 2

```

and with `stdin` input

```
1
3
4
5
6
7

```

, the program will output to `stderr` with format

```
'3' is not recognized as an internal or external command,
operable program or batch file.
'1' is not recognized as an internal or external command,
operable program or batch file.
'2' is not recognized as an internal or external command,
operable program or batch file.
'5' is not recognized as an internal or external command,
operable program or batch file.
'4' is not recognized as an internal or external command,
operable program or batch file.
'7' is not recognized as an internal or external command,
operable program or batch file.
'6' is not recognized as an internal or external command,
operable program or batch file.

```

(corresponds to output sequence `3 1 2 5 4 7 6`)

---

Explanation:

```
set /p X=       Prompt for variable X (min range)
   ||exit       If failed (end of file), exit - similar to short-circuit of logical OR
set /p Y=       Prompt for variable Y
for %%n in (%*)do     For each number %%n in all command-line arguments
   if %X% LEQ %%n     If X <= n
      if %%n LEQ %Y%  and n <= Y
         %%n          run command named "n", which lead to an error.

%0 %*           Call itself, process other ranges

```

---

Ungolfed code (with interaction enabled if `true` is passed as argument 1; prompt for the list from `stdin`, use `goto` to avoid stack overflow - actually I've just tried to run a script that call itself over 70000 times without seeing any problem, so I guess it should be pretty safe):

```
@echo off

set INTERACTIVE=%1

if "%INTERACTIVE%" == "true" (
    set rangeMinPrompt=Enter range min:
    set rangeMaxPrompt=Enter range max:
    set listPrompt=Enter list:
) else (
    set rangeMinPrompt=
    set rangeMaxPrompt=
    set listPrompt=
)

set /p list=%listPrompt%

:loop_label

set /p rangeMin=%rangeMinPrompt%&& set /p rangeMax=%rangeMaxPrompt%|| exit /b

for %%n in (%list%) do (
    if %rangeMin% LEQ %%n (
        if %%n LEQ %rangeMax% (
            echo %%n
        )
    )
)

goto :loop_label

```

# Answer
> 1 votes
# C# (.NET Core), 50 + 18 bytes

```
a=>b=>b.SelectMany(x=>a.Where(y=>y>=x[0]&y<=x[1]))

```

+18 bytes from

```
using System.Linq;

```

It takes a collection for presents and a collection of arrays for docks.

Try it online!

# Answer
> 1 votes
# Clean, 59 bytes

```
import StdEnv;f p l=flatten[[n\\n<-p|a<=n&&n<=b]\\[a,b]<-l]

```

Try it online!

Takes two lists, returns a list.

# Answer
> 1 votes
## Wolfram Language (Mathematica), 34 bytes

```
r#~SortBy~{#&@@@r~Position~#&}&

```

Try it online!

is the `Function` operator.

This is an unnamed curried function which should be called first with the list of (expanded) dock ranges and then with the list of presents. For example, if you assign the function to `f`:

```
f[ {{4,5,6,7},{1,2,3}} ][ {1,2,3,4,5,6,7} ]

```

The list of presents simply sorted by the first-level position of the value in the list of dock ranges. We need to wrap the `SortBy` function in a list to make the sort stable.

# Answer
> 1 votes
# Julia 0.6, ~~31~~ 30 bytes

```
p%d=vcat((∩(p,x)for x=d)...)

```

Try it online!

Redefines the `%` operator and maps the set intersection`∩()` over the docks `d` maintaining order and multiplicity of the first imput, the list of presents `p`. `vcat` with the input expanded to multiple arguments via `...` flattens the resulting nested array.

Edit, -1Byte: List comprehension instead of `map()`.

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


title: Draw an ASCII key signature

text:
# Question
Title: Draw an ASCII key signature
Given an input of a note, output an ASCII drawing of the corresponding major key on the treble clef.

Here are all the major keys (that don't include double-sharps or double-flats) and their corresponding key signatures:

<sup>*Circle of fifths deluxe 4* by Wikipedia user Just plain Bill, copyright CC BY-SA 3.0</sup>

If the input is a key with sharps, draw the following ASCII art with the appropriate number of sharps:

```
   #
-#-------
      #
----#----
  #
-------#-
     #
---------

---------

```

And if the input is a key with flats:

```
---------
  b
----b----
      b
-b-------
   b
-----b---
       b
---------

```

Here is a concise summary of the possible inputs as well as how many sharps or flats they use:

```
   0   1   2   3   4   5   6   7
#  C   G   D   A   E   B   F#  C#
b  C   F   Bb  Eb  Ab  Db  Gb  Cb

```

All five lines of dashes must always be drawn, but there may be any number of dashes per line such that the sharps or flats have at least one column of padding on each side, as long as each line of dashes has the same length. For example, these are all also acceptable outputs for the input `Ab`:

```
---------   ------   ---------   ----------------
  b           b           b          b
----b----   ----b-   -------b-   ------b---------

-b-------   -b----   ----b----   ---b------------
   b           b           b          b
---------   ------   ---------   ----------------

---------   ------   ---------   ----------------

```

In the case of C major, which has no sharps nor flats, any positive number of dashes per line (even one) is acceptable.

Any amount of leading or trailing whitespace is fine, as are trailing spaces on each line. Extra leading spaces are okay as long as there are the same number on each line.

You may take input in lowercase or require that inputs without a sharp or flat contain a trailing space, if you so desire.

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

# Answer
# Python 2, ~~206 197 178 175 168~~ 161 bytes

*Thanks to Mr. Xcoder for -12 bytes!*

This is a function which returns the result as a 2D list of characters. If the input does not contain a sharp/flat, it should be padded with a space.

```
def f(k,r=range(10)):n="CGDAEB".find(k[0])+7*' #'.find(k[1]);return[[(' -'[i%2],'b#'[n>0])[0<j<=abs(n)and`i`==(n*"1403625"+"5263748")[j-1]]for j in r]for i in r]

```

**Try it online!**
> 3 votes

# Answer
# Charcoal, 60 bytes

```
≔⁻⁺⊖﹪⊗℅§θ¬χ⁷×⁷№θ#×⁷№θbθ←ＵＯ⁹¦⁹-¶Ｆθ«Ｊι⊖﹪⊕×³ι⁷#»Ｆ±θ«Ｊι⊕﹪⁺³×⁴ι⁷b

```

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

```
≔⁻⁺⊖﹪⊗℅§θ¬χ⁷×⁷№θ#×⁷№θbθ

```

Calculate the number of sharps in the key signature.

```
←ＵＯ⁹¦⁹-¶

```

Print the stave, but one square left of the origin so that the first sharp/flat is in column zero.

```
Ｆθ«

```

Loop over any sharps.

```
Ｊι⊖﹪⊕×³ι⁷#»

```

Calculate the row of the sharp and print it.

```
Ｆ±θ«

```

Loop over any flats.

```
Ｊι⊕﹪⁺³×⁴ι⁷b

```

Calculate the row of the flat and print it.
> 3 votes

# Answer
# Befunge, 139 bytes

```
~9%:4%7*+4/7%~6%1-2/7*+vv\`0:\!-g02+*2g00+1%7+g00*+3g00::<<0+55p02:_@
- b#09p01*-1*2p00:`0:-8<>10g`!**:00g2+*\!20g2%*+1g,1+:8`!#^_>$,:1-\^1

```

Try it online!

Note that the input is expected to be terminated with a linefeed, as would typically occur when running the program interactively.

**Explanation**

We start by reading two characters from stdin - the main note, *n*, and an accidental, *a* (which can be a linefeed if there is no accidental). Using those values, we calculate the key signature number, *signum*, as follows:

```
signum = (n%9 + n%9%4*7)/4%7 + (a%6 - 1)/2*7 - 8

```

This returns a value in the range -7 to 7, where the sign tells us whether we need sharps or flats (positive or negative), and the absolute value gives us the number of sharps or flats required. So for later use, we extract the sign, *s*, and the the accidental count, *cnt*, with:

```
s   = (signum > 0)
cnt = abs(signum)

```

Then we have two nested loops, iterating a row number, *r*, from 9 down to 0, and a column number, *c*, from 0 up to 8. For a particular row and column, we calculate whether an accidental should be visible at that point with:

```
accidental = (r == (c*(s+3) + s)%7 + 1 + s*2) and (c > 0) and (c <= cnt)

```

If it's not an accidental, we need to output a line or space depending on whether the row, *r*, is odd or even. And if it is an accidental, we need to output a sharp or flat depending on the sign, *s*. So we evaluate the following formula:

```
index = (!accidental * (r%2)) + (accidental * (s+2))

```

Which gives us an index in the range 0 to 3, representing either a line, a space, a flat or a sharp. We simply use that index to lookup the required output character from a table, which you can see embedded at the start of the second line of code.
> 2 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, music
---


title: ASCII Airplane Banner

text:
# Question
Title: ASCII Airplane Banner
Given two inputs -- one of them a non-empty printable ASCII string (including space, excluding newline), the other being one of two distinct, consistent values of your choice (`1 / 0`, `l / r`, `left / right`, etc.) -- output an ASCII art airplane banner of the string, pointing either left or right. For consistency, I'll be using `left` and `right` throughout this challenge description.

The plane is either `|-DI>-/` (`left`) or `\-<ID-|` (`right`). Since the banner is clear, it consists of the input string's characters separated by spaces, either left-to-right (`left`) or right-to-left (`right`), and surrounded by a box of the shape

```
    /--/
---<  <
    \--\

```

or

```
\--\
 >  >---
/--/

```

Note there must be one space between the beginning/end of the message and the `>`,`<` characters.

For example, here is the message `HAPPY BIRTHDAY!` and the direction `left`:

```
           /-------------------------------/
|-DI>-/---< H A P P Y   B I R T H D A Y ! <
           \-------------------------------\

```

Here is the message `PPCG` and the direction `right`. Note that the letters appear "backwards" when viewed from this side of the banner:

```
\---------\
 > G C P P >---\-<ID-|
/---------/

```

## Rules

* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 6 votes
# Perl 5, ~~149~~ 102 + 4 (`-plF` ) = ~~150~~ 106 bytes

*Shortened using tricks I've learned since the original answer. Still scored using the rules in effect at the time of the question.*

```
s/./--/g;$_=$"x11 ."/-$_/";$_.="
|-DI>-/---< @F <
".y|\\/|/\\|r;if(<>){y|<>|><|;$_=reverse;s|-/|-\\|}

```

Try it online!

Two line input. First is the message. Second is 0 for left, 1 for right.

# Answer
> 6 votes
# JavaScript (ES6), ~~141~~ 138 bytes

String and direction are input via currying syntax.
`'/\n|-DI>-/---< '` for left, `'/\n|-DI<-\\---> '` for right.

```
t=>p=>(r=`${s='           '}/${_='-'.repeat(t.length*2+1)}${p}${[...t].join` `} ${d=p[12]}
${s}\\${_}\\`,d>'<'?[...r].reverse().join``:r)

```

```
f=

t=>p=>(r=`${s='           '}/${_='-'.repeat(t.length*2+1)}${p}${[...t].join` `} ${d=p[12]}
${s}\\${_}\\`,d>'<'?[...r].reverse().join``:r)

console.log(f('HAPPY BIRTHDAY!')('/\n|-DI>-/---< '))
console.log(f('HAPPY BIRTHDAY!')('/\n|-DI<-\\---> '))
```

# Answer
> 4 votes
# , ~~73~~, 65 bytes

```
Ó./&
É ÄÒ-ys$/YGpr\$.11>Hj|R|-DI>-/³-<A< ÀñkæG|æ}-r>$BR>³-\-<

```

Try it online!

Not the greatest score, but that's because almost half of this comes from reversing the output.

Hexdump:

```
00000000: d32e 2f26 200a c920 c4d2 2d79 7324 2f59  ../& .. ..-ys$/Y
00000010: 4770 725c 242e 3131 3e48 6a7c 527c 2d44  Gpr\$.11>Hj|R|-D
00000020: 493e 2d2f b32d 3c1b 413c 201b c0f1 6be6  I>-/.-<.A< ...k.
00000030: 477c e616 7d2d 723e 2442 523e b32d 5c2d  G|..}-r>$BR>.-\-
00000040: 3c                                       <

```

Takes the string as input to the buffer, and the direction as `0` for left and `1` for right as command line arguments.

# Answer
> 4 votes
# 05AB1E, 63 bytes

```
„\\S'-¹g·>×ýD∞2äθ‚11ú"|-DI>-/---<"¸¹ε²i∞θ}J'<«S«ð«J¸«Àε²i∞2äθ}»

```

Try it online!

Based off bugs that may get fixed in the future.

# Answer
> 4 votes
# Charcoal, ~~44~~ ~~40~~ ~~39~~ 35 bytes

```
|-DI>-/³↗<→/-ＬηＬη↙¹←< ¿Ｎ↷⁴‖Ｔ⮌⪫η ‖Ｂ↓

```

Try it online! Link is to verbose version of code. First input is 1 for right and 0 for left, second is banner string. Edit: ~~Saved 1 byte by using~~ `ReflectButterfly(:Up)` ~~as `ReflectButterfly(:Down)`~~ currently has a cursor positioning bug, but I saved a further 4 bytes by reversing the print direction, and now it doesn't matter which I use. ~~38~~ ~~34~~ 32 byte version if mirroring the banner was allowed:

```
|-DI>-/³Ｐ⪫⪫<<η ↘→\-ＬηＬη↖¹‖Ｂ↑¿Ｎ‖Ｔ

```

Try it online! Link is to verbose version of code. First input is 0 for right and 1 for left. Explanation:

```
|-DI>-/

```

Print the plane.

```
³↗<→/-ＬηＬη↙¹←<

```

Print the top half of the box (note trailing space).

```
¿Ｎ↷⁴‖Ｔ

```

If the second input is nonzero, reverse the print direction, otherwise reflect the plane and box.

```
⮌⪫η

```

Print the message with extra spacing (note trailing space). The cursor is at the far end of the box from the plane so the message needs to be reversed.

```
‖Ｂ↓

```

Reflect to get the bottom half of the box.

# Answer
> 2 votes
# Jelly, ~~68~~ 65 bytes

```
“/\<“\/>”y
³K“|-DI>-/---< “ < ”j
LḤ‘”-x⁾//jṭ⁶x11¤Fµ,Ñj¢œs3U⁴¡YÑ⁴¡

```

Try it online!

Takes 1 for right, 0 for left.

*-3 bytes thanks to @JonathanAllan* (*grr* I always forget `AB+` does the same as `B+@A`)

# Answer
> 1 votes
# SOGL V0.12, ~~55~~ ~~47~~ 43 bytes

```
└"┐ξA∫`Ν┌r4≥‘┘¹§,{e⌡↔@¹"╝′‰‘┼}"-<-/ \”┼e?±↔

```

Try it Here!

0 for left and 1 for right

# Answer
> 1 votes
# Charcoal, 56 bytes

<sup> -8 bytes thanks to totallyhuman and Erik the Outgolfer!</sup>

```
≔⪫Ｓ θ≔⁺Ｌθ²η× ¹¹/η/⸿|-DI>-/³<× η<‖Ｂ↓ＦＮ«‖ＴＭ⁺η³→≔⮌θθ»↑↑Ｍη←θ

```

Try it online!

Fixing the cases dzaima mentioned took quite a toll on the byte count. 36 bytes if we are allowed to reverse characters like `<` and `/`.

# Answer
> 1 votes
# Python 2, ~~137~~ ~~136~~ 133 bytes

```
lambda s,d:'{0}/{1}-/\n|-DI{3}-{4}---{5} {2} {5} \n{0}\\-{1}\\'.format(' '*11,'--'*len(s),' '.join(s),*list('></\\<>')[d::2])[::-d|1]

```

Try it online!

`1` for right and `0` for left

# Answer
> 1 votes
# PHP, 175 bytes

```
[,$d,$s]=$argv;$f=str_repeat("--",strlen($s));$r="\-$f\
 ".join(" ",str_split("><"[$d].$s)).($d?" <---/->":" >---\-<")."ID-|
/-$f/           ";echo$d?strrev($r):$r;

```

Run with `-nr`, first argument = `0` for facing right or `1` for left and second argument=text
or try it online.

# Answer
> 1 votes
# Corea, 51 bytes

```
"u *:>ip.j:l)X-'/S:>"
|-DI>-/---< V<
"h}>>`tHL`idF

```

Try it online!

## Explanation

The program is composed of a few parts:

## 1: Initialization

```
"u *:>ip.j:l)X-'/S:>"
"..................."   execute the inside as code
 u                      repeat
   *                    a space, 11 times
    :                   duplicate this string
     >                  write this string to the content field
      i                 take a line of input
       p                push a space
        .j              insert that space after every character
          :l)           get (length(str) + 1)
             X-         repeat a hyphen that many times
               '/       push the "/" character
                 S      surround that string with the above character
                  :>    duplicate and write that string to the content field

```

## 2: raw text

The following text is outputted to the content field:

```

|-DI>-/---< V<

```

## 3: postamble

```
"h}>>`tHL`idF
"               execute until the end of the file
 h              mirror the previous string horizontally
  }             move the modified input string to the front of the stack
   >>           write the top two strings to the content field
     `   `id    do the inside `i`nput times
      tH        reflect the content field horizontally and vertically
        L       reverse the input string
            F   save the input string in a field (default: V)
                this replaces all Vs in the code with the input string

```

# Answer
> 1 votes
## Perl 5, 126 bytes

**124 bytes code + 2 for `-pl`.**

```
s/./$& /g;$_=($q=$"x11 .'/-'.s/./-/gr."/
")."|-DI>-/---< $_<
".$q=~y|\\/|/\\|r;<>&&(y|<>|><|,$_=reverse,s/>/ >/,s|-/-|-\\-|)

```

Try it online!

# Answer
> 1 votes
# Google Sheets, 210 Bytes

Anonymous worksheet function that takes input input as string from \[A1\] and int from range \[B1\] where 1 indicates that the plane is on the left and 0 indicates that the plane is on the right.

```
=If(B1,"           /","\")&Rept("-",2*Len(A1)+1)&If(B1,"/
","\
")&If(B1,"|-DI>-/---< "," > ")&RegexReplace(A1,"(.)","$1 ")&If(B1,"<
",">---\-<ID-|
")&If(B1,"           \","/")&Rept("-",2*Len(A1)+1)&If(B1,"\","/

```

# Answer
> 0 votes
# Excel VBA, 198 Bytes

Anonymous VBE immediate window function that takes input as string from `[A1]` and int from range `[B1]` where `1` indicates that the plane is on the left and `0` indicates that the plane is on the right.

```
b=[B1]:a=StrConv(IIf(b,[A1],StrReverse([A1])),64):j=[Rept("-",2*Len(A1)+1)]:k="/"&j &"/":l="\"&j &"\":s=Space(11):?IIf(b,s &k,l):?IIf(b,"|-DI>-/---< "," > ")a;IIf(b,"<",">---\-<ID-|"):?IIf(b,s &l,k)

```

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


title: Hilbert's binary Hotel

text:
# Question
Title: Hilbert's binary Hotel
In this challenge you will be asked to implement any function (or full program) that fulfills two properties. Those properties are:

* Your function must be an injective (reversible) function from the polynomials with non-negative integer coeffecients to the non-negative integers. This means no two unequal inputs can map to an equal output.
* Your function must preserve the total number of "on bits" from its input to its output. This means if you count the 1 bits of each coefficient of the polynomial, their sum should be the same as the number of 1 bits in the binary representation of the output. For example `9` is `1001` in binary so it has 2 `1` bits.

---

# IO

A non-negative integer polynomial is the same as a infinite list of non-negative integers such that after a certain point all the integers are zero. Thus, polynomials may be represented either by infinite lists (although this is probably undesirable) or by finite lists with implicit zeros after the end of the list.

The key distinction between polynomials and finite lists is that adding a zero to the end of a list will change the list:

While adding a zero to the end of a polynomial does not change its value:

Thus if your function takes a finite list representing a polynomial as input, adding a zero must not change its result.

When representing polynomials as lists, you may represent them either with the first or last entry representing the constant term. For example you could have either of the following possibilities:

In the first case, adding zeros to the end of the list should not change the result; in the second case, adding zeros to the *front* of the list should not change the result.

Of course if your language supports polynomials you may take those as inputs.

Output should be a non-negative integer output via any standard methods.

---

This is so answers will be scored in bytes, with fewer bytes being better.

# Answer
> 7 votes
# Jelly, 8 bytes

```
BFṢḄæ«ÆẸ

```

Try it online!

### Left inverse, 5 bytes

```
Bċ0ÆE

```

Try it online!

### How it works

```
BFṢḄæ«ÆẸ  Main link. Argument: A (array)

B         Binary; convert each integer in A to base 2.
 F        Flatten; concatenate the resulting binary arrays.
  Ṣ       Sort the resulting bit array.
   Ḅ      Convert from base 2 to integer, yielding an integer x with as much set
          bits as there are set bits in A.
      ÆẸ  Unexponents; convert A = [a1, a2, ...] to y = (p1**a1 + p2**a2 + ...),
          where pn is the n-th prime number.
          By the fundamental theorem of arithmetic, the resulting integer is unique
          for each array A without trailing zeroes.
    æ«    Bitshift left; compute x * 2**y.

```

# Answer
> 6 votes
# Wolfram Language (Mathematica), ~~36~~ 20 bytes

```
x#/.x->2^(#/.x->2)!&

```

Try it online!

Takes a polynomial f(x) as input. Evaluates y\*f(y), where y = 2^(f(2)!). Regrettably, this means that the outputs get pretty large.

Evaluating y\*f(y) will preserve the number of 1-bits whenever y is a power of 2 bigger than any coefficient, which is true for the value chosen above. We choose y = 2^(f(2)!) to make the result injective:

* Two different inputs with the same value of y will give different outputs because we're essentially reading two different numbers in base y.
* If we fix k=f(2) and therefore y, the smallest value of y\*f(y) is achieved when the input is a constant polynomial equal to k and the largest value is achieved when the input is the polynomial giving the base-2 expansion of k. In the first case, y\*f(y) = 2^(k!)\*k, and in the second case, y\*f(y) \< 2^(k!\*ceil(lg k)), which is less than 2^((k+1)!)\*(k+1).
* As a result, for two polynomials f and g with f(2) \< g(2), the integer we get from f will be less than the integer we get from g.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 61 bytes

```
Tr[2^((2#2-1)2^#)&@@@Position[Reverse/@#~IntegerDigits~2,1]]&

```

Try it online!

Two positive integers can be mapped to a single positive integer. Let `a, b` be two positive integers. Then `a, b -> (2a - 1) 2^(b-1)` is a bijection from NxN to N.

This function finds the position of all `1` bits in the input (from the 1s place), and applies an injective-only variant of the above map to each position. Then, each resulting number is raised to the power of two, and all numbers are added together (which is okay since we applied an injective NxN -\> N map).

For example:

```
{1, 2, 3}
{{1}, {1, 0}, {1, 1}}             (* Convert to binary *)
{{1}, {0, 1}, {1, 1}}             (* Reverse each *)
{{1, 1}, {2, 2}, {3, 1}, {3, 2}}  (* Position of 1s *)
{2, 12, 8, 24}                    (* Inject to N *)
{4, 4096, 256, 16777216}          (* Raise to the power of 2 *)
16781572                          (* Add *)

```

### Inverse function (124 bytes)

```
##+#&~Fold~#&@*Reverse/@Normal@SparseArray[{Log2[j=#~BitAnd~-#],(#/j+1)/2}->1&@@@(Reverse[#~IntegerDigits~2]~Position~1-1)]&

```

Here's an inverse function to test for injectivity.

Try it online!

# Answer
> 5 votes
# Python 2, ~~118~~ ~~117~~ ~~114~~ ~~103~~ 100 bytes

100 bytes by Jonathan Frech:

```
a=input()
while a[0]<1:a.pop(0)
y="".join("2"+bin(v)[2:]for v in a)
print~-2**y.count("1")<<int(y,3)

```

Try it online!

103 bytes with a golfing possibility1

```
a=input()
while a[0]<1:a.pop(0)
x="".join(map(bin,a))
print~-(1<<x.count("1"))<<int(x.replace(*"b2"),3)

```

Try it online!

*-15 bytes thanks to Jonathan Frech*

It creates a number that first contains the "on bits" and then the unary representation of the array interpreted as a trinary number.

The trinary number is created by converting the numbers to binary strings (`0bNNN`), then replacing `b` with `2`.

1I could have saved 14 bytes by converting it to a base-12 number instead, but TIO ran out of memory so I decided to use this.

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
gÅpImPoIbS{2β*

```

Try it online!

Yields the same results as Dennis' Jelly solution, yet the technique is *slightly* different.

## How?

Let's try the input `[1, 2, 3]`:

```
gÅpImPoIbS{2β* | Full program.
               | STACK: [[1, 2, 3]]
               |
g              | Push the length.
               | STACK: [3]
 Åp            | Generate the first N primes.
               | STACK: [[2, 3, 5]]
   Im          | Push the input, and apply pairwise exponentiation.
               | STACK: [2, 9, 125]
     P         | Push the product.
               | STACK: 2250
      o        | Push 2 ** N.
               | STACK: 2 ** 2250 (way too large)
       Ib      | Push the input and convert to binary.
               | STACK: [2 ** 2250, ['1', '10', '11']].
         S{    | Sort all the characters.
               | STACK: [2 ** 2250, ['0', '1', '1', '1', '1']]
           2β  | Convert from binary.
               | STACK: [2 ** 2250, 15]
             * | Multiplication.
               | STACK: [2 ** 2250 * 15]
               | Implicitly print the top of the stack (2 ** 2250 * 15).

```

# Answer
> 1 votes
# Python 2, 74 bytes

```
r='print 0';s='<<'
for n in input():r+=oct(n)[:0:-1];s+='0'+'1'*n
exec r+s

```

Try it online!

# Answer
> 0 votes
# JavaScript 6, ~~96~~ 83 Bytes

```
x=>(t=x.map(k=>(x[0]+=k)&&2+k.toString(2)).join``).replace(/0|2/g,'')+'0'.repeat(t)

```

outputs a binary expression

```
([1,2]) => 3*2^21210(Decimal)
([0,1,2]) => 3*2^21210
([1,2,0]) => 3*2^2121020
([1,2,3,4]) => 31*2^212102112100(Threotically)

```

---
Tags: code-golf, math, binary, open-ended-function
---


title: Queue Our Decomposition

text:
# Question
Title: Queue Our Decomposition
In this challenge I will ask you to find a QR decomposition of a square matrix. The QR decomposition of matrix **A** is two Matrices **Q** and **R** such that **A = QR**. In particular we are looking for **Q** to be an orthogonal matrix (that is **QTQ=QQT=I** where **I** is the multiplicative identity and **T** is the transpose) and **R** to be a upper triangular matrix (every value below its diagonal must be zero).

You will write code that takes a square matrix by any reasonable method and outputs a QR decomposition by any method. Many matrices have multiple QR decompositions however you only ever need output one.

Elements of your resultant matrices should be within two decimal places of an actual answer for every entry in the matrix.

This is a competition so answers will be scored in bytes with fewer bytes being a better score.

---

### Test Cases

*These are only possible outputs, your outputs need not match all of these as long as they are valid.*

```
0 0 0     1 0 0   0 0 0
0 0 0 ->  0 1 0   0 0 0
0 0 0     0 0 1 , 0 0 0

1 0 0     1 0 0   1 0 0
0 1 0 ->  0 1 0   0 1 0
0 0 1     0 0 1 , 0 0 1

1 2 3     1 0 0   1 2 3
0 3 1 ->  0 1 0   0 3 1
0 0 8     0 0 1 , 0 0 8

0 0 1     0 0 1   1 1 1
0 1 0 ->  0 1 0   0 1 0
1 1 1     1 0 0 , 0 0 1

0 0 0 0 1     0 0 0 0 1   1 0 0 0 1
0 0 0 1 0     0 0 0 1 0   0 1 1 1 0
0 0 1 0 0 ->  0 0 1 0 0   0 0 1 0 0
0 1 1 1 0     0 1 0 0 0   0 0 0 1 0
1 0 0 0 1     1 0 0 0 0 , 0 0 0 0 1

```

# Answer
# Octave, 19 bytes

```
@(x)[[q,r]=qr(x),r]

```

Try it online!

My first Octave answer \o/

Octave’s `qr` has quite a few alternatives in other languages that return both **Q** and **R**: `QRDecomposition` (Mathematica), `matqr` (PARI/GP), `128!:0` \- if I recall correctly - (J), `qr` (R)...
> 5 votes

# Answer
# Julia, 2 bytes

```
qr

```

The function `qr` accepts a square matrix and returns a `Tuple` of matrices: **Q** and **R**.

Try it online!
> 5 votes

# Answer
# Wolfram Language (Mathematica), 15 bytes

```
QRDecomposition

```

Try it online!

I mean... what can I say?
> 4 votes

# Answer
# , ~~38~~ 37 bytes

```
pryr::f(list(qr.R(q<-qr(m)),qr.Q(q)))

```

Try it online!
> 3 votes

# Answer
# SageMath, 27 bytes

```
lambda x:matrix(RDF,x).QR()

```
> 1 votes

# Answer
# Python 2, ~~329~~ 324 bytes

```
import fractions
I=lambda v,w:sum(a*b for a,b in zip(v,w))
def f(A):
 A,U=[map(fractions.Fraction,x)for x in zip(*A)],[]
 for a in A:
    u=a
    for v in U:u=[x-y*I(v,a)/I(v,v)for x,y in zip(u,v)]
    U.append(u)
 Q=[[a/I(u,u)**.5 for a in u]for u in U];return zip(*Q),[[I(e,a)*(i>=j)for i,a in enumerate(A)]for j,e in enumerate(Q)]

```

We must use fractions to ensure correct output, see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt\_process#Numerical\_stability

Indentation used:

1. 1 space
2. 1 tab
> 1 votes

# Answer
# Python with numpy, 28 bytes

```
import numpy
numpy.linalg.qr

```
> 0 votes

---
Tags: code-golf, math, matrix, factoring
---