title: Opposite of the digital root!

text:
# Question
Title: Opposite of the digital root!
*Also known as the \[analog root\]*

*(Opposite of the digital root!) ;)*

The digital root of a number is the continuous summation of its digits until it is a single digit, for example, the digital root of 89456 is calculated like this:

8 + 9 + 4 + 5 + 6 = 32

3 + 2 = 5

The digital root of 89456 is 5.

Given a digit as input via **STDIN**, print/return all of the possible two digit numbers that have that digital root. If you need it to, it can include itself, e.g. 05

These are all of the possible inputs and outputs:

**(You get to choose whether or not to include the leading zero for the digit itself)**

## I/O

**0** =\> 0 or 00 or nothing

**1** =\> 01 and/or 1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91 - **Make sure that 1 does not return 100**

**2** =\> 02 and/or 2, 11, 20, 29, 38, 47, 56, 65, 74, 83, 92

**3** =\> 03 and/or 3, 12, 21, 30, 39, 48, 57, 66, 75, 84, 93

**4** =\> 04 and/or 4, 13, 22, 31, 40, 49, 58, 67, 76, 85, 94

**5** =\> 05 and/or 5, 14, 23, 32, 41, 50 ,59, 68, 77, 86, 95

**6** =\> 06 and/or 6, 15, 24, 33, 42, 51, 60, 69, 78, 87, 96

**7** =\> 07 and/or 7, 16, 25, 34, 43, 52, 61, 70, 79, 88, 97

**8** =\> 08 and/or 8, 17, 26, 35, 44, 53, 62, 71, 80, 89, 98

**9** =\> 09 and/or 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99

No standard loopholes, and it's , so the shortest answer in bytes wins.

> Congrats to Heeby Jeeby Man on his amazing 46 byte brain-flak answer!

# Answer
## Pyke, 6 bytes

```
ITV
9+

```

Try it here!

```
ITV\n9+ - if input: (don't print anything for 0 case)
 TV\n9+ -  repeat 10 times:
   \n   -    print ^
     9+ -   ^ += 9

```
> 5 votes

# Answer
## JavaScript (ES6), ~~27~~ ~~31~~ 30 bytes

Returns `0` for `0` or an array of solutions otherwise.

```
n=>n&&[...1e9+''].map(_=>n+=9)

```

### Demo

```
let f =

n=>n&&[...1e9+''].map(_=>n+=9)

for(n = 0; n < 10; n++) {
  console.log(n, JSON.stringify(f(n)));
}
```
> 10 votes

# Answer
# 05AB1E, ~~13~~ ~~12~~ 9 bytes

-3 bytes thanks to Adnan

```
тL<ʒSOSOQ

```

Try it online!

## Explanation

```
тL<ʒSOSOQ   Main link. Argument n
тL<         List from 1 to 100, then decrement to get 0 to 99
   ʒ        Filter
    SOSO    Sum of all chars, twice
        Q   Compare to input

```
> 8 votes

# Answer
# Jelly, 8 bytes

```
11Ḷ×9+ȧ@

```

Try it online!

Different algorithm than my other answer.
> 7 votes

# Answer
# Brain-Flak, 46 bytes

```
{((()()()()()){}){(({}[()])<(({}{}[]))>)}}{}{}

```

Try it online!

## Explanation

This answer uses an idea from Megatom's answer namely using the stack height as the difference between the loop counter and the increment. Like previous answers this answer has a large outer loop to catch all the zeros. Inside the loop we push 10 to act as a counter, we then start another nested loop. In this loop we decrement the counter by 1

```
({}[()])

```

Then we pop the top two items, which are the counter and the last item we calculated. We add these to the stack height in order to counter balance the decrementation, we then push this twice, once for output and once so that it can be consumed to calculate the next result. Pushing things twice means we accidentally push an additional value which needs to be removed at the end of execution.

The reason this just barely beats Megatom is Megatom's answer is forced to get its stack heights while the last result is still on the stack. This means they are forced to use a rather expensive `[()]` to decrease the total by one. By moving the duplicate to the end of the loop I am able to avoid having to use `[()]` at the cost of an additional `{}` at the very end of the program. If Megatom were to use this strategy his answer would look like:

```
{<>((()()()()()){}){((({}[()])<>{}[]))<>}}<>{}

```

also 46 bytes.

# Brain-Flak, 52 bytes

```
{((()()()()()){}){({}[()]<(({})((()()())){}{})>)}}{}

```

Try it online!

## Explanation

The main outerloop makes a special case for input of zero. If zero is input we jump over the entire loop, pop zero and then output nothing. Otherwise we enter the loop. Here we push loop 10 times each time adding 9 to the top of the stack, keeping old values. Since 9 preserves digital sums this will get us the next value. Once the loop has expired we use the zero it generated to exit the loop which is then popped by the `{}` at the end.

# Brain-Flak, 56 bytes

```
{([(((()()())){}{})]){({}()<(({})<(({}{}))>)>)}}{}({}{})

```

Try it online!

## Explanation

This version works very similarly to the last one, except we loop 9 times instead of 10 leaving out the original value. In order to do this we have to rearrange the way we handle memory a bit. All of the bytes we might have saved using this method get put into cleanup.
> 7 votes

# Answer
# Haskell, 21 bytes

`f` takes an integer and returns a list of integers.

```
f d=[d,d+9..99^0^0^d]

```

Try it online!

* Starts with the digit `d` and generates the range with every 9th number up to a bound of 99, *except* for the tricky case of `0`.
* To stop early for `0`, uses that the power `0^d==1` for `0` and `==0` for all other digits. Thus `99^0^0^d` gives `1` for `0` but `99` for anything else.
> 6 votes

# Answer
# Dyalog APL, 15 bytes

```
{(×⍵)/+\⍵,10⍴9}

```

**How?**

`⍵,10⍴9` \- concatenate input with 10 `9`s (`⍵ 9 9 9 9 9 9 9 9 9 9`).

`+\` \- cumulative sum.

`(×⍵)/` \- expand signum times - where signum gives 1 for 1-9 and 0 for 0.

Try it online!

### Dyalog APL, 24 bytes

```
{⍵/⍨⎕=(⍵≠0)×1+9|⍵-1}⍳100

```

Requires `⎕IO←0`.

**How?**

```
                      ⍳100  ⍝ 0 .. 99
              1+9|⍵-1      ⍝ digit sum (⍵-1 mod 9 + 1)
        (⍵≠0)×             ⍝ edge case for 0
     ⎕=                    ⍝ equals to the input
 ⍵/⍨                       ⍝ compress with the range

```
> 5 votes

# Answer
# Python 2, 29 bytes

```
lambda n:n and range(n,100,9)

```

Try it online!
> 5 votes

# Answer
# Brachylog, 12 bytes

```
0g|g{t+₉}ᵃ¹⁰

```

Try it online!

### Explanation

```
0g               Input = 0, Output = [0]
  |              Or
   g{   }ᵃ¹⁰     Accumulate 10 times, starting with [Input]
     t+₉         Take the last element, add 9

```
> 5 votes

# Answer
# Bash, ~~31~~ 27 bytes

```
seq $1 9 $(($1?99:0))|xargs

```

Try it online!

previous

```
eval echo {$1..$(($1?99:0))..9}

```
> 5 votes

# Answer
# Brain-Flak, 48 bytes

```
{<>((()()()()()){}){(({}[()])<>[][()]({}))<>}}<>

```

Try it online!

I may add an explanation later.
> 5 votes

# Answer
# Actually, 18 bytes

```
╗2╤DR⌠╜-9@%Y⌡░╜;)I

```

Try it online!

Explanation:

```
╗2╤DR⌠╜-9@%Y⌡░╜;)I
╗                   save input to register 0
 2╤DR               range(1, 100)
     ⌠╜-9@%Y⌡░      elements in range where function returns truthy:
      ╜-              subtract from input
        9@%           mod 9
           Y          is equal to 0
              ╜;)   push a copy of the input on the top and the bottom of the stack
                 I  if input is truthy, return the filtered range, else return the input (special-cases 0)

```
> 4 votes

# Answer
# Mathematica, 25 bytes

```
If[#==0,0,Range[#,99,9]]&

```

works for 0
> 4 votes

# Answer
# PHP, 41 Bytes

prints underscore separated values

```
for(;100>$a=&$argn;$a+=$a?9:ERA)echo$a._;

```

`ERA` is the shortest constant in PHP with the value `131116`. You can replace it with the boring alternative `100` or end the program with `die`

Online Version
> 4 votes

# Answer
# Jelly, 12 bytes

```
⁵²Ḷµ,³%9EµÐf

```

Try it online!

**How It Works**

```
⁵²Ḷµ,³%9EµÐf
⁵             - literal 10
 ²            - square
  R           - lowered range: 0 to 99 inclusive.
   µ     µÐf  - filter based on:
    ,³          - element and input
      %9        - mod 9
        E       - are equal

```
> 4 votes

# Answer
# Brain-Flak, ~~54~~ 52 bytes

```
{<>((((()()())){}{})()){({}<(({})<>({}))><>[()])}}<>

```

Try it online!

My first foray with Brain-Flak, and I think I've done pretty well. Anyone with more experience have advice?

### How It Works:

```
{ Don't do anything if input is 0
  <>((((()()())){}{})()) Switch to other stack and add 9 and 10
                         10 is the counter, 9 is to add to the current num
  { While counter
     (
       {} Pop the counter
       <(({})<>({}))> Get a copy of the 9, switch to the other stack and add it to a copy of the top of it. Use <...> to make it return 0
       <>[()] Switch to the other stack and decrement the counter
     )
  }
}<> Switch to the stack with the values on it

```
> 4 votes

# Answer
# Python, ~~48~~ 51 bytes

*3 bytes saved thanks to @WheatWizard*

```
lambda n:[x for x in range(100)if~-n==~-x%9or x==n]

```
> 3 votes

# Answer
# Jelly, 12 bytes

```
ȷ2ḶDS$ÐL⁼¥Ðf

```

Try it online!
> 3 votes

# Answer
# PHP, 35

```
print_r(range($argn,!!$argn*99,9));

```

Creates the range `[$argn, 100)` with a step of `9` as array and prints it. If the input is `0` it creates the range `[0,0]` =\> `array(0)`.
> 3 votes

# Answer
# , 23 bytes

```
pryr::f(x+0:(10*!!x)*9)

```

Try it online!

The TIO link uses `function(x)` instead of `pryr::f`, since TIO doesn't have the `pryr` package installed.
> 2 votes

# Answer
## Pyke, 6 bytes (old version)

Working commit

```
TXU#sq

```

Explanation:

```
TX     -   10**2
  U    -  range(^)
   #   - filter(^)
    s  -   digital_root(^)
     q -  ^==input

```
> 2 votes

# Answer
# Ruby, 25 bytes

```
->a{[*a.step(99,9)]*a|[]}

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~14~~ 11 bytes

```
Ｉ∧Ｎ⁺Ｉθ×⁹…¹¹

```

Try it online! Link is to verbose version of code. Edit: Saved ~~2 bytes by not printing anything for zero input and 1 byte by using vectorising operations~~ 3 bytes thanks to @ASCII-only. Explanation:

```
         ¹¹ Literal 11
        …   Range
       ⁹    Literal 9
      ×     Vector multiply
     θ      (First) input
    Ｉ       Cast to number
   ⁺        Vector add
  Ｎ         Input digit as a number
 ∧          Logical AND
Ｉ           Cast to string
            Implicitly print on separate lines

```
> 2 votes

# Answer
# C (gcc), 55 bytes

`f()` need not actually be called with any argument; the `n` is just there instead of outside the function to save a byte.

```
f(n){for(scanf("%d",&n);n&&n<100;n+=9)printf("%d ",n);}

```

Try it online!
> 2 votes

# Answer
# Pyt, 11 bytes

```
?56+ř⁻9*+:;

```

Try it online!

```
?               implicit input; if input is truthy:
 56+            push 11
    ř⁻          řangify; decrement
      9*        multiply by 9
        +       add input
         :;     otherwise, do nothing; implicit print

```
> 2 votes

# Answer
# Vyxal `H`, 6 bytes

```
ʁ'∑∑?=

```

Try it Online!

Port of kalsowerus's 05AB1E answer.

A port of Kip the Malamute's Pyt answer would be **8 bytes**:

```
:[11ʁ9*+

```

Try it Online!

#### Explanation

```
ʁ'∑∑?=  # H flag pushes 100
ʁ'      # Filter range(100) by:
  ∑∑    #  Digit sum twice
    ?=  #  Equals the input

```

```
:[11ʁ9*+  # Implicit input
:         # Duplicate
 [        # If input is not 0:
  11ʁ     #  Push range(11)
     9*   #  Multiply by 9
       +  #  Add to input
          # (Otherwise, do nothing)

```
> 2 votes

# Answer
# Julia 0.6, 18 bytes

I use a ternary to catch the `0` case, and a range `n:9:99` to create the numbers. In julia a range is an `AbstractVector` and can be used in place of an actual `Vector` of numbers in most cases, but it will just print as `1:9:91` which doesn't satisfy the challenge, so I wrap it in `[_;]` to collect the contents into a `Vector`.

```
n->n>0?[n:9:99;]:0

```

Try it online!
> 1 votes

# Answer
# Perl 5, 25 + 1 (`-n`) = 26 bytes

```
say;!$_||($_+=9)>99||redo

```

Try it online!
> 1 votes

# Answer
**Clojure, 33 bytes**

```
(fn[n](if(> n 0)(range n 100 9)))

```
> 1 votes

# Answer
# Clojure, 38 bytes

```
(defn f[n](if(pos? n)(range n 100 9)))

```

or as anonymous function which is 29 bytes

```
(#(if(pos? %)(range % 100 9))n)

```

Try it online!

thanks @steadybox
> 1 votes

# Answer
# Thunno `D`, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
?11R9*+

```

Attempt This Online!

Port of Kip the Malamute's Pyt answer.

## Thunno `H`, \\$ 8 \log\_{256}(96) \approx \\$ 6.58 bytes

```
gdSdSA$=

```

Attempt This Online!

Port of kalsowerus's 05AB1E answer.

#### Explanations

```
?11R9*+  # D flag duplicates input
?        # If input is not 0:
 11R     #  Push range(11)
    9*   #  Multiply by 9
      +  #  Add to input
         # (Otherwise, do nothing)

```

```
gdSdSA$=  # H flag pushes 100
g         # Filter range(100) by:
 dSdS     #  Digit sum twice
     A$=  #  Equals the input

```
> 1 votes

# Answer
# Perl 5, 62 bytes

```
sub x{$f=$_[0];@x=("0$f",$f);push@x,map$f+$_*10,(1..9)if$f;@x}

```

There's bound to be a shorter way
> 0 votes

# Answer
# Gol\>\<\>, 12 bytes

```
I:ZhbF:N9+|;

```

Try it online!

### How it works

```
I:ZhbF:N9+|;

I             Take input as number
 :            Duplicate
  Z           Pop and skip one if nonzero
   h          If zero, print the top as number and halt
              Otherwise...
    bF....|   Repeat these commands 11 times
      :N      Print top as number, with newline
        9+    Add 9
           ;  Halt

```
> 0 votes

---
Tags: code-golf, math, number, kolmogorov-complexity, arithmetic
---


title: Normalize a Vector

text:
# Question
Title: Normalize a Vector
To *normalize* a vector is to scale it to a length of 1 (a unit vector), whilst keeping the direction consistent.

For example, if we wanted to normalize a vector with 3 components, **u**, we would first find its length:

> **|u| = sqrt(ux2 \+ uy2 \+ uz2)**

...and then scale each component by this value to get a length 1 vector.

> **û = u ÷ |u|**

---

# The Challenge

Your task is to write a program or function which, given a non-empty list of signed integers, interprets it as a vector, and normalizes it. This should work for any number of dimensions, for example (test cases rounded to two decimal places):

```
[20]           -> [1]
[-5]           -> [-1]
[-3, 0]        -> [-1, 0]
[5.5, 6, -3.5] -> [0.62, 0.68, -0.40]
[3, 4, -5, -6] -> [0.32, 0.43, -0.54, -0.65]
[0, 0, 5, 0]   -> [0, 0, 1, 0]

```

**Rules:**

* You can assume the input list will:
    + Have at least one non-zero element
    + Only contain numbers within your language's standard floating point range
* Your output should be accurate to *at least* **two decimal places**. Returning "infinite precision" fractions / symbolic values is also allowed, if this is how your language internally stores the data.
* Submissions should be either a full program which performs I/O, or a function. Function submissions can either return a new list, or modify the given list in place.
* Builtin vector functions/classes are allowed. Additionally, if your language has a vector type which supports an arbitrary number of dimensions, you can take one of these as input.

This is a contest, so you should aim to achieve the shortest solution possible (in bytes).

# Answer
# 05AB1E, 4 bytes

### Code:

```
nOt/

```

Try it online!

### Explanation

```
n     # Square each element of the input
 O    # Sum all elements
  t   # Take the square root of the sum
   /  # Divide each element by the square root of the sum

```
> 15 votes

# Answer
# JavaScript (ES6), 31 bytes

```
a=>a.map(n=>n/Math.hypot(...a))

```

### Test cases

```
let f =

a=>a.map(n=>n/Math.hypot(...a))

console.log(JSON.stringify(f([20]          ))) // -> [1]
console.log(JSON.stringify(f([-5]          ))) // -> [-1]
console.log(JSON.stringify(f([-3, 0]       ))) // -> [-1, 0]
console.log(JSON.stringify(f([5.5, 6, -3.5]))) // -> [0.62, 0.68, -0.40]
console.log(JSON.stringify(f([3, 4, -5, -6]))) // -> [0.32, 0.43, -0.54, -0.65]
console.log(JSON.stringify(f([0, 0, 5, 0]  ))) // -> [0, 0, 1, 0]
```
> 10 votes

# Answer
# Mathematica, 9 bytes

```
Normalize

```

Try it online!
> 10 votes

# Answer
# , 8 bytes

```
%+/&.:*:

```

Try it online!

6 bytes `%|@j./` works if the vector is at least 2-dimensional.
> 9 votes

# Answer
# Jelly, ~~5~~ 3 bytes

```
÷ÆḊ

```

Try it online!, or see the test suite

Saved 2 bytes thanks to miles!
> 8 votes

# Answer
# Octave, 13 bytes

```
@(x)x/norm(x)

```

Try it online!
> 6 votes

# Answer
# C,  ~~73~~  70 bytes

*Thanks to @Christoph for saving a byte!*

```
s,i;f(v,n)float*v;{for(s=0;i++<n;)s+=*v**v++;for(;--i;)*--v/=sqrt(s);}

```

Try it online!
> 6 votes

# Answer
# Python, ~~47~~ 46 bytes

```
lambda v:[e/sum(e*e for e in v)**.5for e in v]

```

Try it online!
> 4 votes

# Answer
# Julia, 9 bytes

```
normalize

```

Try it online!
> 4 votes

# Answer
## CJam, 9 bytes

```
{_:mhzf/}

```

Try it online!

### Explanation

```
_    e# Duplicate input.
:mh  e# Fold hypothenuse-length over the vector. This gives the norm, unless the vector
     e# has only one component, in which case it just gives that component.
z    e# Abs. For the case of a single negative vector component.
f/   e# Divide each vector component by the norm.

```
> 3 votes

# Answer
# TI-Basic, 6 bytes

```
Ans/√(sum(Ans<sup>2</sup>
```

Run with `{1,2,3}:prgmNAME`, where `{1,2,3}` is the vector to be normalized.

Divides each element in the vector by the square root of the sum of the squares of its elements.
> 3 votes

# Answer
# , 23 bytes

```
function(v)v/(v%*%v)^.5

```

Try it online!

`v%*%v` computes the dot product of v with itself.
The function will issue a warning for length 2 or greater vectors.
> 3 votes

# Answer
# Java (OpenJDK 8), 57 bytes

```
v->v.stream().map(x->x/v.stream().reduce(0d,Math::hypot))

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog), ~~13~~ ~~12~~ 10 bytes

*1 byte saved thanks to @Adám*

*2 bytes saved thanks to @ngn*

```
⊢÷.5*⍨+.×⍨

```

Try it online!

**How?**

```
⊢  ÷  .5*⍨  +.  ×⍨
u  ÷    √   Σ   u²

```
> 2 votes

# Answer
# MATL, 5 bytes

```
t2&|/

```

Try it online!

I'm not entirely sure this is the shortest way to do this. First, we duplicate the input, then select the second output type of `|` (which is either `abs`, `norm` or `determinant`). Finally, we divide the input by the norm.

Alternative for 7 bytes:

```
t2^sX^/

```
> 2 votes

# Answer
# Haskell, 29 bytes

```
f x=map(/sqrt(sum$(^2)<$>x))x

```

Try it online!

Or for 1 byte more pointfree: `map=<<flip(/).sqrt.sum.map(^2)`
> 2 votes

# Answer
# Funky, 42 bytes

```
a=>(d=a::map)(c=>c/d(b=>b^2)::reduce@+^.5)

```

Try it online!
> 2 votes

# Answer
# C++ (gcc), 70 bytes

Input by `std::valarray<float>`. Overwrites the original vector.

```
#import<valarray>
int f(std::valarray<float>&a){a/=sqrt((a*a).sum());}

```

Try it online!
> 2 votes

# Answer
# Ohm v2, 5 bytes

```
D²Σ¬/

```

Try it online!
> 2 votes

# Answer
# Common Lisp, 69 bytes

```
(lambda(v)(mapcar(lambda(x)(/ x(sqrt(loop as y in v sum(* y y)))))v))

```

Try it online!
> 2 votes

# Answer
# Vyxal, 4 bytes

```
²∑√/

```

Try it Online!

```
²    # Square each
 ∑   # Sum
  √  # Square root
   / # Divide by that

```
> 2 votes

# Answer
# Husk, ~~8~~ 7 bytes

```
´(Ṁ/√ṁ□

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~39~~ 35 bytes

```
->v{v.map{|x|x/v.sum{|x|x*x}**0.5}}

```

-4 bytes thanks to G B.
> 1 votes

# Answer
# C# (.NET Core), 51+64=115 bytes

```
v=>v.Select(d=>d/Math.Sqrt(v.Select(x=>x*x).Sum()))

```

Try it online!

+64 bytes for the `using System;using System.Collections.Generic;using System.Linq;`

# C# (.NET Core), 94+13=107 bytes

```
v=>{var m=0d;foreach(var x in v)m+=x*x;for(int i=0;i<v.Length;)v[i++]/=Math.Sqrt(m);return v;}

```

Try it online!

+13 bytes for `using System;`

The non-Linq approach

### DeGolfed

```
v=>{
    var m=0d;
    foreach (var x in v)
        m+=x*x;

    for (int i=0; i < v.Length;)
        v[i++] /= Math.Sqrt(m);

    return v;
}

```
> 1 votes

# Answer
# Perl 5, 45 + 1 (`-a`) = 46 bytes

```
say$_/sqrt eval join'+',map"($_)**2",@F for@F

```

Try it online!
> 1 votes

# Answer
# Pip, 10 bytes

9 bytes of code, +1 for `-p` flag.

```
g/RT$+g*g

```

Takes the vector as separate command-line arguments. Try it online!

### How it works

```
      g*g  Arglist, multiplied by itself itemwise
    $+     Sum
  RT       Square root
g/         Divide arglist itemwise by that scalar
           Result is autoprinted (-p flag to format as list)

```
> 1 votes

# Answer
# Pyth, 5 bytes

```
cR.aQ

```

Try it online: Test Suite

### Explanation:

```
cR.aQQ   implicit Q at the end
c        divide
 R   Q   each element of the input
  .aQ    by the L2 norm of the input vector

```
> 1 votes

# Answer
# Perl 6, 25 bytes

```
{$_ »/»sqrt sum $_»²}

```

Try it online!

`$_`, the list argument to the function, is divided elementwise (`»/»`) by the square root of the sum of the squares of the elements (`»²`).
> 1 votes

# Answer
# Coconut, 40 bytes

```
x->map((/)$(?,sum(map(t->t*t,x))**.5),x)

```

I have no idea what I'm doing...

Try it online!
> 1 votes

# Answer
# Thunno `D`, \\$ 5 \log\_{256}(96) \approx \\$ 4.12 bytes

```
2^St/

```

Attempt This Online!

#### Explanation

```
2^St/  # D flag duplicates the input
2^     # Square each
  S    # Sum this list
   t   # Push the square root
    /  # Divide the input by this number

```
> 1 votes

# Answer
# Pyt, 5 bytes

```
Đ²Ʃ√/

```

Try it online!

#### Explanation

```
Đ²Ʃ√/     implicit input
Đ²        duplicate and square
  Ʃ       sum
   √      square root
    /     divide

```
> 1 votes

# Answer
# APL NARS 12 Characters

```
f←{⍵÷√+/⍵*2}

```
> 0 votes

# Answer
# Add++, 38 bytes

```
L?!*,EL2@xa@pBcB`s0.5^VcALG$xVcGa@BcB/

```

Try it online!
> 0 votes

# Answer
# Google Sheets, 65 bytes

```
=ArrayFormula(TextJoin(",",1,If(A:A="","",A:A/Sqrt(Sumsq(A:A)))))

```

The input list is in column `A` with one entry per cell. This is how spreadsheets would normally use lists. Unfortunately, this would normally result in a long list of `,0,0,0,0,0,....` at the end so we have to ignore those with the `If Blank then Blank else Math` logic.

If it was all in one cell, instead, the solution would be 95 bytes:

```
=ArrayFormula(TextJoin(",",1,If(Split(A1,",")="","",Split(A1,",")/Sqrt(Sumsq(Split(A1,","))))))

```
> 0 votes

# Answer
# Japt, 6 bytes

```
®/Ux²q

```

Try it here

---

## Explanation

Map over the input array (`®`), divide (`/`) the current element by the square root (`q`) of the sum (`x`) of the elements in the input (`U`) squared (`²`).
> 0 votes

# Answer
# Swift 4, 44 bytes

```
{a in a.map{$0/sqrt(a.reduce(0){$0+$1*$1})}}

```

Recalculates the vector norm for every component, but at least it's terse!
> 0 votes

# Answer
## Clojure, 47 bytes

```
#(for[i %](/ i(Math/sqrt(apply +(map * % %)))))

```

This version calculates the norm only once and should look a bit more obscure for non-clojurists (`%` is the input argument):

```
#(map / %(repeat(Math/sqrt(apply +(map * % %)))))

```
> 0 votes

# Answer
# Excel VBA, 25 Bytes

Anonymous VBE immediate window function that takes a number vector input from range `[1:1]` and outputs the normalized vector to the same range

```
[1:1]=[1:1/SumSQ(1:1)^.5]

```
> 0 votes

---
Tags: code-golf, math, array, geometry
---


# Question
Title: Shortest code to generate all Pythagorean triples up to a given limit
Generate the shortest possible code in any programming language that can generate all Pythagorean triples with all values not exceeding a given integer limit. A Pythagorean triple is a set of three integers \\$(a, b, c)\\$ that satisfy the equation \\$a^2 + b^2 = c^2\\$. The program should output the triples in any format, such as a list of tuples or a newline-separated list of strings.

Input: An integer limit \\$n\\$ (1 ≤ \\$n\\$\\$10^6\\$)

Output: All Pythagorean triples \\$(a, b, c)\\$ such that \\$1 ≤ a, b, c ≤ n\\$ and \\$a^2 + b^2 = c^2\\$.

## Test Cases

```
Input: 20
Output:
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(8, 15, 17)
(9, 12, 15)
(12, 16, 20)

```

```
Input: 5
Output:
(3, 4, 5)

```

Note: The output order does not matter as long as all the correct Pythagorean triples are included. Duplicate triples should not be included. But, specifying the order might help.

# Answer
> 6 votes
# Vyxal, ~~9~~ 8 bytes

```
ɾ3ḋ'²÷ε=

```

Try it Online!

I'm surprised I didn't manage to make this horribly inefficient.

*-1 thanks to Kevin!*

## Explained

```
ɾ3ḋ'²÷ε=
ɾ          # Range [1, input]
 3ḋ        # Combinations of length 3
   '       # filtered by:
    ²      #   squaring everything
     ÷     #   dumping the triplet onto the stack in reverse order
      ε    #   absolute difference of b**2 and c**2
       =   #   equals a**2

```

# Answer
> 6 votes
# 05AB1E, 9 bytes

```
L3.Æʒn`αQ

```

Try it online or verify all test cases.

The last three bytes could alternatively be `RÆ_` for the same byte-count:

Try it online or verify all test cases.

**Explanation:**

```
L         # Push a list in the range [1, (implicit) input-integer]
 3.Æ      # Create all triplet-combinations of this list
    ʒ     # Filter this list of [a,b,c]-triplets by:
     n    #  Square each inner integer in the triplet
      `   #  Push all three values separated to the stack
       α  #  Get the absolute difference of the top two: |b²-c²|
        Q #  Check if it's equal to the third one: a² == |b²-c²|
          # (after which the filtered list of triplets is output implicitly as result)

      R   #  Reverse the triplet to [c²,b²,a²]
       Æ  #  Reduce it by subtracting: c²-b²-a²
        _ #  Check if this is 0

```

# Answer
> 5 votes
# Factor \+ `math.combinatorics`, 57 bytes

```
[ [1,b] 3 [ 2 v^n first3 -rot + = ] filter-combinations ]

```

Try it online!

* `[1,b] 3 [ ... ] filter-combinations` select combinations of three from \\$\[1..n\]\\$ where...
* `2 v^n` square the elements of the triplet
* `first3` place each element onto the stack
* `-rot` move \\$c^2\\$ from the top of the stack to the bottom
* `+` add \\$a^2\\$ and \\$b^2\\$
* `=` equal?

# Answer
> 4 votes
# Thunno, \\$13\log\_{256}(96)\approx\\$ 10.70 bytes

```
R1+3zQg2^Au_=

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
R1+3zQg2^Au_=  # Implicit input
R1+            # Push range(1, input+1)
   3zQ         # Combinations with length 3
      g        # Filter by:                     STACK: [a, b, c]
       2^      #  Square each                   STACK: [a**2, b**2, c**2]
         Au    #  Dump onto stack               STACK: a**2, b**2, c**2
           _   #  Subtract top two              STACK: a**2, c**2 - b**2
            =  #  Are they equal?               STACK: a**2 == c**2 - b**2
               # Implicit output

```

# Answer
> 4 votes
# Noether, 62 bytes

```
!aI~n(!a~bn1+({a2^!b2^+0.5^~cn<cn=|cc_=&}{aP","PbP","PcP?}b)a)

```

Try it in your browser!

Surprisingly this is the first time I've realised the severe lack of \\$\leq\\$ and \\$\geq\\$ operators in the language.

**Explanation:**

```
!a                                                             # Initialiase variable a to 1
  I~n                                                          # Store user input in n: outer loop exit condition
     (                                                       ) # Outer loop
      !a~b                                                     # Increment a and store value in b
          n1+                                                  # Add 1 to n: inner loop exit condition
             (                                             )   # Inner loop
              {                         }{               }     # If ... Else
               a2^                                             # Square a
                  !b2^                                         # Increment value of b and square
                      +0.5^                                    # Sum a and b and square root
                           ~cn<                                # Store value in c and check if less than n
                               cn=                             # c == n
                                  |                            # Bitwise OR
                                   cc_=                        # c == floor(c)
                                       &                       # Bitwise AND
                                          aP","PbP","PcP?      # If true, output variable values, comma separated
                                                          b    # Push b to stack (inner loop exit condition)
                                                            a  # Push a to stack (outer loop exit condition)

```

# Answer
> 3 votes
# Japt, 14 bytes

```
õ à3 fÈÌ²Ñ¶Xx²

```

Try it

```
õ à3 fÈÌ²Ñ¶Xx²     :Implicit input of integer U
õ                  :Range [1,U]
  à3               :Combinations of length 3
     f             :Filter by
      È            :Passing each X through the following function
       Ì           :  Last element
        ²          :  Square
         Ñ         :  Multiply by 2
          ¶        :  Is equal to
           Xx      :  X reduced by addition
             ²     :  After squaring each

```

# Answer
> 3 votes
# \>\<\> (Fish), 111 bytes

```
i:*&43::*{:}:*+\
/*::<5[1;?)&:&:/
\:{:}(?!v~1+31.
/]v?)}:{/|.!051+1~\
n \]~~>1+$:@$:@= ?^50.
\' 'o}:n' 'o}:nao$~$64.

```

Try it

## Explanation

`><>` lacks a square root function so this simply tries all numbers until it finds one greater than the square of the inputs.

First, we square the input. We start searching at a,b=4,3. We check if \\$a^2\\$, (`::*`) + \\$b^2\\$ is more than the input squared, if so we exit.

Then we push 5, the starting third value. Square it, if it is more than a^2+b^2, go to the next iteration. Otherwise, add 1 to C.

If A^2+B^2=C^2, print A, B, and C, then go to next.

When we go to the next iteration, add 1 to B. If B\>A, add 1 to A instead and reset B to 1. This is `1+$:@$:@=?~1+1`. Then we jump back to the start to try another iteration.

# Answer
> 3 votes
# JavaScript (V8), 63 bytes

```
n=>{for(;p=n;n--)while(--p>(q=(n*n-p*p)**.5))q%1||print(q,p,n)}

```

Try it online!

### Commented

```
n => {                  // n = input
  for(                  // outer loop:
    ;                   //
    p = n;              //   before each iteration, initialize p to n
                        //   stop when n = 0
    n--                 //   decrement n after each iteration
  )                     //
    while(              //   inner loop:
      --p > (           //     decrement p and test whether it's greater
        q =             //     than q defined as:
        (n * n - p * p) //       the square root of the difference
        ** .5           //       between n² and p²
      )                 //     stop as soon as the test fails
    )                   //
      q % 1 ||          //     if q is an integer:
        print(q, p, n)  //       print the triplet (q, p, n)
}                       //

```

# Answer
> 3 votes
# JavaScript, 81 bytes

```
n=>{for(a=0;++a<n;)for(b=a;b<n;++b)(c=(a*a+b*b)**.5)%1||c<=n&&console.log(a,b,c)}

```

Try it:

```
f=n=>{for(a=0;++a<n;)for(b=a;b<n;++b)(c=(a*a+b*b)**.5)%1||c<=n&&console.log(a,b,c)}

;[
  1,
  3,
  5,
  7,
  10,
  17,
  20
].forEach(n=>{console.log(n+':');f(n)})
```

# Answer
> 3 votes
## Scala, 71 bytes

```
(n:Int)=>for{c<-5 to n;b<-4 to c;a<-3 to b if a*a+b*b==c*c}yield(a,b,c)

```

or styled differently:

```
(n:Int)=>for{c<-5 to n
b<-4 to c
a<-3 to b
if a*a+b*b==c*c}yield(a,b,c)

```

It's not often that Scala gets a chance to do well in golfing, but the `.to()` method is perfect for inclusive ranges.

Try it online or on Scastie!

# Answer
> 2 votes
# Arturo, 50 bytes

```
$=>[select combine.by:3@1..&'x[=+x\0^2x\1^2x\2^2]]

```

Try it

```
$=>[                      ; an anonymous function
    select                ; select elements from a block
    combine.by:3 @1..&    ; combinations of 3 from the range 1 to n
    'x                    ; assign current triplet to x in the select
    [                     ; begin select
        =+x\0^2x\1^2x\2^2 ; is a^2+b^2 equal to c^2?
    ]                     ; end select
]                         ; end function

```

# Answer
> 2 votes
# Python, ~~91~~ 88 bytes

```
lambda n,r=range:[(k,j,i)for i in r(1,n+1)for j in r(1,i)for k in r(1,j)if i*i==j*j+k*k]

```

Attempt This Online!

# Answer
> 2 votes
# Nekomata, 12 bytes

```
RS3Lᵖ{:*Ɔ$∑=

```

Attempt This Online!

A port of @Fatalize's Brachylog answer.

```
RS3Lᵖ{:*Ɔ$∑=
R               Range from 1 to the input
 S              Subset
  3L            Length should be 3
    ᵖ{          Start a block; treat the block as a predicate,
                  and return the original value if the block does not fail
      :*        Multiply by itself
        Ɔ$∑=    The last element should equals to the sum of the other elements

```

By default, the Nekomata interpreter will print all possible results.

# Answer
> 1 votes
# Charcoal, 26 bytes

```
ＩΣΣＥ⊕ＮＥιＥΦλ⁼×ιι⁺×λλ×νν⟦νλι

```

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

```
     Ｎ                      Input integer
    ⊕                       Incremented
   Ｅ                        Map over implicit range
       ι                    Current value
      Ｅ                     Map over implicit range
          λ                 Current value
         Φ                  Filter over implicit range
            ×ιι             Square of outer value
           ⁼                Equals
                ×λλ         Square of inner value
               ⁺            Plus
                   ×νν      Square of innermost value
        Ｅ                   Map over matches
                      ⟦     List of
                       ν    Innermost value
                        λ   Inner value
                         ι  Outer value
  Σ                         Flatten
 Σ                          Flatten
Ｉ                           Cast to string
                            Implicitly print

```

# Answer
> 1 votes
# Python 3, ~~112~~ 104 bytes

```
lambda n,r=range:{(*sorted((i,j,k)),)for i in r(1,n+1)for j in r(1,n+1)for k in r(1,n+1)if i*i+j*j==k*k}

```

Literally the same thing as the other answers.

# Answer
> 1 votes
# MathGolf, 21 bytes

```
╒■■mÅ─╡gæ_▀s=gÆ²xε-┬▀

```

Try it online.

**Explanation:**

```
╒         # Push a list in the range [1, (implicit) input-integer]
 ■        # Get the cartesian product with itself to create pairs
  ■       # Get the cartesian product with itself to create pairs of pairs
   m      # Map over each pair of pairs,
    Å     # using 2 characters as inner code-block:
     ─    #  Flatten the pair to a quadruplet
      ╡   #  Discard the last item to make it a triplet
 g        # Filter this list of triplets by,
  æ       # using 4 characters as inner code-block:
   _      #  Duplicate the current list
    ▀     #  Uniquify the values in the copy
     s    #  Sort it from lowest to highest
      =   #  Check if the two lists are still the same
 g        # Filter this list further by,
  Æ       # using 5 characters as inner code-block:
   ²      #  Square each integer in the triplet
    x     #  Reverse it
     ε    #  Reduce the triplet by:
      -   #   Subtracting
       ┬  #  Check if the result of this c²-b²-a² equals 0
 ▀        # After the filter: uniquify the remaining list of triplets
          # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# Pyth, 14 bytes

```
f!-F^R2_T.CSQ3

```

Try it online!

### Explanation

```
                  # implicitly assign Q = eval(input())
         .C  3    # all sorted lists of three elements from
           SQ     # range(1,Q+1)
f                 # filter these lists on lambda T
       _T         #   reverse T
    ^R2           #   map elements to their squares
  -F              #   fold on subtraction (subtract all elements from the first)
 !                #   not (only true for zero)

```

# Answer
> 1 votes
# Befunge-93 (PyFunge), 125 bytes

```
v
&
>35g:*25g:*+15g:*-|
  ,*52.g51.g52.g53<v
^p53+1_v#`\g52:g53<<
^111   >$135p25g:1 5g\`!#v_1+25p
^ p51+1_@#`g51\g51 :p521$<

```

Try it online!

Note: The three "1"s shown here on line 6 ((1,5),(2,5) and (3,5) in Funge-Space) are actually be U+0001 in the source code. This is reflected correctly in TIO.

I may be able to save some bytes by moving those storage characters to line 1 or 2, and send line 6 left and wrap it, and if I can find a way to reduce the number of "g"s required to get the incremented values.

I'll do a nice writeup for this when I have time.

# Answer
> 1 votes
# Python, 98 bytes

Two solutions already exist for Python, but this one uses a slightly different approach that I thought might be informative:

```
from itertools import *
lambda n:[(k,j,i)for(k,j,i)in combinations(range(0,n+1),3)if i*i==j*j+k*k]

```

# Answer
> 1 votes
# Brachylog, 13 bytes

```
⟦₁⊇Ṫ.^₂ᵐṅᵗ+0∧

```

Try it online!

### Explanation

This is a generator, which will unify with each triplet.

```
⟦₁                 Range [1, …, N]
  ⊇Ṫ.              Subset of 3 elements
     .^₂ᵐ          Square each element
         ṅᵗ        Negate the last one (which is the biggest)
           +0∧    The sum must be 0

```

### Much faster, 19 bytes

```
≥~hṪ≥₁ℕ₁ᵐ^₂ᵐṅʰ+0∧Ṫ≜

```

Try it online!

Takes about 1.5s for N = 200 on TIO. This uses integer constraint programming mechanisms which is way more efficient than brute forcing combinations in a range, but is longer to express in this case.

```
≥~hṪ                 A triplet of elements whose head is smaller than N
    ≥₁               The triplet is non-increasing
      ℕ₁ᵐ            Each element is in [1, +inf)
         ^₂ᵐ         Map square
            ṅʰ       Negate the first element
              +0∧    The sum must be 0
                 Ṫ≜  Assign values to satisfy these constraints

```

# Answer
> 1 votes
# C (gcc), 113 + 7 bytes

Compiled with `-lm -DM=<input>`

```
r,s,t;main(){for(;s<M;)for(t=++s;(r=sqrt(2*s*++t))<M;)r-sqrt(2*s*t)||(r+=s+t)>M||printf("%d %d %d\n",r-t,r-s,r);}

```

Try it online!

# Answer
> 0 votes
# jq, ~~85~~ 78 bytes

```
[range(3;.)]|combinations(3)|select(map(pow(.;2))|.[0]==.[1]+.[2]and.[1]>.[2])

```

~~Try it online!~~  Try it online!

Generates all triples, then filters.

# Answer
> 0 votes
# JavaScript 72 bytes

```
c=>{for(a=b=c;c;--a||(a=--b)||(a=b=--c))c*c-b*b-a*a||console.log(c,b,a)}

```

Formatted:

```
c => {
  for( a=b=c; c; /* until c is 0 */
     /* count down a, when a==0 reduce b and reset a=b, the same with c */
      --a || (a = --b) || (a = b = --c)
    )
    /* if c²-b²-a² == 0 log the tuple */
    c*c - b*b - a*a || console.log(c,b,a)
}

```

Try it online

# Answer
> 0 votes
# Haskell, 56 bytes

```
q l=[(a,b,c)|c<-[1..l],a<-[1..c],b<-[a..l],a^2+b^2==c^2]

```

Try it online!

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


# Question
Title: Smallest integers after N divisible by 2, 3, and 4
Give credit to whom credit is due.

**Objective** Given an integer `N > 0`, out the smallest integers `A`, `B`, and `C` so that:

1. All of `A`, `B`, and `C` are strictly greater than `N`;
2. `2` divides `A`;
3. `3` divides `B`;
4. and `4` divides `C`.

This is a code-golf, so the shortest answer in bytes wins.

## Test cases

```
N => A, B, C
1 => 2, 3, 4
4 => 6, 6, 8
43 => 44, 45, 44
123 => 124, 126, 124
420 => 422, 423, 424
31415 => 31416, 31416, 31416
1081177 => 1081178, 1081179, 1081180

```

# Answer
# Jelly, 8 bytes

```
~%2r4¤+‘

```

Try it online! or verify all test cases.

### How it works

```
~%2r4¤+‘  Main link. Argument: n (integer)

~         Bitwise NOT; yield ~n = -(n + 1).
     ¤    Combine the three links to the left into a niladic chain:
  2         Yield 2.
   r4       Yield the range from 2 to 4, i.e., [2, 3, 4].
 %        Yield the remainder of the division of ~n by 2, 3 and 4.
          In Python/Jelly, -(n + 1) % k = k - (n + 1) % k if n, k > 0.
       ‘  Yield n + 1.
      +   Add each modulus to n + 1.

```
> 17 votes

# Answer
## Python 2, 32 bytes

```
lambda n:[n+2&-2,n/3*3+3,n+4&-4]

```

Bit arithmetic for 2 and 4, modular arithmetic for 3.

I found four 7-byte expressions for the next multiple of `k` above `n` but none shorter:

```
n-n%k+k
~n%k-~n
n/k*k+k
~n/k*-k

```

Any gives 34 bytes when copies for `k=2,3,4`, and 33 bytes if combined:

```
[n/2*2+2,n/3*3+3,n/4*4+4]
[n/k*k+k for k in 2,3,4]

```

But, 2 and 4 are powers of 2 that allow bit tricks to zero out the last 1 or 2 bytes.

```
n+2&-2
n+4&-4

```

This gives 6 bytes (instead of 7) for getting the next multiple, for 32 bytes overall, beating the `for k in 2,3,4`.

Unfortunately, the promising-looking `n|1+1` and `n|3+1` have the addition done first, so incrementing the output takes parentheses.
> 26 votes

# Answer
# Julia, 16 bytes

```
n->n-n%(r=2:4)+r

```

Try it online!
> 14 votes

# Answer
# MATL, ~~15 10~~ 9 bytes

```
2:4+t5M\-

```

Try it online!

Explanation:

```
2:4          #The array [2, 3, 4]
   +         #Add the input to each element, giving us [12, 13, 14]
    t        #Duplicate this array
     5M      #[2, 3, 4] again
       \     #Modulus on each element, giving us [0, 1, 2]
        -    #Subtract each element, giving us [12, 12, 12]

```
> 12 votes

# Answer
# MATL, 8 bytes

```
Qt_2:4\+

```

Uses Denis' Jelly algorithm, I'm surprised it's the same length!

Try it online, or, verify all test cases.

```
Q    % takes implicit input and increments by one
t_   % duplicate, and negate top of stack (so it's -(n+1))
2:4  % push vector [2 3 4]
\    % mod(-(n+1),[2 3 4])
+    % add result to input+1
     % implicit display

```
> 12 votes

# Answer
# Matlab, 33 bytes

Another slightly different approach

```
@(a)feval(@(x)a+1+mod(-a-1,x),2:4)

```
> 6 votes

# Answer
# 05AB1E, 8 bytes

Code:

```
>D(3L>%+

```

Try it online!.
> 6 votes

# Answer
# Ruby, 27 bytes

Maps 2, 3, and 4 to the next multiple above `n`.

```
->n{(2..4).map{|e|n+e-n%e}}

```
> 5 votes

# Answer
## Pyth, ~~11~~ 10 bytes

```
m*dh/QdtS4

```

Test suite.

```
       tS4  generate range [2, 3, 4]
m           for d in range...
 *dh/Qd       d*(1+input/d)

```

Thanks to Dennis for a byte!
> 4 votes

# Answer
# CJam, 15 bytes

```
5,2>rif{1$/)*N}

```

Try it online! or verify all test cases.
> 4 votes

# Answer
# C, ~~50~~ 46 bytes

```
i;f(int*a,int n){for(i=1;++i<5;*a++=n+i-n%i);}

```

*Thanks to Neil and nwellnhof for saving 4 bytes!*

Disappointingly long. I feel like there's some bit-shifting hack in here that I don't know about, but I can't find it yet. Returns a pointer to an array holding the three elements. Full program:

```
i;f(int*a,int n){for(i=1;++i<5;*a++=n+i-n%i);}

int main()
{
    int array[3];
    int n=10;
    f(array, n);
    printf("A:%d\tB:%d\tC:%d\n",array[0],array[1],array[2]);
    return 0;
}

```
> 4 votes

# Answer
## Pyke, ~~11 9~~ 8 bytes

```
3FODQRc+

```

Try it here!

```
3FODQRc+
         - Q = input()
3F       - for i in range(3): # for i in [0,1,2]
  O      -  i += 2
    Q c  -   Q-(Q%i)
       + -  i+^

```
> 4 votes

# Answer
## Mathematica, 21 bytes

```
Ceiling[#+1,{2,3,4}]&

```

This is an unnamed function which takes a single integer as input and returns a list of the multiples.

The `Ceiling` function takes an optional second parameter which tells it to round up to the next multiple of the given number. Thankfully, it *also* automatically threads over its second argument such that we can give it a list of values and in turn we'll get rounded up multiples for all of those.
> 4 votes

# Answer
# Octave, 20 bytes

```
@(n)n-mod(n,d=2:4)+d

```

Examples:

```
octave:60> f(123)
ans =

   124   126   124

octave:61> f(1081177)
ans =

   1081178   1081179   1081180

octave:62> f(420)
ans =

   422   423   424

```

Worth noting that we can do this up to 9 without adding any extra bytes:

```
@(n)n-mod(n,d=2:9)+d

```

Output (2520 is the smallest positive integer evenly divisible by all the single digit numbers):

```
octave:83> f(2520)
ans =

   2522   2523   2524   2525   2526   2527   2528   2529

```
> 4 votes

# Answer
# Haskell, 27 bytes

```
f n=[div n d*d+d|d<-[2..4]]

```
> 4 votes

# Answer
# Reng, 40 bytes

```
i1+#i2341ø>(1+)31j
i(2[¤,  q!^$]æl0eq!~

```

## 1: init

```
i1+#i2341ø

```

`i1+#i` sets the input to `1 + input`; this is because we are to work on the numbers strictly greater than the input. `234` initializes the tape with our iteration values, and  jumps to the beginning of the next line.

## 2a: loop

```
i(2[¤,  q!^$]æl0eq!~

```

`i(` puts the input at the STOS, and `2[` makes a new stack with the top 2 elements. `¤` duplicates the stack, and `,` does modulus. If there is a remainder, `q!^` breaks out of the loop to go to (b). Otherwise, we're fine to print. `$` removes the extra thingy, `]` closes the stack, and `æ` prints it nicely. `l0wq!~` terminates iff the stack contains zero members.

## 2b: that other loop

```
          >(1+)31j
        q!^

```

`(1+)` adds 1 to the STOS, and `31j` jumps to the part of the loop that doesn't take stuff from the stack. And profit.

---

That extra whitespace is really bothering me. Take a GIF.
> 4 votes

# Answer
## Labyrinth, 19 bytes

```
:?
:
#/)
\ #
!"*@
"

```

Try it online!

This outputs the results in the order `C, B, A` separated by linefeeds.

### Explanation

As usual, a short Labyrinth primer:

* Labyrinth has two stacks of arbitrary-precision integers, *main* and *aux*(iliary), which are initially filled with an (implicit) infinite amount of zeros. We'll only be using *main* for this answer.
* The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.

Despite the two no-ops (`"`) which make the layout seem a bit wasteful, I'm quite happy with this solution, because its control flow is actually quite subtle.

The IP starts in the top left corner on the `:` going right. It will immediately hit a dead end on the `?` and turn around, so that the program actually starts with this linear piece of code:

```
:   Duplicate top of main stack. This will duplicate one of the implicit zeros
    at the bottom. While this may seem like a no-op it actually increases
    the stack depth to 1, because the duplicated zero is *explicit*.
?   Read n and push it onto main.
:   Duplicate.
:   Duplicate.

```

That means we've now got three copies of `n` on the main stack, but its depth is `4`. That's convenient because it means we can the stack depth to retrieve the current multiplier while working through the copies of the input.

The IP now enters a (clockwise) 3x3 loop. Note that `#`, which pushes the stack depth, will always push a positive value such that we know the IP will always turn east at this point.

The loop body is this:

```
#   Push the stack depth, i.e. the current multiplier k.
/   Compute n / k (rounding down).
)   Increment.
#   Push the stack depth again (this is still k).
*   Multiply. So we've now computed (n/k+1)*k, which is the number
    we're looking for. Note that this number is always positive so
    we're guaranteed that the IP turns west to continue the loop.
"   No-op.
!   Print result. If we've still got copies of n left, the top of the
    stack is positive, so the IP turns north and does another round.
    Otherwise, see below...
\   Print a linefeed.
    Then we enter the next loop iteration.

```

After the loop was traversed (up to `!`) three times, all copies of `n` are used up and the zero underneath is revealed. Due to the `"` at the bottom (which otherwise seems pretty useless) this position is a junction. That means with a zero on top of the stack, the IP tries to go straight ahead (west), but because there's a wall it actually makes a 180 degree turn and moves back east as if it had hit a dead end.

As a result, the following bit is now executed:

```
"   No-op.
*   Multiply two zeros on top of the stack, i.e. also a no-op.
    The top of the stack is now still zero, so the IP keeps moving east.
@   Terminate the program.

```
> 4 votes

# Answer
## Minkolang 0.15, 17 bytes

```
n$z3[zi2+$d%-+N].

```

Try it here!

### Explanation

```
n$z                  Take number from input and store in register
   3[                Open for loop that repeats 3 times
     z               Push value in register on stack
      i2+            Loop counter plus 2
         $d          Duplicate stack
           %-+       Mod, subtract, add
              N      Output as number
               ].    Close for loop and stop.

```
> 3 votes

# Answer
# Matlab, 50 bytes

```
@(a)arrayfun(@(k)find(~rem(a+1:a+k,k))+a,[2 3 4])

```
> 3 votes

# Answer
# Retina, ~~62~~ ~~43~~ 26 bytes

17 bytes thanks to @Martin Büttner.

```
^
1111:
M!&`(11+):(\1*)
:

```

(Note the trailing newline.)

Try it online!

Input in unary in `1`, output in unary in `1` separated by newlines.

## Previous 43-byte version:

```
.+
11:$&;111:$&;1111:$&
\b(1+):(\1*)1*
$1$2

```

Try it online!

Input in unary, output in unary separated by semi-colon (`;`).

## Previous 62-byte version:

```
.+
$&11;$&111;$&1111
((11)+)1*;((111)+)1*;((1111)+)1*
$1;$3;$5

```

Try it online!

Input in unary, output in unary separated by semi-colon (`;`).
> 3 votes

# Answer
## JavaScript (ES6), 26 bytes

Interestingly porting either @KevinLau's Ruby answer or @xnor's Python answer results in the same length:

```
n=>[2,3,4].map(d=>n+d-n%d)
n=>[n+2&-2,n+3-n%3,n+4&-4]

```

I have a slight preference for the port of the Ruby answer as it works up to 253-3 while the port of the Python answer only works up to 231-5.
> 3 votes

# Answer
# Octave, ~~27~~ ~~22~~ 20 bytes

MATLAB and Octave:

```
f=2:4;@(x)f.*ceil((x+1)./f)

```

Better (solutions are equivalent, but one may outperform the other when further golfed), MATLAB and Octave:

```
@(x)x-rem(x,2:4)+(2:4)
f=2:4;@(x)x+f-rem(x,f)

```

Only in Octave:

```
@(x)x-rem(x,h=2:4)+h

```

Try here.
> 3 votes

# Answer
# APL (Dyalog Unicode), 11 bytes

-1 thanks to Adam

```
⎕(+-|⍨)1+⍳3

```

Try it online!

Explanation:

```
⎕(+-|⍨)1+⍳3
       1+⍳3    ⍝ 2 3 4
⎕              ⍝ read n
  +-|⍨          ⍝ {⍺ + ⍵ - ⍵ | ⍺}

Let's look at how {⍺ + ⍵ - ⍵ | ⍺} is transformed to +-|⍨:

        {⍺ + ⍵ - ⍵ | ⍺}
       {⍺} + {⍵ - ⍵ | ⍺}
         ⊣ + ({⍵} - {⍵ | ⍺})
         ⊣ + (⊢ - ({⍵} | {⍺}))
         ⊣ + (⊢ - (⊢ | ⊣))
        (⊣ + ⊢ - (⊢ | ⊣))
          (+ - (⊢ | ⊣))
          (+ - (⊣ |⍨ ⊢))
          (+ - (|⍨))
          (+-|⍨)

```
> 3 votes

# Answer
# \>\<\>, 31 bytes

```
&2v
:&\&
?!\1+:{:}%
ao\n1+:5=?;

```

Expects `N` to be present on the stack at program start. Try it online!
> 2 votes

# Answer
# R, ~~30~~ 26 bytes

(Reduced 4 bytes thanks to @Neil)

```
N=scan();cat(N+2:4-N%%2:4)

```

This (similarly to the rest of the answers I guess) adds 2:4 to the input and the reduces the remainder after running modulo on the same numbers.
> 2 votes

# Answer
# UGL, ~~51~~ ~~31~~ ~~25~~ 24 bytes

```
icu$l_u^^/%_u^*ocO$dddd:

```

Try it online!

## Previous 25-byte version:

```
iRcu$l_u$r^/%_u*ocO$dddd:

```

Try it online!

## Previous 31-byte version:

```
iRcuuulu$cuuuuuu%-r^/%_u*oddcO:

```

Try it online!

## Previous 51-byte version:

```
i$$cuuu/%_ucuuu*@cuuuu/%_ucuuuu*@cuu/%_ucuu*ocOocOo

```

Try it online!
> 2 votes

# Answer
# Mathematica 28 bytes

```
f@n_:=n-n~Mod~#+#&/@{2,3,4}

```

---

```
f[1]
f[4]
f[43]
f[123]
f[420]
f[31415]
f[1081177]

```

{2, 3, 4}

{6, 6, 8}

{44, 45, 44}

{124, 126, 124}

{422, 423, 424}

{31416, 31416, 31416}

{1081178, 1081179, 1081180}

---

The general case produces a general answer:

```
f[r]

```

{2 + r - Mod\[r, 2\], 3 + r - Mod\[r, 3\], 4 + r - Mod\[r, 4\]}
> 2 votes

# Answer
# Java ~~70~~ 57

```
a->System.out.print(a/2*2+2+" "+(a/3*3+3)+" "+(a/4*4+4))

```
> 2 votes

# Answer
# \>\<\>, 28 bytes

```
i2&::&::&@%-+nao&1+:&5=?;20.

```

# How it Works

```
i2&::&::&@%-+nao&1+:&5=?;20.
i2&                                  Takes N as input and stores 2 in the register
   ::                                Duplicates N twice
     &::&                            Pushes the register onto the stack and duplicates twice
          @                          Shifts top the 3 values in the stack to the right
                                     Stack now looks like: N N & N & (& = register)
            %-+nao                   Computes the smallest multiple of k > N: N+k-N%k, where k is the value of the register
               nao                   Outputs answer and a newline.
                  &1+:&5=?;          Increments register by 1, ends the program if the register equals 5
                           20.       Jumps back into the loop, skipping taking input and initializing the register

```

You could save a byte if you are allowed to take input by initializing the stack with N, but TIO doesn't allow for that. The interpreter on https://fishlanguage.com/ does.

```
2&::&::&@%-+nao&1+:&5=?;10.

```

Try it online!
> 2 votes

# Answer
# Vyxal `r`, 8 bytes

```
3ɾ›ƛ⁰/⌈*

```

Try it Online!

-1 thanks to lyxal

```
 ɾ       # Range 1...
3        # Literal
  ›      # Incremented (2...4)
   ƛ     # Map to...
       * # Product of...
          # Current item (implicit)
       * # And...
      ⌈  # Floor of
         # (Implicit) current item
     /   # Divided by...
    ⁰    # Input

```
> 2 votes

# Answer
# J, 18 bytes

```
2 3 4&([*>:@<.@%~)

```

Try it online!
> 1 votes

# Answer
# Golfscript, 22 bytes

```
~..2/)2*@3/)3*@4/)4*]`

```

Try it online!

Alternative 22-byte solution:

```
~..[4 2 3]{.@@/)*@}/]`

```

Try it online!
> 1 votes

# Answer
## Actually, 22 bytes

```
╗52x"╝1`;╛@%Y@╜<*`╓"£M

```

Try it online!

Fun fact: 3 bugs in Actually's interpreter were found and fixed while writing this program.

Not so fun fact: Those 3 bugs prevented this solution from being much shorter.

Explanation:

```
╗52x"╝1`;╛@%Y@╜<*`╓"£M
╗                       push input to reg0
 52x                    push range(2,5) ([2,3,4])
    "╝1`;╛@%Y@╜<*`╓"£M  map (for n in [2,3,4]):
     ╝                    push n to reg1
      1`;╛@%Y@╜<*`╓       find the smallest integer k where:
        ;╛@%Y               k is divisible by n and...
             @╜<*           is greater than the input

```
> 1 votes

# Answer
# Mathcad, \[tbd\] bytes

function version allows for simple evaluation of different divisor sets.

---

*Mathcad byte equivalence scheme not yet determined. Keyboard equivalence ~ 16 bytes.*
> 1 votes

# Answer
# Desmos, ~~141~~ 136 bytes

```
a=1
b=2\operatorname{ceil}\left(.5a+.1\right)
c=3\operatorname{ceil}\left(\frac{a}{3}+0.1\right)
d=4\operatorname{ceil}\left(.25a+.1\right)

```

Demonstration
Fixed the outputs while shaving off a few bytes.
> 1 votes

# Answer
# Brachylog, 12 bytes

```
Ṫ;234z%ᵛ0&>ᵛ

```

Try it online!

Takes input through the output variable and gives output through the input variable. (Shortest I could get it without reversed I/O was `~{>ᵛ}Ṫ;234z%ᵛ0∧Ṫ`, which at 16 bytes ties an extremely awkward implementation of Dennis' algorithm: `+₁Xṅg;234z%ᵐ+ᵐ↙X`.)

```
           ᵛ    Every element of
         &      the input variable
          >     is strictly greater than
                the output variable.
                Also, the input variable
Ṫ               is a list of three elements
     z          which zipped
 ;234           with 2, 3, and 4
       ᵛ0       produces 0 for each pair
      %         when the first element is taken mod the second.

```
> 1 votes

# Answer
# Japt, 8 bytes

```
3õ@Ä c°X

```

Try it
> 1 votes

# Answer
# Forth (gforth), 40 bytes

```
: f 5 2 do dup i over i mod - + . loop ;

```

Try it online!

### Explanation

Uses modulo of 2, 3, and 4 to get the distance to the next divisible number and then adds it to the original number (+1)

### Code Explanation

```
: f                \ start a new word definition
  5 2              \ set up parameters loop from 2 to 4
  do               \ start a counted loop
    dup i over     \ duplicate N, get the loop index, and then copy N again
    i mod          \ get N mod Loop-index (distance from last divisible number)
    -              \ subtract from Loop-index to get distance to next divisible number
    +              \ add distance-to-next to N to get number
    .              \ print
  loop             \ end counted loop
;                  \ end word definition

```
> 1 votes

# Answer
# Java (JDK), ~~141~~ 129 bytes

```
interface C{static void main(String[]a){var n=Double.valueOf(a[0])+1;for(int i=1;++i<5;)System.out.print(i*Math.ceil(n/i)+" ");}}

```

Try it online!

You may notice that no `class` has been defined, but instead an interface. This is just to further golf the code. Since the interface hasn't been given a `public` access modifier, the `main` method doesn't need it, either.

For a better understanding of this code, it's shown below with the variable `a` remnamed to its traditional name `args`:

```
var n = Double.valueOf(args[0]) + 1;
for (int i = 1; ++i < 5;)
    System.out.print(i * Math.ceil(n / i) + " ");
}

```

The program inputs a value as a command-line argument which is immediately incremented for compactness before being stored in the `double` variable `n`. Next, the for loop cycles through each integer `i` from 2 through to 4, printing the output values each cycle. See here for an interactive demonstration of the formula used to calculate said values.

In order to further golf this code, I think finding a way to use Java 6 would be ideal due to the `static` block's functionality, as expressed below:

```
public class Foo {
    static {
        // Your code here
    }
}

```

As you can see, although it's definitely good practice, explicitly defining the `main` method isn't necessary in this particular version of Java. (Correct me if that was incorrectly phrased)

Unfortunately, in performing such a conversion, the `var` keyword would no longer exist (since it was introduced in Java 10). More importantly, reconstructing the value input mechanism would be necessary, since a `static` block obviously doesn't have any method parameters, and especially not for command-line arguments. Feel free to leave comments and suggestions.
> 1 votes

# Answer
# C (gcc), 41 bytes

```
i=5;f(int*n){for(;--i;n[i-2]=*n+i-*n%i);}

```

Try it online!
> 1 votes

# Answer
# MMIX, 36 bytes (9 instrs)

Uses bit tricks to avoid dividing by 2 or 4 (sadly, it's unavoidable for 3)

```
foo ADDU $2,$0,1        // a = n + 1
    ANDN $2,$2,1        // a &= ~1
    ADDU $1,$0,3        // c = n + 3
    PUT  rD,0
    DIVU $0,$0,3
    GET  $0,rR          // b = n % 3
    SUBU $0,$1,$0       // b = c - b (= n + 3 - n % 3)
    ANDN $1,$1,3        // c &= ~3
    POP  3,0            // return a,b,c

```
> 1 votes

# Answer
# Scala, 268 bytes

```
def logic(y:Int)(x: Int) = (x)%y ==0

def fun(n:Int,  logic: Int => Boolean) : Int = {
  if (logic(n)) n else fun(n+1, logic)
}
for {
    N <- Array[Int](1,4, 43, 123, 420, 31415, 1081177)
    ABC <- Array[Int](2,3,4)
    res = fun(x+1, logic(i) _)
    } yield res

```
> 0 votes

# Answer
# Perl 5 `-n`, 26 bytes

```
//;map{say$'+$_-$'%$_}2..4

```

Try it online!
> 0 votes

# Answer
# Perl 6, 25 bytes

```
{[$^a+$_-$a%$_ for 2..4]}

```

Try it online!
> 0 votes

# Answer
## Arm Thumb (no div), 30 bytes

Raw machine code:

```
3001 1c42 2301 439a 600a 2302 3202 439a
608a 1c03 3b03 dcfd 1ac0 6048 4770

```

Uncommented assembly:

```
        .text
        .thumb
        .globl smallest_after_n
        .thumb_func
smallest_after_n:
        adds    r0, #1
        adds    r2, r0, #1
        movs    r3, #1
        bics    r2, r3
        str     r2, [r1]
        movs    r3, #2
        adds    r2, #2
        bics    r2, r3
        str     r2, [r1, #8]
        movs    r3, r0
.Lmod_loop:
        subs    r3, #3
        bgt     .Lmod_loop
.Lmod_loop_end:
        subs    r0, r3
        str     r0, [r1,#4]
        bx      lr

```

### Explanation

Happens to be valid Thumb-1, but feel free to use Thumb-2 to compete.

It is easier to understand in the equivalent C code.

```
void smallest_after_n(int32_t N, int32_t out[3])
{
    ++N; // increment N
    // Even multiple of 2: Lowest bit is zero.
    int32_t A = (N + 1) & ~1;
    out[0] = A;
    // Even multiple of 4: Lowest 2 bits are zero.
    // Since we know the lowest bit of A is zero, we reuse it.
    int32_t C = (A + 2) & ~2;
    out[2] = C;
    // Calculate the "inverse modulo" using a subtraction loop.
    // N % 3 == 0 => 0
    // N % 3 == 1 => -2
    // N % 3 == 2 => -1
    int32_t inv_modulo = N;
    while ((inv_modulo -= 3) > 0) {}
    // Round up by subtracting a negative
    int32_t B = N - inv_modulo;
    out[1] = B;
}

```
> 0 votes

# Answer
# Arturo, 25 bytes

```
$[n][map 2..4'd->d+n-n%d]

```

Try it
> 0 votes

# Answer
# Thunno, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
DA~234d%+1+

```

Attempt This Online!

Port of Dennis's Jelly answer.

#### Explanation

```
DA~234d%+1+  # Implicit input
DA~          # Duplicate and bitwise not
   234d      # Push [2, 3, 4] (digits of 234)
       %     # Push ^^ modulo ^
        +1+  # Add and increment

```
> 0 votes

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


title: Time to shortest permutation

text:
# Question
Title: Time to shortest permutation
Yesterday, as part of a IQ-style test, I got this interesting question:

> The time on a 24-hour clock is 11:43. What is the least number of minutes I should wait before the same digits are on the screen again (in any valid 24-hour time order)?

The answer's 91 minutes, if you were wondering!

This stuck in my mind, and it finds its way... here. In an adapted form, however... Your task is, given a 24-hour time string in the format `HH:MM` (or in any other way as long as it provides `HH` and `MM`), shift the digits around until you find 24-hour time strings that would be in the same day counting forwards, and pick the one whose distance to the input is the shortest. Then return the number of minutes to the picked time string as an integer, using default output rules.

## Method:

See above.

## Input:

Allow facilities for input such that 2 digits of hours and 2 digits of minutes are provided. Do not worry about invalid input (example: `25:12`, `1:34` \[`01:34` will be correct, however\], and `05:89`).

You cannot use 12-hour system.

## Output:

An integer. Note that it should be in minutes, not seconds or any other unit (this is fixed)

Return a distinct value (like 1440, an error, etc. I'm using "Nil" in the test-cases) when no valid shifted 24-hour time string can be created until 23:59.

## Test cases:

```
Input (HH:MM) -> Output (Int or "Nil")

11:43 -> 91
01:01 -> 9
17:38 -> 59
14:21 -> 413
13:20 -> 413
23:41 -> Nil
00:00 -> Nil

```

# Scoring:

This is , so shortest answer wins!

# Answer
# Vyxal `g`, ~~24 23~~ 22 bytes

```
Ṗ½'‛0xC½<Π;ƛE60β;ḣ$-'Ṡ

```

Try it Online!

Port of Kevin Cruijssen's 05AB1E answer. Input as a string, `"HHmm"`.

*-1 thanks to AndrovT in chat*
*-1 thanks to lyxal*

#### Explanation

```
Ṗ½'‛0xC½<Π;ƛE60β;ḣ$-'Ṡ  # Implicit input
Ṗ                       # Permutations
 ½                      # Split each in half
  '       ;             # Filter:
   ‛0xC½                #  Push [24, 60]
        <               #  Less than [24, 60]?
         Π              #  Both are true?
           ƛ    ;       # Map:
            E           #  Convert to integer
             60β        #  Convert from base-60
                 ḣ$     # Extract head and swap
                   -    # Subtract head from rest
                    '   # Filter:
                     Ṡ  #  Positive integers only
                        # g flag gets minimum
                        # Implicit output

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 135 bytes

```
Min@(s=Select)[(x@#~f~60-a~f~60)&/@s[Permutations[p=#],(w=x@#;24>w[[1]]>=#&@@(a=x@p)&&w[[2]]<60)&],#>0&]&
x=BlockMap[f=FromDigits,#,2]&

```

Try it online!

-6 bytes from @att
> 6 votes

# Answer
# 05AB1E, 24 bytes

```
œ2δôʒŽ9¦2ô‹P}60δβć-ʒ0›}ß

```

Input as a single 4-digit string in the format `HHmm`. Outputs an empty string if there is no result available.

Try it online or verify all test cases.

**Explanation:**

```
œ            # Get all permutations of the (implicit) input-string
  δ          # Map over each permutation:
 2 ô         #  Split it into parts of size 2 (to split HH and mm)
    ʒ        # Filter this list of [HH,mm] by:
     Ž9¦     #  Push compressed integer 2460
        2ô   #  Split it into parts of size 2 as well: [24,60]
          ‹  #  Check [HH<24,mm<60]
           P #  And check if both are truthy by taking the product
    }  δ     # After the filter: map over the remaining [HH,mm]:
     60 β    #  Convert it from a base-60 list to a base-10 integer
ć            # Extract head; pop and push remainder-list and first item separately
 -           # Subtract this head (the input) from all other valid permutations
  ʒ0›}       # Only keep all positive integers from the list with a filter on 0>
             # (a.k.a. keep all integers for times later than the input-time)
      ß      # After the filter: pop and leave the minimum
             # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž9¦` is `2460`.
> 4 votes

# Answer
# JavaScript (ES6), 96 bytes

Expects `("HH")("MM")`. Returns `NaN` for `Nil`.

```
h=>F=(m,s=h+m)=>(m=-~m%60)||++h<24?(g=s=>[...s].sort().slice(-4)+0)(s)==g("00"+h+m)||1+F(m,s):+F

```

Try it online!

### Commented

```
h =>           // outer function taking h = hours
F = (          // inner recursive function taking
  m,           //   m = minutes
  s = h + m    //   s = concatenation of the original hours and minutes
) =>           //
(m = -~m % 60) // increment the minutes modulo 60
||             // ignore the next statement if the result is not 0
++h < 24       // otherwise, increment the hours and make sure they are
?              // less than 24; if successful:
  ( g = s =>   //   g is a helper function taking a string s
    [...s]     //   split s into a list of characters
    .sort()    //   sort them lexicographically
    .slice(-4) //   take the last 4 characters
    + 0        //   coerce back to a string with a trailing '0'
  )(s) ==      //   invoke g with s and compare the result with
  g(           //   the same operation applied to ...
    "00" +     //     two leading zeros
    h + m      //     followed by h, followed by m
  )            //
  ||           //   stop if it matches; otherwise,
    1 +        //     increment the final result
    F(m, s)    //     and do a recursive call
:              // else:
  +F           //   force the result to NaN and stop

```
> 4 votes

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

```
x=>(g=y=>++y>2399?+g:y%100<60?(e=t=>[...1e4+t+g].sort()+0)(x)==e(y)||g(y)+1:g(y))(x)

```

Try it online!
> 4 votes

# Answer
# Python, 132 bytes

```
lambda x:(a:=x.split(':'),b:=int(a[0])*60+int(a[1]),*[i for i in range(b+1,1440)if sorted(f"{i%60:02}:{i//60:02}")==sorted(x)])[2]-b

```

Attempt This Online!

Throws a error if there is no valid output.

# Python, 113 bytes

```
lambda x,y:(b:=x*60+y,*[i for i in range(b+1,1440)if sorted((e:="%02d%02d")%divmod(i,60))==sorted(e%(x,y))])[1]-b

```

Attempt This Online!

Takes input as 2 numbers
> 3 votes

# Answer
# Charcoal, 42 bytes

```
≔↨Ｉ⪪θ:⁶⁰ηＩ⌊Φ…¹⁻¹⁴⁴⁰η⬤Ｉ…¹χ⁼№θλ№Ｉ↨¹⁰⁰↨⁺ηι⁶⁰λ

```

Try it online! Link is to verbose version of code. Outputs `None` if there is no solution. Explanation:

```
≔↨Ｉ⪪θ:⁶⁰η

```

Calculate the number of minutes since midnight.

```
Ｉ⌊Φ…¹⁻¹⁴⁴⁰η⬤Ｉ…¹χ⁼№θλ№Ｉ↨¹⁰⁰↨⁺ηι⁶⁰λ

```

Create a range from `1` until the number of minutes until the next midnight, filter on those that, when formatted as a time, contain identical counts of digits, and output the minimum. Note that I don't count `0` digits as all times have four digits so if the counts of the other digits are correct then so will the counts of the zero digits be; this avoids having to actually format the time.
> 3 votes

# Answer
# JavaScript, 109 bytes

Without recursion:

```
(h,m)=>{for(k=1,t=h*60+m;t++<1440;++k)if((a=(h,m)=>+[...''+h+m].sort().join``)(h,m)==a(t/60|0,t%60))return k}

```

Try it

```
f=(h,m)=>{for(k=1,t=h*60+m;t++<1440;++k)if((a=(h,m)=>+[...''+h+m].sort().join``)(h,m)==a(t/60|0,t%60))return k}

[
  '11:43', // -> 91
  '01:01', // -> 9
  '17:38', // -> 59
  '14:21', // -> 413
  '13:20', // -> 413
  '23:41', // -> undefined
].forEach(t => {
  const [hours, minutes] = t.split`:`.map(x=>+x);

  const additional = f(hours, minutes);

  if (additional === undefined) {
    console.log(undefined);
    return;
  }

  const getTime = (h,m) => {
    const now = new Date();
    now.setHours(h+1);
    now.setMinutes(m);

   const timeParts = now.toJSON().split`T`.flatMap(x=>x.split`:`);

    return [timeParts[1], timeParts[2]].join`:`
  }

  const oldTime = getTime(hours, minutes);
  const newTime = getTime(hours, minutes + additional);

  console.log(`${oldTime} + ${additional} minutes = ${newTime}`);
})
```
> 3 votes

# Answer
# Perl 5, 99 bytes

```
sub{"@{[grep{s|1(..)([0-5].)|$1:$2@{[sort/./g]},|}1e4..12359]}"=~/$_[0]((.+),.*?)\2/&&$1=~y///c/16}

```

Try it online!

Creates a long string of all HH:MM in a day (all 24\*60 of them) and adds the four digits sorted after each of those timestamps in the same long string. Searches the long string for the five char input HH:MM and collects the sorted digits behind it with `(.+),` and searches for those same sorted digits further down the long string with `\2`. The number of chars jumped ahead to find them divided by 16 is the number of minutes.
> 3 votes

# Answer
# Excel, ~~175~~ 171 bytes

```
=LET(
    a,A1,
    b,1440,
    c,{1;2;4;5},
    d,TEXT(SEQUENCE(,b)/b,"hh:mm"),
    e,BYCOL(MID(d,c,1),LAMBDA(x,CONCAT(SORT(x)))),
    f,0+IF(e=CONCAT(SORT(MID(a,c,1))),d),
    b*(XLOOKUP(a+1/b,f,f,,1)-a)
)

```

Input as *string* in format `"hh:mm"` in cell `A1`. Error returned if no valid output.
> 2 votes

# Answer
# Julia 1.0, ~~107~~ 102 bytes

```
using Dates
!x=(f=Minute;~q=sort(["$q"...]);t=Time(x);max(f(tonext(i->~i==~t,t,step=f(1))-t).value,0))

```

Try it online!

In Julia 1.8, the function will return 0 for inputs with no solution (example: `!"23:41"`). The TIO link only supports Julia 1.0, which fails for these inputs, since `Dates.tonext` doesn't stop at "23:59".

* Renaming `Dates.Minute` a `f` saves a byte.
* The subfunction `~` returns a sorted list of digits for comparison.
* This solution relies on `Dates.tonext`, which I've used in another challenge. In Julia 1.8, it returns a negative value for inputs with no solution, so `max` is used to filter these out. A `limit` parameter also exists, but this would return an error instead of a NULL value.
* -5 bytes thanks to MarcMush: replace `string(q)` with `"$q"`
> 1 votes

# Answer
# Thunno, \\$ 42 \log\_{256}(96) \approx \\$ 34.57 bytes

```
DLzP.Je2APiEgAu60<s24<&ke60AdEDAJsZT_g0>km

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer. Input as a string, `"HHmm"`.

#### Explanation

```
DLzP                   # Get the permutations of the input string
    .J                 # Join each inner list into a single string
      e                # Map over this list:
       2APi            #  Split into two pieces and convert to an integer
           E           # (End map)
            g          # Filter this list:
             Au        #  Dump onto the stack (last item of list on top of stack)
               60<     #  Is the last item less than 60?
                  s24< #  Is the first item less than 24?
&                      #  Are both of the above true?
 k                     # (End filter)
  e                    # Map over this list:
   60Ad                #  Convert from base-60
       E               # (End map)
        DAJ            # Duplicate and get the first item
           sZT         # Swap and remove the first item
              _        # Subtract the first item from the rest
               g       # Filter this list:
                0>     #  Is the number greater than 0?
                  k    # (End filter)
                   m   # Push the minimum value of this list
                       # Implicit output

```
> 1 votes

# Answer
# Nekomata, 24 bytes

```
↕ᵃ{¢b100B"<∩"e<60d}-_Paṁ

```

Attempt This Online!

Another port of Kevin Cruijssen's 05AB1E answer.

Take input as a list of four digits.

```
↕               Get a permutation of the input
 ᵃ              Apply the following block to both the input and the permutation
  {             Start the block
   ¢b               Get a number from base 10 digits
     100B           Convert the number to a list of digits in base 100
"<∩"e<              Check that the two numbers are smaller than [24,60] respectively
     60d            Get a number from base 60 digits
        }       End the block
         -_     Subtract and negate
           P    Check if the result is positive
            a   Get a list of all possible results
             ṁ  Get the minimum

```
> 1 votes

# Answer
# , 59 58 bytes

```
(e.*1+i.~)&([:/:~@,"%.10 10&#:)(+1+[:i.1440-])&.(24 60&#.)

```

Try it online!

* `(+1+[:i.1440-])&.(24 60&#.)` Calculates every absolute minute of the day (0 to 1439 scale), starting at the current hour and up, and then converts back to hh:mm form.
* `...&([:/:~@,"%.10 10&#:)` Converting both the input and the candidate list from the previous step into sorted lists of digits...
* `(e.*1+i.~)` Is the input an element of the candidate list (returns 0 or 1) times one plus its index within the candidate list. This returns 0 for no match, and the number of minutes we have to wait otherwise.
> 0 votes

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


# Question
Title: Calculate the average and standard deviation, rubiks cube style
## Introduction

When solving a rubiks cube, one often write down the times like this

```
11.91, (11.28), (12.32)

```

This is called a average of 3, while a average of 5 looks like this

```
13.36, (11.89), 12.31, (16.44), 12.26

```

Note how the *worst* and *best* times have parenthesis around them. When calculating the average of `5` these times are removed. For an average of 3 the worst and best times are NOT removed. Similarly when calculating the standard deviation.

When taking the average of more than 12 cubes things start to get a bit harder. The general rule of thumb is:

**When solving fewer than 5 cubes, do not remove any times when calculating avg or std**

**When evaluating fewer than 12 times, remove the best and worst time when calculating avg or std**

**When evaluating fewer than 40 times remove the 1/12 worst and 1/12 best times rounded down the nearest integer.**

**When evaluating more than 40 times remove the 1/20 worst times and the 1/20 best times rounded down to the nearest integer.**

For an average of `100` this would mean we would remove the `(100/20) = 5` best solves and `(100/20) = 5` worst solves. Giving

```
14.88, 12.28, 13.76, 16.06, 13.82, 13.26, 14.57, 12.56, 15.02, 14.73,
13.87, 14.59, 15.17, (18.48), 12.09, 12.76, 11.65, 14.14, 12.83, 14.30,
13.28, 14.02, 12.55, 15.18, 13.65, 12.72, 14.86, 14.08, 15.07, 12.88, 13.78,
13.88, 14.63, 12.72, (10.10), 14.70, 12.82, 13.27, 13.82, 14.74, (11.22),
13.46, 12.66, 14.06, (10.58), 15.06, (18.27), 13.39, (17.88), (18.67),
15.38, 15.60, 14.24, 12.64, 15.51, 14.23, 16.71, 14.55, 14.32, 12.33, 11.90,
13.65, 13.69, 13.90, 13.15, (9.61), 12.91, 13.39, 11.77, 12.64, 15.22,
14.69, 12.76, 15.10, 11.91, (11.28), 12.32, 14.28, 14.46, 14.66, 14.15,
15.27, (17.73), 12.70, 14.58, 11.84, 13.25, 13.36, 13.26, 15.72, 14.15,
12.77, 15.26, 12.87, 12.96, 13.57, 14.50, 14.30, 14.57, 12.69

```

## The challenge

The problem at hand is to take a (large) list of numbers and figure out the best average or std of a subset of these.

**input**

```
list, n, avg or std

```

Write a program that takes in a list of numbers formated exactly as comma seperated numbers `12.91, 13.39, ...` or `[12.91, 13,39 ... ]` You can assume that the list only contains real valued positive numbers less than `2^32`.

A number `n` indicating how many numbers to average or take the std of, if `n=0` one should take the average / std of all the numbers.

A string `avg` or `std` indicating if one should return the lowest average of `n` numbers or the lowest standard deviation (std). A negative `n` or a non integer should throw an error, blank or return false.

**Output**

The output should be exactly on the form

```
avg = ...
list of of numbers

```

or

```
std = ...
list of of numbers

```

As shown in the examples. Note that the best and worst times are marked with brackets as given by the rules above. **The function should return the `n` consecutive times with the *lowest* `avg` or `std`** At every 12 time, a newline should be inserted.

## Test case

I will use the following list of `200` numbers to base my tests on

```
15.86, 17.02, 24.01, 21.01, 15.93, 14.86, 18.43, 12.52, 18.48, 19.85, 13.01, 14.92, 13.07, 13.44, 13.07, 15.08, 12.70, 13.59, 15.22, 11.88, 13.26, 13.62, 12.85, 16.88, 15.78, 15.94, 14.88, 12.28, 13.76, 16.06, 13.82, 13.26, 14.57, 12.56, 15.02, 14.73, 13.87, 14.59, 15.17, 18.48, 12.09, 12.76, 11.65, 14.14, 12.83, 14.30, 13.28, 14.02, 12.55, 15.18, 13.65, 12.72, 14.86, 14.08, 15.07, 12.88, 13.78, 13.88, 14.63, 12.72, 10.10, 14.70, 12.82, 13.27, 13.82, 14.74, 11.22, 13.46, 12.66, 14.06, 10.58, 15.06, 18.27, 13.39, 17.88, 18.67, 15.38, 15.60, 14.24, 12.64, 15.51, 14.23, 16.71, 14.55, 14.32, 12.33, 11.90, 13.65, 13.69, 13.90, 13.15, 9.61, 12.91, 13.39, 11.77, 12.64, 15.22, 14.69, 12.76, 15.10, 11.91, 11.28, 12.32, 14.28, 14.46, 14.66, 14.15, 15.27, 17.73, 12.70, 14.58, 11.84, 13.25, 13.36, 13.26, 15.72, 14.15, 12.77, 15.26, 12.87, 12.96, 13.57, 14.50, 14.30, 14.57, 12.69, 15.21, 14.45, 14.90, 14.91, 15.66, 15.87, 14.79, 15.69, 17.37, 15.42, 12.11, 14.89, 13.39, 12.62, 13.42, 14.07, 14.85, 13.23, 14.05, 14.43, 13.36, 14.19, 14.16, 14.66, 12.02, 12.56, 12.69, 12.55, 14.36, 15.79, 12.53, 12.51, 12.15, 15.60, 13.42, 12.87, 13.02, 15.66, 13.18, 14.77, 13.57, 13.86, 12.26, 14.48, 14.68, 11.85, 14.82, 13.74, 13.85, 15.05, 14.78, 14.43, 12.72, 14.39, 15.06, 15.28, 12.06, 14.59, 15.49, 11.66, 14.83, 14.09, 11.62, 15.96, 14.77, 14.99, 14.20, 12.35, 17.62, 11.66, 13.46, 15.24, 14.85, 13.48

```

**Input 0:**

```
list, 3, avg

```

**Output 0:**

```
avg = 11.84
11.91, (11.28), (12.32)

```

**Input 1:**

```
list, 12, avg

```

**Output 1:**

```
avg = 12.88
(9.61), 12.91, 13.39, 11.77, 12.64, (15.22), 14.69, 12.76, 15.10, 11.91, 11.28, 12.32

```

**Input 2:**

```
list, 12, std

```

**Output 2:**

```
std = 0.44
15.21, 14.45, 14.90, 14.91, 15.66, 15.87, 14.79, 15.69, (17.37), 15.42, (12.11), 14.89

```

**Input 3:**

```
list, 0, std

```

**Output 3:**

```
std = 1.21
15.86, 17.02, (24.01), (21.01), 15.93, 14.86, (18.43), 12.52, (18.48), (19.85), 13.01, 14.92,
13.07, 13.44, 13.07, 15.08, 12.70, 13.59, 15.22, 11.88, 13.26, 13.62, 12.85, 16.88,
15.78, 15.94, 14.88, 12.28, 13.76, 16.06, 13.82, 13.26, 14.57, 12.56, 15.02, 14.73,
13.87, 14.59, 15.17, (18.48), 12.09, 12.76, (11.65), 14.14, 12.83, 14.30, 13.28, 14.02,
12.55, 15.18, 13.65, 12.72, 14.86, 14.08, 15.07, 12.88, 13.78, 13.88, 14.63, 12.72,
(10.10), 14.70, 12.82, 13.27, 13.82, 14.74, (11.22), 13.46, 12.66, 14.06, (10.58), 15.06,
(18.27), 13.39, (17.88), (18.67), 15.38, 15.60, 14.24, 12.64, 15.51, 14.23, 16.71, 14.55,
14.32, 12.33, 11.90, 13.65, 13.69, 13.90, 13.15, (9.61), 12.91, 13.39, (11.77), 12.64,
15.22, 14.69, 12.76, 15.10, 11.91, (11.28), 12.32, 14.28, 14.46, 14.66, 14.15, 15.27,
(17.73), 12.70, 14.58, 11.84, 13.25, 13.36, 13.26, 15.72, 14.15, 12.77, 15.26, 12.87,
12.96, 13.57, 14.50, 14.30, 14.57, 12.69, 15.21, 14.45, 14.90, 14.91, 15.66, 15.87,
14.79, 15.69, 17.37, 15.42, 12.11, 14.89, 13.39, 12.62, 13.42, 14.07, 14.85, 13.23,
14.05, 14.43, 13.36, 14.19, 14.16, 14.66, 12.02, 12.56, 12.69, 12.55, 14.36, 15.79,
12.53, 12.51, 12.15, 15.60, 13.42, 12.87, 13.02, 15.66, 13.18, 14.77, 13.57, 13.86,
12.26, 14.48, 14.68, 11.85, 14.82, 13.74, 13.85, 15.05, 14.78, 14.43, 12.72, 14.39,
15.06, 15.28, 12.06, 14.59, 15.49, (11.66), 14.83, 14.09, (11.62), 15.96, 14.77, 14.99,
14.20, 12.35, 17.62, (11.66), 13.46, 15.24, 14.85, 13.48

```

Split the lines at every 12 number.

**Input 4:**

```
list, 201, avg

```

**Output 5:**

```
Throw `Error` or `False`.

```

**Input 6:**

```
list, 1, avg

```

**Output 6:**

```
avg = 9.61
(9.61)

```

**Input 8:**

```
list, 1, std

```

**Output 8:**

```
std = 0
(15.86)

```

just return the first element of the list.

# Scoring

Submissions will be scored in **bytes**. I recommend this website to keep track of your byte count, though you can use any counter you like. Like always whitespace counts as bytes.

Remove 25% of your byte count if your function has the ability to switch between highest avg and std, and lowest avg and std. Eg input on the form

```
list, n, avg / std, high / low

```

This is , so the lowest score wins!

# Answer
> 2 votes
# Java 10, ~~944~~ ~~903~~ 861 bytes

```
import java.util.*;interface M{static void main(String[]a){var f=a[2];int n=new Short(a[1]),i=0,l,j,k;if(n<0)return;List<Double>L=new Stack(),t,r,R=L,u,U=L,S=L,V=L;for(var s:a[0].split(","))L.add(new Double(s));l=L.size();n=n<1?l:n;i=0;double m=99,M=m,q,Q,x,y,z;do{for(t=new Stack(),x=y=j=0;j<n;)t.add(L.get(i+j++));for(k=n<12?0:n<40?n/12:n/20,j=k=k<1?1:k,u=new ArrayList(t),r=new Stack();j-->0;){r.add(q=Collections.min(t));r.add(Q=Collections.max(t));if(n>4){t.remove(q);t.remove(Q);}}for(var T:t)x+=T;x/=k=n>4?n-2*k:n;if(x<m){m=x;R=r;U=u;}for(var T:t)y+=(z=T-x)*z;y=Math.sqrt(y/k);if(y<M){M=y;S=r;V=u;}}while(i++<l-n);j=f.charAt(0)-97;System.out.println(f+" = "+f.format(f="%.2f",q=j<1?n<2?Collections.min(L):m:n<2?0:M));i=0;for(var o:j<1?U:n<2?L.subList(0,1):V)System.out.print(f.format((j<1?R:S).remove(o)?"(%.2f)":f,n+j<2?q:o)+(++i<n&i%12>0?", ":"\n"));}}

```

Full program requirement, strict I/O formatting, validating.. sigh.. \>.\>

Verify all test cases: 3,avg ; 12,avg ; 12,std ; 0,std ; 201,avg ; 1,avg ; 1,std ; -1,either.

Here is the same as function with somewhat flexible I/O and without validating (still **~~776~~ ~~739~~ ~~719~~ 705 bytes**..):

```
import java.util.*;(L,n,f)->{int i=0,l=L.size(),j,k;List<Double>t,r,R=new Stack(),u,U=R,S=R,V=R;n=n<1?l:n;double m=99,M=m,q,Q,x,y,z;do{for(t=new Stack(),x=y=j=0;j<n;)t.add(L.get(i+j++));for(k=n<12?0:n<40?n/12:n/20,j=k=k<1?1:k,u=new ArrayList(t),r=new Stack();j-->0;){r.add(q=Collections.min(t));r.add(Q=Collections.max(t));if(n>4){t.remove(q);t.remove(Q);}}for(var T:t)x+=T;x/=k=n>4?n-2*k:n;if(x<m){m=x;R=r;U=u;}for(var T:t)y+=(z=T-x)*z;y=Math.sqrt(y/k);if(y<M){M=y;S=r;V=u;}}while(i++<l-n);j=f.charAt(0)-97;System.out.println(f+" = "+f.format(f="%.2f",q=j<1?n<2?Collections.min(L):m:n<2?0:M));for(var o:j<1?U:n<2?L.subList(0,1):V)System.out.print(f.format((j<1?R:S).remove(o)?"(%.2f)":f,n+j<2?q:o)+" ");}

```

-20 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
import java.util.*;           // Required import for List, Stack and Collections
interface M{                  //  Class
  static void main(String[]a){//   Mandatory main-method
    var f=a[2];               //    Save the third argument in String `f`
    int n=new Short(a[1]),    //    Save the second argument as integer in `n`
        i=0,l,j,k;            //    Some temp/index integers
    if(n<0)return;            //    If `n` is negative: stop the program
    List<Double>L=new Stack(),//    Input-List, starting empty
                t,r,R=L,u,U=L,S=L,V=L;
                              //    Some temp Lists
    for(var s:a[0].split(","))//    Loop over the input-items as Strings
      L.add(new Double(s));   //     Convert them to doubles, and add them to the List
    l=L.size();               //    Set `l` to the amount of items
    n=n<1?l:n;                //    If `n` was 0, make it equal to `l` instead
    double m=99,M=m,          //    Lowest `avg` and `std`, both starting at 99
           q,Q,x,y,z;         //    Some temp floats
    do{                       //    Start the do-while:
      for(t=new Stack(),      //     Reset List `t`
          x=y=j=0;j<n;)       //     Loop `j` in the range [0, `n`):
        t.add(L.get(i+j++));  //      And add the items on index `i+j` of List `L` to `t`
      for(k=n<12?             //     If `n` is smaller than 12
             0                //      Set `k` to 0
            :n<40?            //     Else-if `n` is in the range [12; 40)
             n/12             //      Set `k` to 1/12th of `n`
            :                 //     Else (`n` is 40 or larger)
             n/20,            //      Set `k` to 1/20th of `n`
          j=k=k<1?1:k,        //     If `k` is 0 due to rounding, make it 1 instead
          u=new ArrayList(t), //     Copy List `t` to `u`
          r=new Stack();      //     And reset List `r`
          j-->0;){            //     Loop `k` amount of times:
        r.add(q=Collections.min(t));
                              //      Add the smallest item in List `t` to `r`
        r.add(Q=Collections.max(t));
                              //      as well as the largest item
        if(n>4){              //      If `n` is 5 or larger:
          t.remove(q);t.remove(Q);}}
                              //       Remove those two items from List `t`
      for(var T:t)            //     Loop over List `t`:
        x+=T;                 //      And sum them all into value `x`
      x/=k=n>4?               //     If `n` is 5 or larger
          n-2*k               //      Set `k` to `n-2*k` and divide `x` by that
         :                    //     Else:
          n;                  //      Set `k` to `n` and divide `x` by that
      if(x<m){                //     If `x` is smaller than the previous smallest avg `m`
        m=x;                  //      Replace `m` with `x` (smallest avg)
        R=r;                  //      Replace `R` with `r` (items between parenthesis)
        U=u;}                 //      And replace `U` with `u` (all `n` items in this avg)
      for(var T:t)            //     Loop over List `t` again:
        y+=(z=T-x)*z;         //      And sum `(T-x)**2` to `y`
      y=Math.sqrt(y/k);       //     Also divide `y` by `k`, and take its square-root
                              //     The process above is how you calculate the std
      if(y<M){                //     If `y` is smaller than the previous smallest std `M`:
        M=y;                  //      Replace `M` with `y` (smallest std)
        S=r;                  //      Replace `S` with `r` (items between parenthesis)
        V=u;}}                //      And replace `V` with `u` (all `n` items in this std)
    while(i++<l-n);           //    Continue the do-while as long as `i` is smaller than `l-n`
    j=f.charAt(0)-97;         //    Set `j` to the alphabetic index of the first letter of `f`
    System.out.println(f+" = "//    Print "`f` = "
      +f.format(f="%.2f",     //     Round to two decimals
        q=j<1?                //     If it's an avg:
           n<2?               //      And `n` is 1:
            Collections.min(L)//       Simply take the smallest value in `L`
           :                  //      Else:
            m                 //       Take the calculated lowest avg `m`
          :                   //     Else (it's an std):
           n<2?               //      If `n` is 1:
            0                 //       Use 0
           :                  //      Else:
            M));              //       Take the calculated lowest std `M`
    i=0;                      //    Reset `i` to 0
    for(var o:j<1?            //    If it's an avg:
               U              //     Loop over List `U`
              :               //    Else (it's an std instead):
               n<2?           //     If `n` is 1:
                L.subList(0,1)//      Only take the first item of List `L`
               :              //     Else:
                V)            //      Loop over List `V`
      System.out.print(f.format(
       (j<1?                   //    If it's an avg:
         R                     //     Use List `R`
        :                      //    Else (it's an std instead):
         S)                    //     Use List `S`
           .remove(o)?         //    If the current item is in this List:
             "(%.2f)"          //     Round to two decimals, and add parenthesis
            :                  //    Else:
             f,                //     Only round to two decimals
       n+j<2?                  //    If it's an avg, and `n` is 1:
        q                      //     Take the smallest value in `L`
       :                       //    Else:
        o)                     //     Take the current item in this loop
          +(++i<n              //    If it's not the last item,
                 &i%12>0?      //    and also not the 12th item of the row:
            ", "               //     Append a comma and space as separator
           :                   //    Else:
            "\n"));}}          //     Append a newline instead

```

# Answer
> 1 votes
# 05AB1E, score: 85.5 (114 bytes \- 25% bonus)

<sup>† Could be **score: 83.25 (111 bytes \- 25% bonus)** by removing `2.ò` (which rounds the output avg/std to 2 decimals). This isn't mentioned in the challenge rules, but since everything else about the I/O is so strict and rounding to two decimals is also done by the WCA (World Cube Association), I've just included it.</sup>

```
DŒsgI‚²ĀèDUùεƵJü2XŽ4Ý2ô@ÏXšzX*òθFDWsà‚vyD…(ÿ).;}}Dʒ'(å≠X5‹~}žuмDÅA©-nÅAt®‚³Çθè‚}Σθ}|θÇнƵ7.Sè`2.ò³'=‚sªs12ô»»¹gÝ²å×

```

Also supports `low` vs `high` as fourth input. At the cost of just 8 bytes (`|θÇнƵ7.Sè` instead of `н`), this was well worth the 25% bonus.
Outputs an empty string for invalid \\$n\\$.

Try it online or verify all test cases.

**Explanation:**

```
D                    # Duplicate the first (implicit) input-list
 Œ                   # Pop the copy, and get all its sublists
  sgI‚²Āè            # Transform n=0 to n=listLength
  s                  #  Swap so the first input-list is at the top again
   g                 #  Pop and push its length
    I‚               #  Pair it with the second input-integer `n`
      ²              #  Push the second input-integer `n` again
       Ā             #  Check whether it's NOT 0 (0 if 0; 1 otherwise)
        è            #  0-base index this into the pair
         DU          # Store a copy in variable `X`
           ù         # Only keep the subslist of that size
ε                    # Map over each sublist
 ƵJü2XŽ4Ý2ô@ÏXšzX*òθ #  Determine how many lowest/highest numbers we should surround
                     #  with parenthesis:
 ƵJ                  #   Push compressed integer 120
   ü2                #   Get its overlapping pairs: [12,20]
     X               #   Push value `X`
      Ž4Ý            #   Push compressed integer 1240
         2ô          #   Split it into pairs: [12,40]
           @         #   >= check on `X`: [X>=12,X>=40]
            Ï        #   Keep the [12,20]-values at the truthy indices
             Xš      #   Prepend `X` itself to this list
               z     #   Calculate 1/v for each value in this list
                X*   #   Multiply each by `X`
                  ò  #   Round each to the nearest integer
                   θ #   Pop and keep the last one
 F                   #  Loop that many times:
  D                  #   Duplicate the current sublist
   W                 #   Push its minimum (without popping)
                     #   (will ignore values already wrapped in parenthesis)
    s                #   Swap so the copy of the sublist is at the top again
     à               #   Pop and push its maximum
                     #   (will ignore values already wrapped in parenthesis)
      ‚              #   Pair this minimum and maximum together
       v             #   Loop over this pair:
        yD           #    Push the min or max twice
          …(ÿ)       #    Surround the top copy in parenthesis
              .;     #    Replace the first occurrence of this value in the sublist
       }             #   Close the [min,max]-loop
 }                   #  Close the other loop
  D                  #  Duplicate the modified sublist
   ʒ                 #  Filter the copy by:
    '(å≠            '#   Check that the current value does NOT contain parenthesis
           ~         #   OR
        X5‹          #   Whether `X` is smaller than 5
   }                 #  Close the filter
    žu               #  Push constant string "()<>[]{}"
      м              #  Remove all those characters from each value within the list
                     #  (only applies if `X` is smaller than 5)
  DÅA©-nÅAt®‚        #  Pop this list, and push its [std,avg] pair:
  D                  #   Duplicate this list
   ÅA                #   Pop the copy, and get its average
     ©               #   Store this average in variable `®` (without popping)
      -              #   Subtract this average from each value in the list
       n             #   Square each
        ÅA           #   Take the average of this list again
          t          #   Take the square-root of that
           ®‚        #   And pair this std with the average `®`
  ³                  #  Push the third input-string
   Ç                 #  Convert it to a list of codepoint integers
                     #  ("avg"=[97,118,103]; "std"=[115,116,100])
    θ                #  Pop and push the last value ("avg"=103; "std"=100)
     è               #  Use that to 0-based modular index into the pair of [std,avg]
      ‚              #  And pair it together with the modified list
}                    # Close the map
 Σ                   # Sort this list by:
  θ                  #  The last item of the pair (the avg or std)
 }                   # Close the sort-by
  |                  # Get a list of all remaining inputs: [third,fourth]
   θ                 # Pop and keep its last item (the fourth input)
                     # (`|θ` cannot be `I`, since `³` won't add the third input to the
                     # input history)
    Ç                # Convert it to a list of codepoint integers as well
                     # ("low"=[108,111,119]; "high"=[104,105,103,104])
     н               # Pop and push the first value ("low"=108; "high"=104)
      Ƶ7             # Push compressed integer 108
        .S           # Compare: -1 if <108; 0 if ==108; 1 if >108
                     # (aka "low"=0; "high"=-1)
          è          # Use that to 0-based modular index into the sorted list
                     # (where -1 will take the last/highest item)
`                    # Pop the pair and push its contents to the stack
 2.ò                 # Round the avg/std to 2 decimals†
    ³                # Push the third input-string again
     '=‚            '# Pair it with an "="
        sª           # Swap and append the rounded avg/std
 s                   # Swap so the list is at the top
  12ô                # Split it into parts of size 12
     »               # Join each inner list by spaces, and then each string by newlines
          »          # Join the two strings on the stack with newline delimiter
¹gÝ²å×               # Transform it to an empty string if `n` is invalid:
¹g                   #  Push the length of the first input-list
  Ý                  #  Pop and push a list in the range [0,listLength]
   ²å                #  Check if the second input `n` is in this list
                     #  (1 if truthy; 0 if falsey)
     ×               #  Repeat the string that many times
                     # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ƵJ` is `120`; `Ž4Ý` is `1240`; and `Ƶ7` is `108`.

---
Tags: code-golf, statistics
---