# Question
Title: Let's practice the scoring rules of 421!
**421** is a rather popular dice game in France and some other European countries. It is mostly played in bars and pubs to determine who's going to buy the next round of drinks. The full game is usually played in two rounds, with tokens that each player tries to get rid of, but this is irrelevant here. (Wikipedia page in French.)

The game is played with 3 standard cube dice.

## Task

Your task is to sort a non-empty list of distinct 3-dice rolls **\[ X,Y,Z \]** from highest to lowest, by applying the scoring rules of this game.

## Basic scoring

* **4,2,1** is the highest possible combination. Depending on the rules, it may score 8, 10 or 11 points. Because we are sorting the rolls rather than counting the points, the exact value doesn't matter.
* Three Aces: **1,1,1** is the second highest combination and scores **7** points.
* Two-Aces: **X,1,1** (where **X** is 2 to 6) scores **X** points.
* Three-of-a-Kind: **X,X,X** (where **X** is 2 to 6) scores **X** points.
* Straights: **X,X+1,X+2** scores **2** points.
* All other rolls score **1** point.

## Settling ties

Whenever two rolls give the same number of points, the following rules apply:

* A Two-Aces is better than a Three-of-a-Kind. Example: **5,1,1** beats **5,5,5**.
* The Three-of-a-Kind **2,2,2** is better than a straight. Example: **2,2,2** beats **4,5,6**.
* Straights are ordered from lowest to highest. Example: **4,5,6** beats **2,3,4**.
* All other rolls are settled by sorting the dice from highest to lowest. Example: **6,5,2** beats **6,4,3**. (Therefore, the lowest possible combination in the game is **2,2,1**.)

Below are the 56 possible distinct rolls ordered from highest to lowest:

```
421 111 611 666 511 555 411 444 311 333 211 222 654 543 432 321
665 664 663 662 661 655 653 652 651 644 643 642 641 633 632 631
622 621 554 553 552 551 544 542 541 533 532 531 522 521 443 442
441 433 431 422 332 331 322 221

```

## Challenge rules

* You may take the rolls in any reasonable format, such as a list of lists `[[3,2,1],[4,2,1]]`, a list of strings `["321","421"]`, a list of integers `[321,421]`, etc. However, each die must be clearly identifiable with a value from **1** to **6**.
* For each roll, you can assume that the dice are sorted either from lowest to highest or from highest to lowest, as long as it is consistent. Please state in your answer which order you're expecting, if any.
* The shortest answer in bytes wins!

## Test cases

Using lists of strings with the dice sorted from highest to lowest:

### Inputs

```
[ "321", "654" ]
[ "222", "321", "211" ]
[ "333", "311", "331", "111" ]
[ "111", "222", "333", "444" ]
[ "321", "421", "521", "621" ]
[ "422", "221", "442", "421", "222" ]
[ "222", "111", "421", "211", "651", "652", "543" ]

```

### Expected outputs

```
[ "654", "321" ]
[ "211", "222", "321" ]
[ "111", "311", "333", "331" ]
[ "111", "444", "333", "222" ]
[ "421", "321", "621", "521" ]
[ "421", "222", "442", "422", "221" ]
[ "421", "111", "211", "222", "543", "652", "651" ]

```

# Answer
# Python, 93 bytes

```
lambda a:sorted(a,key=lambda x:(x!=421,x>111,-(x%100<12)*x-(x%111<1)*x*.9,(x%111==99)*-x,-x))

```

Try it online!
> 6 votes

# Answer
# Jelly,  ~~37~~  34 bytes

```
;Ø1,ẋ3$)Ẏṙ-;‘r’Ɗ€;œċ3$Ṇ63¦
6RṚÇiµÞ

```

A monadic link accepting a list of lists of dice rolls (each sorted descending) which yields the sorted rolls descending.

**Try it online!** Or see a test-suite ...or try all rolls sorted lexicographically

### How?

This method builds a list of all rolls from highest to lowest\*, replacing `[4,2,1]` with `0` (an invalid input roll), in order to rank each roll using Jelly's first-index-of atom, `i`.

* The list also includes repeats and redundant entries which wont affect the behaviour:

```
[[1,1,1],[6,1,1],[6,6,6],[5,1,1],[5,5,5],[4,1,1],[4,4,4],[3,1,1],[3,3,3],[2,1,1],[2,2,2],[1,1,1],[7,6,5],[6,5,4],[5,4,3],[4,3,2],[3,2,1],[2,1,0],[6,6,6],[6,6,5],[6,6,4],[6,6,3],[6,6,2],[6,6,1],[6,5,5],[6,5,4],[6,5,3],[6,5,2],[6,5,1],[6,4,4],[6,4,3],[6,4,2],[6,4,1],[6,3,3],[6,3,2],[6,3,1],[6,2,2],[6,2,1],[6,1,1],[5,5,5],[5,5,4],[5,5,3],[5,5,2],[5,5,1],[5,4,4],[5,4,3],[5,4,2],[5,4,1],[5,3,3],[5,3,2],[5,3,1],[5,2,2],[5,2,1],[5,1,1],[4,4,4],[4,4,3],[4,4,2],[4,4,1],[4,3,3],[4,3,2],[4,3,1],[4,2,2],0,[4,1,1],[3,3,3],[3,3,2],[3,3,1],[3,2,2],[3,2,1],[3,1,1],[2,2,2],[2,2,1],[2,1,1],[1,1,1]]

```

```
;Ø1,ẋ3$)Ẏṙ-;‘r’Ɗ€;œċ3$Ṇ63¦ - Link 1, build rolls: descending pips, P  e.g. [6,5,4,3,2,1]
       )                   - for each:       e.g. X=5
 Ø1                        -   literal [1,1]
;                          -   concatenate        [5,1,1]
      $                    -   last two links as a monad (f(X)):
     3                     -     literal 3
    ẋ                      -     repeat           [5,5,5]
   ,                       -   pair               [[5,1,1],[5,5,5]]
        Ẏ                  - tighten (to a list of rolls rather than pairs of rolls)
          -                - literal -1
         ṙ                 - rotate left by (make rightmost [1,1,1] the leftmost entry)
               Ɗ€          - for €ach: last three links as a monad (f(X)):
            ‘              -   increment  -> X+1
              ’            -   decrement  -> X-1
             r             -   range      -> [X+1,X,X-1]
                           -   ...note: [7,6,5] and [2,1,0] are made but are redundant
           ;               - concatenate
                     $     - last two links as a monad (f(P)):
                    3      -   literal 3
                  œċ       -   combinations with replacement -> [[6,6,6],[6,6,5],...,[6,6,1],[6,5,5],...,[1,1,1]]
                 ;         - concatenate
                         ¦ - sparse application...
                       63  - ...to indices: 63
                      Ṇ    - ...what: NOT   -> replaces the [4,2,1] entry with a 0

6RṚÇiµÞ - Main Link: list of rolls
     µÞ - sort by the monadic link:
6       -   six
 R      -   range -> [1,2,3,4,5,6]
  Ṛ     -   reverse -> [6,5,4,3,2,1]
   Ç    -   call the last link as a monad -> [[1,1,1],[6,1,1],[6,6,6],[5,1,1],...]
    i   -   first index of (e.g.: [1,1,1]->1 or [6,1,1]->2 or [4,2,1]->0)

```
> 4 votes

# Answer
# Retina 0.8.2, 67 bytes

```
O$#^`(421|111)|(\d)((11)|\2\2)|(654|543|432|321)|\d{3}
$1$2$#4$#5$&

```

Try it online! Link includes test cases. Explanation: The numeric sort key is generated as follows:

```
421     42100421
111     11100111
611-211   610611-  210211
666-222   600666-  600222
654-321    01654-   01321
653-221    00653-   00221

```
> 4 votes

# Answer
# , 73 bytes

```
(x=scan())[order(x!=421,x>111,-(x%%100<12)*x-(!x%%37)*x*.9,x%%37!=25,-x)]

```

Try it online!

* Full program taking a list of integer from stdin and returning them in descending order (i.e. `421 ... 221`)
* Started as partially inspired by @Lynn answer, now is basically a porting of it... so credits to @Lynn ;)
* Saved 2 bytes getting division remainder `x % 37` instead of `111`

**Explanation :**

For each of the numbers 5 keys are computed and used hierarchically to sort the array :

```
key1 = 0 if equal to 421, 1 otherwise
key2 = 0 if equal to 111, 1 otherwise
key3 = 0
       - 1.0*x if number is x11 numbers (2 aces)
       - 0.9*x if number is xxx numbers (3 of a kind)
key4 = 0 if number is a straight, 1 otherwise
key5 = -x

Then the array is sorted by key1 first, then by key2 in case of tie and so on...

```
> 3 votes

# Answer
# 05AB1E, ~~76~~ ~~48~~ 45 bytes

```
421X3∍6LR©vy11«y3∍}®vy>y<ŸJ})D®3ãJsм)˜©IΣ®sk>

```

~~This turned out to be a lot longer than expected, but at least it's easy to implement. Will see if I can find a better solution..~~ Made the list by hand now, but still a bit long.

Try it online or verify all test cases.

**Explanation:**

```
421             # Push 421 to the stack
X3∍             # ('1' lengthened to size 3) Push 111 to the stack
6LR             # Take the range [6, 1]
   ©            # Save this range in the register so we can re-use it
   v    }       # Loop over this range:
    y11«        #  Merge '11' with the current number `y`, and push it to the stack
    y3∍         #  Lengthen the current number `y` to size 3, and push it to the stack
   ®v      }    # Load the range [6, 1] from the register, and loop over it again:
     y>y<Ÿ      #  Take the range [`y+1`, `y-1`]
          J     #  And join them together to single 3-digit numbers
)               # Push everything that's now on the stack to a single list
 D              # Duplicate this list
  ®             # Load the range [6, 1] from the register again
   3ã           # Take the cartesian repeated three times
     R          # Reverse this list
      J         # Join every inner list to a single 3-digit number
 s              # Swap, so the duplicate list of above is at the top of the stack again
  м             # And remove all those items from the cartesian list
   )            # Combine both lists (as list of lists)
    ˜           # Flatten it
     ©          # Store this full completed list (now equal to the challenge description,
                #  with some additional values we can ignore) in the register
I               # Take the input-list
 Σ              # Sort it by:
  ®             #  The list we generated above
   sk           #  Take the 0-indexed indices
     >          #  And increase it by 1 (because apparently 0 is placed at the back,
                #  so '421' would always be at the end)

```

Here is the actual list the first part of the code generates:

```
['421','111','611','666','511','555','411','444','311','333','211','222','111','111','765','654','543','432','321','210','','665','664','663','662','661','656','655','','653','652','651','646','645','644','643','642','641','636','635','634','633','632','631','626','625','624','623','622','621','616','615','614','613','612','','566','565','564','563','562','561','556','','554','553','552','551','546','545','544','','542','541','536','535','534','533','532','531','526','525','524','523','522','521','516','515','514','513','512','','466','465','464','463','462','461','456','455','454','453','452','451','446','445','','443','442','441','436','435','434','433','','431','426','425','424','423','422','','416','415','414','413','412','','366','365','364','363','362','361','356','355','354','353','352','351','346','345','344','343','342','341','336','335','334','','332','331','326','325','324','323','322','','316','315','314','313','312','','266','265','264','263','262','261','256','255','254','253','252','251','246','245','244','243','242','241','236','235','234','233','232','231','226','225','224','223','','221','216','215','214','213','212','','166','165','164','163','162','161','156','155','154','153','152','151','146','145','144','143','142','141','136','135','134','133','132','131','126','125','124','123','122','121','116','115','114','113','112','']

```

Try it online.

As you can see it contains empty items; numbers like `765` or `210`; and numbers in the range `[216, 112]`. But we can all ignore these, because the items we want to actually sort are in the correct order.

---

## Original 76 bytes solution:

```
Σ•X˜„Éε´õñ€9Ú ù?ä0₅9úd5àPÎøŒccuĆYÑ,o¾eíË¿¼À8@gID=vÆOΣxjF¨O‡J₃^εR™\èv•667вsk>

```

Try it online ~~or verify all test cases~~ (no test suite because there is still a bug with sort-by with compressed numbers not seeing the closing bracket to stop the sort).

**Explanation:**

```
Σ             # Sort by:
 •...•667в    #  The correctly sorted list of all possible rolls from the challenge
 sk           #  Take the 0-indexed indices
   >          #  And increase it by 1 (because apparently 0 is placed at the back,
              #  so '421' would always be at the end)

```

**Explanation** `•X˜„Éε´õñ€9Ú ù?ä0₅9úd5àPÎøŒccuĆYÑ,o¾eíË¿¼À8@gID=vÆOΣxjF¨O‡J₃^εR™\èv•667в`**:**

Everything between the two  is a compressed number that is generated with the following program:

```
Z>β 255B

```

Try it online.

* `Z>`: Take the max of the list + 1 (`667` in this case)
* `β`: Convert the list from Base-`667` to a single number
* `255B`: And convert that single number to base `255` (using 05AB1E's code page), so we have our compressed number.

By using `667в` it converts this compressed number back to the original list.
> 2 votes

# Answer
# JavaScript (ES7), 96 bytes

```
d=>d.sort((a,b,g=(n,[x,y,z]=n)=>n**=n-421?y*z-1?x-y|y-z?~y%x|~z%y?1:2:3:x-1?3.1:5:5)=>g(b)-g(a))

```

Sorts rolls by adhering closely to the rules of scoring. Expects an array of strings with individual rolls in descending order of value, e.g. `["654"]`

Try it online!

# Explanation

Categories of rolls are raised to the following exponents:

```
421                 5
Three Aces          5
Two Aces            3.1
Three-of-a-Kind     3
Straights           2
Other               1

```

**Ungolfed**

Mentally unwrapping the conditional checks gives me a headache, and I'm certain it can somehow be further golfed....

```
var f =
d => d.sort(
    (
     a, b,
     g = (n, [x, y, z] = n) =>               // destructure rolls, e.g. "321" => ["3","2","1"]
        n **=                                // differentiate scores by raising to the exponent corresponding to its category in the table above
                                             // all conditionals check for a falsy value
            n - 421
                ? y * z - 1                  // ends with "11"
                    ? x - y | y - z          // three-of-a-kind
                        ? ~y % x | ~z % y    // straights, with operators chosen to correctly convert strings to numbers
                            ? 1
                            : 2
                        : 3
                    : x - 1                  // three aces
                        ? 3.1
                        : 5
                : 5
    ) =>
    g(b) - g(a)
)

```
> 2 votes

# Answer
### Javascript, 101 chars, 116 bytes (UTF-8)

```
a=>(r=d=>(i="ƥoɣʚǿȫƛƼķōÓÞʎȟưŁ".indexOf(String.fromCharCode(d)),i<0?700-d:i),a.sort((a,b)=>r(a)-r(b)))

```

Takes an array of numbers representing the rolls like `[ 321, 654 ]`.

Try it online!

**Explanation:**

I took the first 16 of the 56 possible distinct rolls (the ones that don't really follow any order) and I encoded them as a string: `"ƥoɣʚǿȫƛƼķōÓÞʎȟưŁ"`. Each character of this string corresponds the the first 16 possible rolls (`ƥ` is `421`, `o` is `111`, ...). Now for each two elements `a` and `b` of the array we just check their index from the string, if they are included the index is used, otherwise (the index is `-1`) we use the roll number itself (we substract it from `700` to inverse the order of the ones not included, **i.e.** to sort them in a decreasing order).
> 1 votes

# Answer
# Clean, ~~169~~ 102 bytes

All octal escapes are counted as one byte, as the Clean compiler will happily take them that way, but TIO and SE won't because they aren't well-formed UTF-8.

```
import StdEnv
$l=[e\\c<-:"\245\157\143\232\377\53\233\274\67\115\323\336\216\37\260\101\231\230\227\226\225\217\215\214\213\204\203\202\201\171\170\167\156\155\52\51\50\47\40\36\35\25\24\23\n\11\273\272\271\261\257\246\114\113\102\335",e<-l|c==toChar e]

```

Try it online!

Uses the fact that all the dice rolls, as integers modulo 256, are unique.
Conveniently, `Char` is treated (mostly) as a modulo 256 integer.
> 1 votes

# Answer
# Pyth, 48 bytes

```
oxs[]j421T]j7 2_sm+Ld,,ddjT9tS6_m_+LdS3 4.C_S6 3

```

Expects input as a nested array, each element ordered descending. Try it online here, or verify all the test cases at once here.

```
oxs[]j421T]j7 2_sm+Ld,,ddjT9tS6_m_+LdS3 4.C_S6 3)NQ   Final 3 tokens inferred from context
                                                      Implicit: Q=eval(input()), T=10
    ]j421T                                            Convert 421 to base 10, wrap in array -> [[4,2,1]]
          ]j7 2                                       Convert 7 to base 2, wrap in array -> [[1,1,1]]
                 m          tS6                       Map d in [2,3,4,5,6] using:
                      ,dd                               [d,d]
                         jT9                            Convert 10 to base 9 -> [1,1]
                  +Ld,                                  Prepend d to each of the above
               _s                                     Flatten and reverse -> [[6,1,1],[6,6,6]...[2,2,2]]
                                m       4             Map d in [0,1,2,3] using:
                                  +LdS3                 [d+1,d+2,d+3]
                                 _                      Reverse the above
                               _                      Reverse the result -> [[6,5,4]...[3,2,1]]
                                           _S6        [6,5,4,3,2,1]
                                         .C    3      All 3-element combinations of the above, respecting order
  s[                                            )     Wrap the 5 previous sections in an array, concatenate
ox                                               NQ   Order Q using each element's index in the above list

```
> 1 votes

# Answer
# 05AB1E, 24 bytes

```
Σ5βËyθyP‚yнÃ6βyË_y¥PΘy)(

```

Try it online!

Overall algorithm:

```
Σ          )( # sort by the following, in decreasing priority:
 5βË          # 1 for 421, 0 otherwise
 yθyP‚yнÃ6β   # 7 for 111, X for XXX and X11, 0 otherwise
 yË_          # 0 for XXX, 1 otherwise
 y¥PΘ         # 1 for sequences, 0 otherwise
 y            # the roll itself

```

Details:

```
5β          # parse the roll as a base-5 number
  Ë         # are all digits equal? (base-5 421 is 111)

yθ          # last die (equal to the 1st die iff we have XXX)
  yP        # product of dice (equal to the 1st die iff we have X11)
    ‚       # wrap the two in an array
     yнÃ    # keep only those that are equal to the 1st die
        6β  # parse as a base-6 number (111 -> [1, 1] -> 7)

yË          # are all dice equal?
  _         # boolean negation

y¥          # deltas ([a, b, c] -> [b - a, c - b])
  P         # product
   Θ        # 1 if it's equal to 1, 0 otherwise

```
> 1 votes

---
Tags: code-golf, game, sorting
---


title: Brute-force the switchboard

text:
# Question
Title: Brute-force the switchboard
The other day, our team went to an escape room. One of the puzzles involved a board of six mechanical switches where you had to find the correct combination of on and off in order to unlock a box, somewhat like this:

```
-v-v-v-
-v-v-v-

```

Being developers, we decided it would be more efficient to try every single one of 2^6=64 combinations than actually solve the puzzle. So we assigned some poor guy to do some binary counting:

```
-v-v-v-
-v-v-v-

-v-v-v-
-v-v-^-

-v-v-v-
-v-^-v-

-v-v-v-
-v-^-^-

```

and so on.

**The challenge**
Write a program that, given the switches all in off position as a string formatted as above, generates all combinations of on and off in any order.

You can write either a full program or a function. Thus, your program can either take in input through stdin, a file, or as a single string argument, and either return or print the output. If returned, the output may be in a list/array/etc. rather than a single string. If the output is a single string, the boards should be separated by newlines (trailing newlines are allowed.)

The input strings will match the regex `r'((-v)+-)(\n(-v)+-)*'` and represent one board with all switches off. This means no zero case, and switches are left-aligned. Each row might not have the same number of switches.

Each output board should be of the exact same format as the input, except that the v's may be replaced by ^'s as required. The output boards can be separated by any number of newlines.

Since runtime is naturally O(2^n) in the number of switches, your code will not be tested on any more than 10 switches in any arrangement.

This is code-golf, so shortest code in number of bytes wins.

**Sample inputs and outputs**

Input:

```
-v-

```

Possible output:

```
-v-
-^-

```

Input:

```
-v-
-v-

```

Possible output:

```
-^-
-^-
-^-
-v-

-v-
-^-

-v-
-v-

```

Since it's extremely tedious to check your answer for bigger numbers of switches, here's a Python script as a sanity check tool. (I've included a currently commented-out snippet to generate expected output from a given input file in case you want more test cases.) It's quite a bit less flexible in terms of input and output than the spec, unfortunately; put the input string in a file named 'input' and the newline-separated output (sorry, no list formatting) in a file named 'output' in the same directory and run `python3 sanitycheck.py`.

# Answer
# Haskell, ~~25~~ ~~24~~ ~~23~~ 17 bytes

```
mapM$min"^v".pure

```

Try it online!

-1 byte thanks to @H.PWiz

-1 byte thanks to @nimi

Returns a list of strings. The TIO has 2 extra bytes for the function declaration - I've seen other people leave it off when they write the function pointfree so I'm doing the same unless told otherwise.

# Previous Answer (25 bytes)

```
g 'v'="v^"
g x=[x]
mapM g

```

The explanations are all for the previous answer, which works pretty much the same way, except I inlined the definition of `g`. The way `g` works now is by using lexical comparison to substitute `^v` for `v` and keep everything else the same.

Interestingly, this works for arbitrary switchboards:

```
>>> mapM g "-----^-----"
  ["-----v-----", "-----^-----"]

```

# Explanation (Short)

```
g 'v'="v^" -- for 'v', choose between 'v' or '^'
g x=[x]    -- for any other character, choose just that character
mapM g     -- find all ways to choose characters using g on the given input

```

# Explanation (Long)

`mapM` is a pretty scary function for those not familiar with Haskell. But it's not hard to understand in this context. By making it act on `String`s (which in Haskell are lists of characters), I've specialized it to its definition for lists. So in this context, its type signature is

```
mapM :: (a -> [b]) -> [a] -> [[b]]
--      ^^^^^^^^^^                  arg 1: a function from any a to a list of b
--                    ^^^           arg 2: a list of a
--                           ^^^^^ return: a list of list of b

```

It is actually even more specialized in my usage of it - `a` and `b` are both `Char` \- so we can see the type signature as

```
mapM :: (Char -> String) -> String -> [String]

```

Let's quickly look at what `g` does before explaining how `mapM` works.

```
g :: Char -> String
g 'v' = "v^"
g  x  = [x]

```

`g` uses pattern matching to convert the `Char 'v'` into the string `"v^"`; everything else gets converted to a singleton string (remember, strings are just lists of `Char`s, so we can put `x` in a singleton list). Testing on the REPL, we find this is the case

```
>>> g 'a'
  "a"
>>> g 'b'
  "b"
>>> g 'v'
  "v^"

```

Note that `g` has the right type to be an argument of `mapM` (unsurprisingly!).

We'll explore how `mapM` works by giving it `g` and the argument

```
"-v-\n-v-"

```

as input.

`mapM` first maps `g` over the `String`, and because `g` converts `Char`s to `Strings`, this gives us a list of `Strings`

```
["-", "v^", "-", "\n", "-", "v^", "-"]

```

While this is the correct output type, `mapM` does slightly more. You can think of it as forming all `String`s that you could create from this list if you had to pick a single character from each `String` in it (in order).

So for the first element, you have no choice other than to pick the `Char '-'`. For the second element, you can choose between `'v'` and `'^'`, so on and so forth.

It's roughly equivalent to this python code:

```
result = []
for x1 in "-":
  for x2 in "v^":
    for x3 in "-":
      ...
        result.append(''.join([x1, x2, x3, x4, x5, x6, x7]))

```

Except that since Haskell separates between `Char`s and `String`s, when it puts the `Char`s into a list, it doesn't need to `join` them.

So the final output is

```
["-v-\n-v-", "-v-\n-^", "-^-\n-v-", "-^-\n-^-"]

```

as desired.
> 23 votes

# Answer
# Jelly, 7 bytes

```
«Ƭ€”^Œp

```

Try it online!

Output is a list of Jelly strings.

Explanation:

```
«Ƭ€”^Œp  Arguments: 1
«Ƭ€”^    Dyad-nilad pair
  €       Map over left argument
 Ƭ         Apply repeatedly until a result that has previously been seen is seen
           again, return original and intermediate results
«           Dyad: Minimum of arguments
   ”^     Nilad: Literal: '^'
         Note: 'v' is the only character that is greater than '^' and can
         appear in the input, so, while for every character c other than 'v'
         this operation returns [c], for 'v' it returns ['v', '^']. In this way,
         duplicates are never going to appear in the output.
     Œp  Monad: Cartesian product of elements

```
> 9 votes

# Answer
# Perl 6, 32 bytes

```
{[X~] .comb».&{$_,('^'if /v/)}}

```

Try it online!

* `.comb` splits the string into characters.
* `».&{...}` maps the characters according to the function between the braces.
* `$_, ('^' if /v/)` produces a list of alternates for each character. Only `v` has an alternate: `^`.
* `[X~]` reduces that list with the string-concatenation cross-product operator `X~`.
> 9 votes

# Answer
# Perl 5, 29 bytes

```
sub{glob"\Q@_"=~s/v/{v,^}/gr}

```

Try it online!

My first submission!

---

Normally, Perl 5 golfers submit programs instead of functions to save from having to include `sub{}` at a minimum. But they have to add `say`, `say␠`, `say for` or `say for␠` in exchange.

By going the sub approach, I could shorten

```
say for glob"\Q$_"=~s/v/{v,^}/gr        # Perl 5, -0n, 32 bytes

```

to

```
sub{glob"\Q@_"=~s/v/{v,^}/gr}           # Perl 5, 29 bytes

```

---

The explanation is quite simple. Perl 5 has a builtin `glob` operator which accepts a shell-like glob pattern which can be used to generate lists of file names (e.g. `foo*.txt`) or list of strings (e.g. `{a,b,c}`). The catch is that the newline needs to be escaped, which I've done using `quotemeta` (as `\Q`).
> 6 votes

# Answer
# K (ngn/k), ~~27~~ 25 bytes

```
{(?,/,/:\:)/x,'"^"/"v"\x}

```

Try it online!

`"^"/"v"\` replace `"v"` with `"^"`

`x,'` zip with the original chars

`(?,/,/:\:)/` uniq cartesian product over
> 4 votes

# Answer
# APL (Dyalog Classic), ~~21 17~~ 15 bytes

```
⊃⊢∘.,.∪'v'⎕r'^'

```

Try it online!

similar to my k solution

returns an n-dimensional array of strings (n = number of switches)

in easier to explain form: `⊃(∘.,⌿ ⊢ ∪¨ 'v'⎕r'^')`

`'v'⎕r'^'` replace `v`s with `^`s

`⊢ ∪¨`... unions with each of the original characters. it's a vector of strings of length 1 or 2

`∘.,⌿` cartesian product reduction

disclose

to get to the fully golfed version we follow the pattern `f⌿ A g¨ B` -\> `A f.g B`:

`∘.,⌿ ⊢ ∪¨ 'v'⎕r'^'` -\> `⊢ ∘.,.∪ 'v'⎕r'^'`

as a side effect the parentheses are no longer needed
> 4 votes

# Answer
# Java, 202 197 189 191 bytes

Yes, it's a comparatively verbose language, but that's what I consider as classical golfing:

```
import java.util.function.Function;

public class SwitchBored
{
    public static void main(String[] args)
    {
        Function<String, String> f = s->{byte i,j,k,m=1,u='^',d='v',a[]=(s+"\n\n").getBytes();for(i=0,s="";i<m;i++,s+=new String(a))for(j=0,k=0;k<a.length;k++){if(a[k]==d||a[k]==u){a[k]=(i&1<<j++)!=0?u:d;m<<=i>0?0:1;}}return s;};

        //System.out.println(f.apply("-v-"));
        System.out.println(f.apply("-v-v-v-\n-v-v-v-"));
        //System.out.println(f.apply("-v-v-v-\n-v-v-"));
        //System.out.println(f.apply("-v-v-v-v-v-\n-v-"));
        //System.out.println(f.apply("-v-v-v-v-v-\n-v-v-v-v-v-"));
    }
}

```

I thought that a "simple" way of dealing with the line breaks that are necessary to achieve to proper layout was to actually re-use the original input character array, and only fill it with `'v'`s and `'^'`s at the appropriate positions.

*Updates:*

It turned out that *not* storing the positions allows ditching the `int` and array variable declarations (at the cost of checking each position of the array whether it contains an `v` or `^` on the fly), saving 5 bytes.

Another 8 bytes saved by computing the upper limit `(1<<numberOfSwitches)` more compactly.

According to the rule mentioned in the comment, function declaration should be counted, so now it's a lambda...
> 3 votes

# Answer
# , 42 bytes

```
]`('v'I.@e.~[)`[}"1'v^'{~2#:@i.@^1#.e.&'v'

```

Try it online!

## explanation

```
]`('v' I.@e.~ [)`[}"1 ('v^' {~ 2 #:@i.@^ 1 #. e.&'v')

```

Let take

```
-v-
-v-

```

as our example input.

* `('v^' {~ 2 #:@i.@^ 1 #. e.&'v')` creates all possible combos of just the switches, ignoring the input format. for our example it produces:

```
vv
v^
^v
^^

```

+ `1 #. e.&'v'` counts the numbers of `v`s in the input.
    + `2 #:@i.@^` raises 2 to that power, produces the integers from 0 to *that* number `i.`, and converts them to binary `#:`
    + `'v^' {~` changes to binary digits to `v` and `^`
* `]`('v' I.@e.~ [)`[}"1` amends the original input, producing one copy of it for each row of the result described in the previous step (ie, all possible `v`/`^` combos). In each copy the `v` of the original input are replaced with one possible sequence of `v`/`^`.
> 3 votes

# Answer
# C (gcc), ~~75 74~~ 70 bytes

-5 byte thanks to @ceilingcat

```
*b=0;f(char*s){b=b?b:s;*s?f(s+1),*s>46?*s=94,f(s+1),*s='v':0:puts(b);}

```

Try it online!

requires the memory `s` points to to be writable
> 3 votes

# Answer
# , ~~41 40~~ 24 bytes

```
[:>@,@{<@(,'^'$~'v'=])"0

```

Try it online!
> 3 votes

# Answer
# Python 2, 87 bytes

```
def f(s):i=s.find('v');return(i>=0and f(s[:i].replace('^','v')+'^'+s[i+1:])+'\n'or'')+s

```

Try it online!

A non-regex approach.
> 3 votes

# Answer
# Python 3.8 (pre-release), ~~129 117 116 110~~ 106 bytes

-10 bytes thanks to @Chas Brown

```
f=lambda s:{s.replace('v','{}').format(*['v^'[c<'1']for c in bin(x+i)[::-1]])for i in range(x:=1<<len(s))}

```

Try it online!
> 3 votes

# Answer
# C (gcc), 102 bytes

```
i,j,l;f(char*s){for(l=j=0;l++<1<<j;puts(""))for(i=j=0;s[i];i++)putchar(s[i]>64?l&1<<j++?118:94:s[i]);}

```

Try it online!
> 2 votes

# Answer
# K4, 44 bytes

**Solution:**

```
-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2};

```

**Examples:**

```
q)k)-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2}"-v-";
-v-
-^-

q)k)-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2}"-v-\n-v-";
-v-
-v-
-v-
-^-
-^-
-v-
-^-
-^-

q)k)-1{@[x;&w;:;]@/:"v^"@a\:'!*/a:(+/w:"v"=x)#2}"-v-v-\n-v-v-v-\n-v-";
-v-v-
-v-v-v-
-v-
-v-v-
-v-v-v-
-^-
-v-v-
-v-v-^-
-v-
-v-v-
-v-v-^-
-^-
-v-v-
-v-^-v-
-v-
-v-v-
-v-^-v-
-^-
-v-v-
-v-^-^-
-v-
-v-v-
-v-^-^-
-^-
-v-v-
-^-v-v-
-v-
-v-v-
-^-v-v-
-^-
-v-v-
-^-v-^-
-v-
-v-v-
-^-v-^-
-^-
-v-v-
-^-^-v-
-v-
-v-v-
-^-^-v-
-^-
-v-v-
-^-^-^-
-v-
-v-v-
-^-^-^-
-^-
-v-^-
-v-v-v-
-v-
-v-^-
-v-v-v-
-^-
-v-^-
-v-v-^-
-v-
-v-^-
-v-v-^-
-^-
-v-^-
-v-^-v-
-v-
-v-^-
-v-^-v-
-^-
-v-^-
-v-^-^-
-v-
-v-^-
-v-^-^-
-^-
-v-^-
-^-v-v-
-v-
-v-^-
-^-v-v-
-^-
-v-^-
-^-v-^-
-v-
-v-^-
-^-v-^-
-^-
-v-^-
-^-^-v-
-v-
-v-^-
-^-^-v-
-^-
-v-^-
-^-^-^-
-v-
-v-^-
-^-^-^-
-^-
-^-v-
-v-v-v-
-v-
-^-v-
-v-v-v-
-^-
-^-v-
-v-v-^-
-v-
-^-v-
-v-v-^-
-^-
-^-v-
-v-^-v-
-v-
-^-v-
-v-^-v-
-^-
-^-v-
-v-^-^-
-v-
-^-v-
-v-^-^-
-^-
-^-v-
-^-v-v-
-v-
-^-v-
-^-v-v-
-^-
-^-v-
-^-v-^-
-v-
-^-v-
-^-v-^-
-^-
-^-v-
-^-^-v-
-v-
-^-v-
-^-^-v-
-^-
-^-v-
-^-^-^-
-v-
-^-v-
-^-^-^-
-^-
-^-^-
-v-v-v-
-v-
-^-^-
-v-v-v-
-^-
-^-^-
-v-v-^-
-v-
-^-^-
-v-v-^-
-^-
-^-^-
-v-^-v-
-v-
-^-^-
-v-^-v-
-^-
-^-^-
-v-^-^-
-v-
-^-^-
-v-^-^-
-^-
-^-^-
-^-v-v-
-v-
-^-^-
-^-v-v-
-^-
-^-^-
-^-v-^-
-v-
-^-^-
-^-v-^-
-^-
-^-^-
-^-^-v-
-v-
-^-^-
-^-^-v-
-^-
-^-^-
-^-^-^-
-v-
-^-^-
-^-^-^-
-^-

```

**Explanation:**

In-place replacement of `"^"`. Determine number of combinations of switches (e.g. 2^n), count up in binary, replace switches...

```
-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2}; / the solution
-1                                         ; / print to STDOUT, swallow -1
  {                                       }  / lambda taking implicit x
                                        #2   / take 2
                             (         )     / do this together
                                  "v"=x      / does input = "v" ?
                                w:           / save as w
                              +/             / sum up
                           a:                / save as a
                         */                  / product
                        !                    / range 0..n
                    a\:'                     / convert each to base-2
               "v^"@                         / index into "v^"
             @'                              / apply each
   @[x;&w;:;]                                / apply assignment to x at indexes where w is true

```
> 2 votes

# Answer
# , 116 bytes

```
function(x,u=utf8ToInt(x))apply(expand.grid(rep(list(c(118,94)),sum(u>45))),1,function(i)intToUtf8(`[<-`(u,u>45,i)))

```

Try it online!

Function returning a vector of newline separated boards
> 2 votes

# Answer
# JavaScript, 88 bytes

```
s=>(g=n=>n--?g(n)+`
`+s.replace(/v/g,_=>'v^'[i=n&1,n>>=1,i]):'')(2**~-s.split`v`.length)

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 29 bytes

```
T`¶v`;#
+%1`#
v$'¶$`^
%`;|$
¶

```

Try it online! Explanation:

```
T`¶v`;#

```

Change the newlines into `;`s and the `v`s into `#` markers.

```
+%1`#

```

Replace the `#`s one at a time from left to right.

```
v$'¶$`^

```

Change each line into two lines, one with the `#` replaced with a `v`, one with it replaced with a `^`.

```
%`;|$
¶

```

Change the `;`s back into newlines and space the results apart.
> 1 votes

# Answer
# Perl 5 `-0`, 51 bytes

```
$_=<>;s/\s/P/g;s/v/{v,^}/g;say s/P|$/\n/gr for glob

```

Try it online!
> 1 votes

# Answer
# JavaScript (Node.js), ~~80 73~~ 68 bytes

```
f=([x,...y],g=c=>f(y).map(z=>c+z))=>x?g(x).concat(x>'a'?g`^`:[]):[y]

```

Try it online!
> 1 votes

# Answer
# Python 3 \- construct, 203 bytes

```
def f(a):
 b=[0]
 for l in a.split():b+=[b[-1]+l.count('v')]
 return'\n'.join(''.join(f"{k:b}".zfill(b[-1])[x:y]+'-\n'for x,y in zip(b,b[1:]))for k in range(2**b[-1])).replace('0','-v').replace('1','-^')

```

Try it online!

First try, not very small but works. There is no elegant string replacement in Python...

The First loop builts a mapping of lines to bit indices, i.e. for each line, the index of the first bit in a bit counter is stored. This is used for indexing the bit counter in the next loop.

The Second loop runs a binary counter, extracts the bits for each line and iteration and joins them. After joining everything together, it is translated back to the switch map format, using string replacement.

I guess, there is a more elegant way by reusing the input string instead of rebuilding it over and over again.

*Edit: inspired by the Python 3.8 answer, here is a much shorter replacing version*

# Python 3 \- replace, 123 bytes

```
def f(a):r=range;n=a.count('v');return'\n'.join(a.replace('v','{}').format(*('v^'[k&2**i>0]for i in r(n)))for k in r(2**n))

```

Try it online!
> 1 votes

# Answer
# Ruby, 64 bytes

Returns an array. Gets numbers from \\$1\\$ to \\$2^v\\$ (where \\$v\\$ is the number of "v" in the input) and flips switches based on the \\$v\\$ least significant bits. This allows us to save a byte over iterating from \\$0\\$ to \\$2^v-1\\$, because the \\$v\\$ least significant bits in \\$2^v\\$ are all zero.

In Ruby, `i[j]` returns the `j`th bit of `i` starting from the least significant bit, aka it is equivalent to `(i>>j)&1`.

```
->s{(1..2**s.count(?v)).map{|i|j=-1;s.gsub(/v/){'v^'[i[j+=1]]}}}

```

Try it online!
> 0 votes

# Answer
# Charcoal, 28 bytes

```
⪫ＥＸ²№θv⭆θ⎇⁼λv§v^÷ιＸ²№…θμvλ¶¶

```

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

```
   ²                            Literal 2
  Ｘ                             Raised to power
    №                           Count of
      v                         Literal `v`
     θ                          In input string
 Ｅ                              Map over implicit range
        θ                       Input string
       ⭆                        Map over characters and join
           λ                    Current character
          ⁼                     Equal to
            v                   Literal `v`
         ⎇                      Then
              v^                Literal `v^`
             §                  Circularly indexed by
                 ι              Outer index
                ÷               Integer divided by
                   ²            Literal 2
                  Ｘ             Raised to power
                    №           Count of
                        v       Literal `v`
                      θ         In input string
                     …          Truncated to length
                       μ        Inner index
                         λ      Else current character
⪫                         ¶¶    Join with newlines
                                Implicitly print

```
> 0 votes

# Answer
# PHP, 93 bytes

```
for(;$j<1<<$x;$j+=print$s)for($x=0,$s=$argv[1];$i=strpos($s,v,$i+1);$s[$i]=$j&1<<$x++?'^':v);

```

Try it online!

Standalone program, input via command line.

Loop the number of possible permutations of the input string based on the number of `v`'s. While counting up in binary, replace each binary `1` with a `^` and each binary `0` with a `v` in the input string.
> 0 votes

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


title: Square Root Distance from Integers

text:
# Question
Title: Square Root Distance from Integers
Given a decimal number `k`, find the smallest integer `n` such that the square root of `n` is within `k` of an integer. However, the distance should be nonzero - `n` cannot be a perfect square.

Given `k`, a decimal number or a fraction (whichever is easier for you), such that `0 < k < 1`, output the smallest positive integer `n` such that the difference between the square root of `n` and the closest integer to the square root of `n` is less than or equal to `k` but nonzero.

If `i` is the closest integer to the square root of `n`, you are looking for the first `n` where `0 < |i - sqrt(n)| <= k`.

# Rules

* You cannot use a language's insufficient implementation of non-integer numbers to trivialize the problem.
* Otherwise, you can assume that `k` will not cause problems with, for example, floating point rounding.

# Test Cases

```
.9         > 2
.5         > 2
.4         > 3
.3         > 3
.25        > 5
.2         > 8
.1         > 26
.05        > 101
.03        > 288
.01        > 2501
.005       > 10001
.003       > 27888
.001       > 250001
.0005      > 1000001
.0003      > 2778888
.0001      > 25000001
.0314159   > 255
.00314159  > 25599
.000314159 > 2534463

```

Comma separated test case inputs:

```
0.9, 0.5, 0.4, 0.3, 0.25, 0.2, 0.1, 0.05, 0.03, 0.01, 0.005, 0.003, 0.001, 0.0005, 0.0003, 0.0001, 0.0314159, 0.00314159, 0.000314159

```

This is , so shortest answer in bytes wins.

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

```
Min[⌈.5/#+{-#,#}/2⌉^2+{1,-1}]&

```

Try it online!

### Explanation

The result must be of the form \\$m^2 \pm 1\\$ for some \\$m \in \mathbb{N}\\$. Solving the inequations \\$\sqrt{m^2+1} - m \le k\\$ and \\$m - \sqrt{m^2-1} \le k\\$, we get \\$m \ge \frac{1-k^2}{2k}\\$ and \\$m \ge \frac{1+k^2}{2k}\\$ respectively. So the result is \\$\operatorname{min}\left({\left\lceil \frac{1-k^2}{2k} \right\rceil}^2+1, {\left\lceil \frac{1+k^2}{2k} \right\rceil}^2-1\right)\\$.

# Answer
> 8 votes
# Python, 42 bytes

```
lambda k:((k-1/k)//2)**2+1-2*(k<1/k%2<2-k)

```

Try it online!

Based on alephalpha's formula, explicitly checking if we're in the \\$m^2-1\\$ or \\$m^2+1\\$ case via the condition `k<1/k%2<2-k`.

Python 3.8 can save a byte with an inline assignment.

**Python 3.8, 41 bytes**

```
lambda k:((a:=k-1/k)//2)**2-1+2*(a/2%1<k)

```

Try it online!

These beat my recursive solution:

**50 bytes**

```
f=lambda k,x=1:k>.5-abs(x**.5%1-.5)>0 or-~f(k,x+1)

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 16 bytes

```
nD(‚>I·/înTS·<-ß

```

Port of *@alephalpha*'s Mathematica answer, with inspiration from *@Sok*'s Pyth answer, so make sure to upvote both of them!

Try it online or verify all test cases.

**Explanation:**

```
n                 # Take the square of the (implicit) input
                  #  i.e. 0.05 → 0.0025
 D(‚              # Pair it with its negative
                  #  i.e. 0.0025 → [0.0025,-0.0025]
    >             # Increment both by 1
                  #  i.e. [0.0025,-0.0025] → [1.0025,0.9975]
     I·           # Push the input doubled
                  #  i.e. 0.05 → 0.1
       /          # Divide both numbers with this doubled input
                  #  i.e. [1.0025,0.9975] / 0.1 → [10.025,9.975]
        î         # Round both up
                  #  i.e. [10.025,9.975] → [11.0,10.0]
         n        # Take the square of those
                  #  i.e. [11.0,10.0] → [121.0,100.0]
          TS      # Push [1,0]
            ·     # Double both to [2,0]
             <    # Decrease both by 1 to [1,-1]
              -   # Decrease the earlier numbers by this
                  #  i.e. [121.0,100.0] - [1,-1] → [120.0,101.0]
               ß  # Pop and push the minimum of the two
                  #  i.e. [120.0,101.0] → 101.0
                  # (which is output implicitly)

```

# Answer
> 3 votes
# JavaScript (ES7),  ~~51~~  50 bytes

```
f=(k,n)=>!(d=(s=n**.5)+~(s-.5))|d*d>k*k?f(k,-~n):n

```

Try it online!

(fails for the test cases that require too much recursion)

---

# Non-recursive version,  ~~57~~  56 bytes

```
k=>{for(n=1;!(d=(s=++n**.5)+~(s-.5))|d*d>k*k;);return n}

```

Try it online!

Or for **55 bytes**:

```
k=>eval(`for(n=1;!(d=(s=++n**.5)+~(s-.5))|d*d>k*k;);n`)

```

Try it online!

(but this one is significantly slower)

# Answer
> 3 votes
# Japt, ~~18~~ 16 bytes

-2 bytes from Shaggy

```
_=¬u1)©U>½-½aZ}a

```

Try it online!

# Answer
> 3 votes
# , ~~39~~ 29 bytes

```
[:<./_1 1++:*:@>.@%~1+(,-)@*:

```

NB. This shorter version simply uses @alephalpha's formula.

Try it online!

## 39 bytes, original, brute force

```
2(>:@])^:((<+.0=])(<.-.)@(-<.)@%:)^:_~]

```

Try it online!

Handles all test cases

# Answer
> 3 votes
# Pyth, ~~22~~ 21 bytes

```
hSm-^.Ech*d^Q2yQ2d_B1

```

Try it online here, or verify all the test cases at once here.

Another port of alephalpha's excellent answer, make sure to give them an upvote!

```
hSm-^.Ech*d^Q2yQ2d_B1   Implicit: Q=eval(input())
                  _B1   [1,-1]
  m                     Map each element of the above, as d, using:
           ^Q2            Q^2
         *d               Multiply by d
        h                 Increment
       c      yQ          Divide by (2 * Q)
     .E                   Round up
    ^           2         Square
   -             d        Subtract d
 S                      Sort
h                       Take first element, implicit print

```

*Edit: Saved a byte, thanks to Kevin Cruijssen*

# Answer
> 3 votes
# Perl 6, ~~34~~ ~~33~~ 29 bytes

*-1 byte thanks to Grimy*

```
{+(1...$_>*.sqrt*(1|-1)%1>0)}

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~89~~ ~~85~~ 71 bytes

```
k=>{double n=2,p;for(;!((p=Math.Sqrt(n)%1)>0&p<k|1-p<k);n++);return n;}

```

Try it online!

-4 bytes thanks to Kevin Cruijssen!

# Answer
> 2 votes
# APL (Dyalog Unicode), 27 bytesSBCS

```
⌊/0~⍨¯1 1+2*⍨∘⌈+⍨÷⍨1(+,-)×⍨

```

Try it online!

Monadic train taking one argument. This is a port of alephalpha's answer.

### How:

```
⌊/0~⍨¯1 1+2*⍨∘⌈+⍨÷⍨1(+,-)×⍨ ⍝ Monadic train

                         ×⍨ ⍝ Square of the argument
                   1(+,-)   ⍝ 1 ± that (returns 1+k^2, 1-k^2)
                 ÷⍨         ⍝ divided by
               +⍨           ⍝ twice the argument
             ∘⌈             ⍝ Ceiling
          2*⍨               ⍝ Squared
     ¯1 1+                  ⍝ -1 to the first, +1 to the second
  0~⍨                       ⍝ Removing the zeroes
⌊/                          ⍝ Return the smallest

```

# Answer
> 2 votes
# Java (JDK), ~~73~~ 70 bytes

```
k->{double i=1,j;for(;(j=Math.sqrt(++i)%1)==0|j>=k&1-j>=k;);return i;}

```

Try it online!

`-3 bytes` thanks to @ceilingcat

# Answer
> 1 votes
# Java 8, 85 bytes

```
n->{double i=1,p;for(;Math.abs(Math.round(p=Math.sqrt(i))-p)>n|p%1==0;i++);return i;}

```

Port of *EmbodimentOfIgnorance*'s C# .NET answer.

Try it online.

The `Math.round` can alternatively be this, but unfortunately it's the same byte-count:

```
n->{double i=1,p;for(;Math.abs((int)((p=Math.sqrt(i))+.5)-p)>n|p%1==0;i++);return i;}

```

Try it online.

# Answer
> 1 votes
# MathGolf, 16 bytes

```
²_b*α)½╠ü²1bαm,╓

```

Try it online!

Not a huge fan of this solution. It is a port of the 05AB1E solution, which is based on the same formula most answers are using.

## Explanation

```
²                  pop a : push(a*a)
 _                 duplicate TOS
  b                push -1
   *               pop a, b : push(a*b)
    α              wrap last two elements in array
     )             increment
      ½            halve
       ╠           pop a, b, push b/a
        ü          ceiling with implicit map
         ²         pop a : push(a*a)
          1        push 1
           b       push -1
            α      wrap last two elements in array
             m     explicit map
              ,    pop a, b, push b-a
               ╓   min of list

```

# Answer
> 1 votes
# Forth (gforth), 76 bytes

```
: f 1 begin 1+ dup s>f fsqrt fdup fround f- fabs fdup f0> fover f< * until ;

```

Try it online!

### Explanation

Starts a counter at 1 and Increments it in a loop. Each iteration it checks if the absolute value of the counter's square root - the closest integer is less than k

### Code Explanation

```
: f                   \ start a new word definition
  1                   \ place a counter on the stack, start it at 1
  begin               \ start and indefinite loop
    1+                \ add 1 to the counter
    dup s>f           \ convert a copy of the counter to a float
    fsqrt             \ get the square root of the counter
    fdup fround f-    \ get the difference between the square root and the next closes integer
    fabs fdup         \ get the absolute value of the result and duplicate
    f0>               \ check if the result is greater than 0 (not perfect square)
    fover f<          \ bring k to the top of the float stack and check if the sqrt is less than k
    *                 \ multiply the two results (shorter "and" in this case)
  until               \ end loop if result ("and" of both conditions) is true
;                     \ end word definition

```

# Answer
> 1 votes
# Jelly, 13 bytes

I have not managed to get anything terser than the same approach as alephalpha
\- go upvote his Mathematica answer!

```
²;N$‘÷ḤĊ²_Ø+Ṃ

```

**Try it online!**

### How?

```
²;N$‘÷ḤĊ²_Ø+Ṃ - Link: number, n (in (0,1))
²             - square n        -> n²
   $          - last two links as a monad:
  N           -   negate        -> -(n²)
 ;            -   concatenate   -> [n², -(n²)]
    ‘         - increment       -> [1+n², 1-(n²)]
      Ḥ       - double n        -> 2n
     ÷        - divide          -> [(1+n²)/n/2, (1-(n²))/n/2]
       Ċ      - ceiling         -> [⌈(1+n²)/n/2⌉, ⌈(1-(n²))/n/2⌉]
        ²     - square          -> [⌈(1+n²)/n/2⌉², ⌈(1-(n²))/n/2⌉²]
          Ø+  - literal         -> [1,-1]
         _    - subtract        -> [⌈(1+n²)/n/2⌉²-1, ⌈(1-(n²))/n/2⌉²+1]
            Ṃ - minimum         -> min(⌈(1+n²)/n/2⌉²-1, ⌈(1-(n²))/n/2⌉²+1)

```

# Answer
> 1 votes
# Japt, 14 bytes

```
_=¬aZ¬r¹©U¨Z}a

```

Try it

```
_=¬aZ¬r¹©U¨Z}a     :Implicit input of integer U
_                  :Function taking an integer Z as an argument
 =                 :  Reassign to Z
  ¬                :    Square root of Z
   a               :    Absolute difference with
    Z¬             :      Square root of Z
      r            :      Round to the nearest integer
       ¹           :  End reassignment
        ©          :  Logical AND with
         U¨Z       :  U greater than or equal to Z
            }      :End function
             a     :Return the first integer that returns true when passed through that function

```

# Answer
> 1 votes
# Perl 5 `-p`, 42 bytes

```
$t=sqrt++$\while($p=abs$t-int$t)>$_||!$p}{

```

Try it online!

---
Tags: code-golf, number, integer
---


title: Round Me, Help Me

text:
# Question
Title: Round Me, Help Me
Given an input `n`, your program or function must output the smallest positive integer `k` such that `n` rounded to the nearest multiple of `k` is greater than `n`.

### Example.

Given an input `20`, the output value should be `3`:

* The nearest multiple of `1` is `20`, which is **not** greater than `20`.
* The nearest multiple of `2` is `20`, which is **not** greater than `20`.
* The nearest multiple of `3` is `21`, which **is** greater than `20`, so it is output.

### Test Cases

```
#Input  #Output
2       3
4       5
6       4
8       3
10      4
12      7
14      3
16      6
18      4
20      3
22      4
24      5
26      3
28      5
30      4
32      3
34      4
36      8
38      3
40      6
42      4
44      3
46      4
48      5
50      3
52      6
54      4
56      3
58      4
60      7
62      3
64      5
66      4
68      3
70      4
72      11
74      3
76      6
78      4
80      3
82      4
84      5
86      3
88      5
90      4
92      3
94      4
96      7
98      3
1000    6

```

The output given any odd input should be 2.

### Rules

* `n` is a positive integer less than `2^32`
* rounding is performed such that if two multiples of `k` are equally distant from `n`, the greater one is chosen ("round halves up"). In this way, every odd `n` yields an output of `2`.
* This is , so shortest code **in each language** wins.

# Answer
> 12 votes
# Python 3, 48 38 bytes

**Edit:** -10 bytes by using recursion

```
l=lambda x,y=2:y*(x%y>=y/2)or l(x,y+1)

```

Try it online!

# Answer
> 9 votes
# Japt, 6 bytes

```
@<rX}a

```

Try it online!

## Explanation:

```
@    <r X}a
XYZ{U<UrX}a
X              // X = 0; Increments when the condition in between {...} fails
   {     }a    // Return the first integer X where:
    U          //   The input
     <U        //   is less than the input
       rX      //     rounded to the nearest multiple of X

```

# Answer
> 7 votes
# MATL, 13 bytes

```
tQ:yy/Yo*<fX<

```

Try it online! Or verify all inputs from `1` to `1000`.

### Explanation

Consider input `6`.

```
t      % Implicit input. Duplicate
       % STACK: 6, 6
Q:     % Add 1, range
       % STACK: 6, [1 2 3 4 5 6 7]
yy     % Duplicate top two elements
       % STACK: 6, [1 2 3 4 5 6 7], 6, [1 2 3 4 5 6 7]
/      % Divide, element-wise
       % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 1.5 1.2 1 0.8571]
Yo     % Round to closest integer. Halves are rounded up
       % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 2 1 1 1]
*      % Multiply, element-wise
       % STACK: 6, [6 6 6 8 5 6 7]
<      % Less than, element-wise
       % STACK: [0 0 0 1 0 0 1]
f      % Find: indices of nonzeros (1-based)
       % STACK: [4 7]
X<     % Minimum of vector. Implicit display
       % STACK: 4

```

# Answer
> 5 votes
# JavaScript (ES6), ~~28~~ 25 bytes

```
n=>g=x=>n%x>=x/2?x:g(-~x)

```
* 3 bytes saved thanks to Arnauld.

---

## Test it

```
o.innerText=(f=

n=>g=x=>n%x>=x/2?x:g(-~x)

)(i.value=64)();oninput=_=>o.innerText=f(+i.value)()
```

```
<input id=i type=number><pre id=o>
```

Or test all numbers from 1-1000 (Give it a minute to run):

```
f=n=>g=x=>n%x>=x/2?x:g(-~x);[2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,11,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,11,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,13,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,9,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,10,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,11,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,9,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,10,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,9,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,10,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,13,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,13,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,11,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,9,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6].forEach((x,y)=>o.innerText+=`\n-----------------------------\n${(++y+"").padStart(7)}  |${(y=f(y)()+"").padStart(8)}  |  ${x==y}`)
```

```
<pre id=o>  Input  |  Output  |  Pass</pre>
```

# Answer
> 5 votes
# Proton, 33 bytes

```
n=>[x for x:2..n+2if n%x>=x/2][0]

```

Try it online!

# Answer
> 5 votes
# Python 2, 35 bytes

```
f=lambda n,i=1:n%i*2/i or-~f(n,i+1)

```

Try it online!

# Answer
> 4 votes
# Pyth, ~~12~~ 11 bytes

```
hfgy%QTTm+2

```

**Try it here.**

# Answer
> 4 votes
# Proton, 33 bytes

```
x=>[y for y:2..x+2if x%y>=y/2][0]

```

Try it online!

# Answer
> 3 votes
# Jelly, 11 bytes

```
÷R%1<.¬;1TṂ

```

A monadic link taking and returning positive integers.

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

### How?

```
÷R%1<.¬;1TṂ - Link: number, n       e.g. 10
 R          - range(n)               [ 1,2,3     ,4  ,5,6     ,7     ,8   ,9     ,10]
÷           - n divided by           [10,5,3.33..,2.5,2,1.66..,1.42..,1.25,1.11..,1 ]
  %1        - modulo by 1            [ 0,0,0.33..,0.5,0,0.66..,0.42..,0.25,0.11..,0 ]
    <.      - less than 0.5?         [ 1,1,1     ,0  ,1,0     ,1     ,1   ,1     ,1 ]
      ¬     - not                    [ 0,0,0     ,1  ,0,1     ,0     ,0   ,0     ,0 ]
       ;1   - concatenate a 1        [ 0,0,0     ,1  ,0,1     ,0     ,0   ,0     ,0 , 1]
         T  - truthy indices         [            4    ,6                           ,11]
          Ṃ - minimum                4

```

Note: The concatenation of `1` is just to handle the cases where `n` is one of `1` ,`2`, or `4` when the result needs to be `n+1` (`‘R÷@%1<.¬TṂ` would also work).

# Answer
> 3 votes
# Haskell, ~~33~~ 32 bytes

```
f n=[i|i<-[1..],2*mod n i>=i]!!0

```

Try it online!

*Saved one byte thanks to w0lf*

# Answer
> 2 votes
# Dyalog APL, ~~23~~ 22 bytes

```
{⊃x/⍨⍵<x×⌊.5+⍵÷x←⍳1+⍵}

```

Try it online!

# Answer
> 2 votes
# Java 8, 42 bytes

Lambda from `Integer` to `Integer`.

```
n->{for(int f=1;;)if(n%++f*2>=f)return f;}

```

Try It Online

## Acknowledgments

* -1 byte thanks to *Kevin Cruijssen*

# Answer
> 2 votes
# Pyth, 5 bytes

```
fgy%Q

```

Test suite

No rounding builtins, just checking for the first positive integer T, where double the input mod T is greater than or equal to T.

Explanation:

```
fgy%Q
fgy%QTT    Implicit variable introduction.
f          Find the first positive integer T such that the following is truthy:
   %QT     Input % T
  y        Doubled
 g    T    Is greater than or equal to T

```

# Answer
> 2 votes
# x86 Machine Code, 17 bytes

This code implements a basic, iterative solution in the form of a reusable function:

```
31 F6                   xor    esi, esi
46                      inc    esi         ; set ESI (our temp register) to 1

                     Loop:
89 C8                   mov    eax, ecx    ; copy 'n' to EAX for division
46                      inc    esi         ; eagerly increment temp
99                      cdq                ; extend EAX into EDX:EAX
F7 F6                   div    esi         ; divide EDX:EAX by ESI
01 D2                   add    edx, edx    ; multiply remainder by 2
39 F2                   cmp    edx, esi    ; compare remainder*2 to temp
7C F4                   jb     Loop        ; keep looping if remainder*2 < temp

96                      xchg   eax, esi    ; put result into EAX (1 byte shorter than MOV)
C3                      ret

```

The function follows the fastcall calling convention, so that the single parameter (`n`) is passed in the `ECX` register. The return value (`k`) is, per usual, returned in the `EAX` register.

Try it online!

# Answer
> 1 votes
# Perl 5, 24 + 1 (-p) = 25 bytes

```
1while$_%++$k<$k/2;$_=$k

```

Try it online!

Tries each integer `$k` starting at 1 until it finds a remainder that is at least half of `$k`.

# Answer
> 1 votes
# Forth (gforth), 45 bytes

```
: f 1 begin 1+ 2dup mod over 1+ 2/ >= until ;

```

Try it online!

### Code Explanation

```
: f             \ start a new word definition
  1             \ start a counter at 1
  begin         \ start an indefinite loop
    1+          \ add 1 to counter
    2dup mod    \ duplicate input value and counter, get remainder of input/counter
    over 1+ 2/  \ get counter/2 (add 1 to force rounding up)
    >=          \ check if remainder is greater than counter/2
  until         \ end loop if true, otherwise go back to beginning
;               \ end word definition

```

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
∞.ΔIs/Dò‹

```

Try it online!

## Explanation

```
∞.ΔIs/Dò‹ Full code
∞.Δ       Returns the first number for which the following code returns true
             -> stack is [n]
   Is     Push the input and swap the stack -> stack is [input, n]
     /    Divide both of them -> stack is [input/n]
      Dò  Duplicate and round the second -> stack is [input/n, rounded(input/n)]
        ‹ Check if input/n got larger by rounding -> stack is [bool]
             -> if bool is true, abort and return the current number

```

# Answer
> 1 votes
# Rockstar, 681 bytes

```
Thought takes Patience and Control
While Patience is as high as Control
Let Patience be without Control

Give back Patience

Rock takes Art
Love is neverending
Sex is bottomless
Put Thought taking Art & Love into your head
If your head is Sex
Give back Art
Else
Limits are inspiration
Put Art with Limits without your head into the rubbish
Give back the rubbish

Listen to Chance
Questions are unstoppable
Until Questions is Chance
Build Questions up
Put Thought taking Chance, Questions into your mind
Answers are independence (but)
Put Questions over Answers into the world
Put Rock taking the world into the world
If your mind is as big as the world
Say Questions
Break it down

```

You can try rockstar online, but you'll need to copy and paste the code across. It will prompt you for an input number.

I didn't go for lowest byte count , because Rockstar is obviously not made for golfing, so instead I tried to go for Rock 'n' Roll lyrics.

## Explanation:

This is based on the same solution as others (python, java):

```
Iterate up from 2:
if n % iterator >= ceil(n/2)
    return iterator

```

First I need to define modulus and ceiling functions though, which for poetry's sake are called Thought and Rock.

The below is a less poetic version with different variable names, and explanations where the syntax is unclear. Parentheses denote comments.

```
Modulus takes Number and Divisor
While Number is as high as Divisor
Put Number minus Divisor into Number
    (blank line ending While block)
Give back Number (return Number)
    (blank line ending function declaration)
Ceil takes Decimal
Put Modulus taking Decimal, 1 into Remainder
If Remainder is 0
Give back Decimal (return Decimal)
Else
Put Decimal with 1 minus Remainder into Result
Give back Result (return Result)
    (blank line ending if block)
    (blank line ending function declaration)
Listen to Input (Read from STDIN to Input)
Index is 1
Until Index is Input
Build Index up (Increment by 1)
Put Modulus taking Input, Index into LHS
Put Index over 2 into RHS
Put Ceil taking RHS into RHS
If LHS is as big as RHS
Say Index
Break it down (Break from loop)

```

# Answer
> 0 votes
# Jelly, 18 bytes

```
ɓ÷Ḟ,¥Ċ$×ạÐṂ⁸Ṁ>⁸µ1#

```

Try it online!

Full program.

# Answer
> 0 votes
# Swift 3, 51 bytes

```
{n in(2..<n+2).filter{Float(n%$0)>=Float($0)/2}[0]}

```

For some *extremely* bizarre reasons, `[0]` doesn't work online. Here is the online compiler-compatible version (that uses `.first!` instead):

```
{n in(2..<n+2).filter{Float(n%$0)>=Float($0)/2}.first!}

```

**Test Suite (online-compatible).**

# Answer
> 0 votes
# C# (Mono), 39 bytes

```
n=>{int i=1;for(;n%++i*2<i;);return i;}

```

Try it online!

# Answer
> 0 votes
# Stax, 7 bytes

```
ç&╬▼⌐╔ñ

```

Run and debug it

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


title: Fivenum and a little bit

text:
# Question
Title: Fivenum and a little bit
*(a paradox, a paradox, a most ingenious paradox)*

This is the first part of a multipart series inspired by different R functions.

# The Task

Given a dataset \\$D\\$ of positive integers, I need you to compute the 5 number summary of \\$D\\$. However, I'm working on large datasets, so I need your code to be as small as possible, allowing me to store it on my computer.

The five number summary consists of:

* Minimum value
* First quartile (Q1)
* Median / Second quartile (Q2)
* Third quartile (Q3)
* Maximum value

There are several different ways of defining the quartiles, but we will use the one implemented by R:

## Definitions:

* Minimum and maximum: the smallest and largest values, respectively.
* Median: the middle value if \\$D\\$ has an odd number of entries, and the arithmetic mean of the two middle-most values if \\$D\\$ has an even number of entries. Note that this means the median may be a non-integer value. We have had to Compute the Median before.
* First and Third Quartiles: Divide the data into two halves, including the central element in each half if \\$D\\$ has an odd number of entries, and find the median value of each half. The median of the lower half is the First Quartile, and the median of the upper half is the Third Quartile.

## Examples:

\\$D=\[1,2,3,4,5\]\\$. The median is then \\$3\\$, and the lower half is \\$\[1,2,3\]\\$, yielding a first quartile of \\$2\\$, and the upper half is \\$\[3,4,5\]\\$, yielding a third quartile of \\$4\\$.

\\$D=\[1,3,3,4,5,6,7,10\]\\$. The median is \\$4.5\\$, and the lower half is \\$\[1,3,3,4\]\\$, yielding a first quartile of \\$3\\$, and the upper half is \\$\[5,6,7,10\]\\$, yielding a third quartile of \\$6.5\\$.

### Additional rules:

* Input is as an array or your language's nearest equivalent.
* You may assume the array is sorted in either ascending or descending order (but please specify which).
* You may return/print the results in any **consistent** order, and in whichever flexible format you like, but please denote the order and format in your answer.
* Built-in functions equivalent to `fivenum` are allowed, but please also implement your own solution.
* You may **not** assume each of the five numbers will be an integer.
* Explanations are encouraged.
* This is , so shortest answer in each language wins!

## Randomly generated test cases

```
1 1 1 1 1 2 2 2 2 2 3 3 4 4 4 4 4 5 5 5 -> 1 1.5 2.5 4 5
1 2 2 2 4 4 5 5 6 7 7 8 9 9 9 9 9 10 10 10 -> 1 4 7 9 10
2 2 2 6 8 10 15 16 21 22 23 24 26 33 35 38 38 45 46 47 48 -> 2 10 23 38 48
1 2 9 -> 1 1.5 2 5.5 9
1 2 3 3 3 4 9 -> 1 2.5 3 3.5 9
1 1 2 5 7 7 8 8 15 16 18 24 24 26 26 27 27 28 28 28 29 29 39 39 40 45 46 48 48 48 48 49 50 52 60 63 72 73 79 85 86 87 88 90 91 93 94 95 95 97 100 -> 1 25 45 76 100
2 2 4 4 6 8 10 11 13 14 14 15 17 21 23 24 26 27 27 28 28 30 31 33 33 34 36 36 38 38 39 40 41 42 42 43 45 45 47 47 47 47 47 48 48 48 50 51 53 53 55 56 56 56 57 57 58 62 62 63 64 64 65 65 66 67 67 67 68 69 69 71 71 71 74 79 80 81 81 81 82 82 83 83 86 86 86 87 89 94 94 94 95 95 97 98 99 100 100 100 -> 2 33.5 54 76.5 100
1 3 3 4 -> 1 2 3 3.5 4
1 3 3 3 4 -> 1 3 3 3 4
```

# Answer
> 6 votes
# , 7 bytes

```
fivenum

```

Try it online!

Obvious cheeky answer. ;-)

Interestingly, `fivenum(x)` is not equivalent to `summary(x)` even when `x` is numeric, as the quantiles are computed differently: `fivenum` averages at discontinuities, whereas `summary` interpolates. You can force `summary` to behave like `fivenum` with the option `quantile.type`, but this is still longer than

# , 51 bytes

```
function(x)quantile(x,(0:4)/4,t=2+5*!sum(!!x)%%4-3)

```

Try it online!

which computes the quantiles of order 0 (min), 0.25 (Q1), 0.5 (median), 0.75 (Q3) and 1 (max). The `t=2` specifies how quantiles are defined: there are 9 possible types, and the challenge definition corresponds to type 2 in most cases, and to type 7 when \\$n\equiv 3\pmod 4\\$. Honestly, this choice of a definition of quantiles is a bit weird.

Note that the source code of the `fivenum` built-in is very different (and much longer).

# Answer
> 5 votes
# MATL, 18 bytes

```
tno?t.5Xqh]5:q4/Xq

```

Output order is increasing, as in the test cases.

Try it online! Or verify all test cases.

### Explanation

MATL, like MATLAB, computes quantiles using linear interpolation if needed (just as specified in the challenge for the median). To achieve the required behaviour for the first and third quartiles, it suffices to repeat the median if the length of the input is odd. Then the results are just the 0, .25, .5, .75 and 1 quantiles.

```
t       % Implicit input: numeric row array. Duplicate
no      % Length, parity
?       % If not zero (that is, if input length is odd)
  .5    %   Push .5
  Xq    %   .5-quantile: median. For even length it behaves as required
  h     %   Concatenate horizontally
]       % End
5:q     % Push [0 1 2 3 4]
4/      % Divide by 4, element-wise: gives [0 .25 .5 .75 1]
Xq      % [0 .25 .5 .75 1]-quantiles. Implicit display

```

# Answer
> 3 votes
# Jelly, 13 bytes

```
œs2a\;WÆṁ;Ḣ;Ṫ

```

Try it online!

Order: `[Q1, Q3, Q2/med, min, max]`.

# Answer
> 2 votes
# Python 3.8 (pre-release), 66 bytes

```
lambda l:[(l[~-i//4]+l[-~i//4])/2for i in[1,n:=len(l),~n-n,~n,-3]]

```

Try it online!

Input and output are in ascending order.

# Answer
> 1 votes
## Python 3.8, 97 bytes

```
lambda l:[l[0],l[-1]]+[(i[x(i)//2]+i[~x(i)//2])/2for i in(l[:~((x:=len)(l)//2-1)],l,l[x(l)//2:])]

```

This assumes that the input list is sorted in ascending order. `f` is the function to return the 5-number summary.

The 5-number summary is in the order: \\$\\{min, max, Q1, Q2,Q3\\}\\$

I took off a few bytes by taking some hints from FlipTack's answer to Compute the Median.

Try it online!

How does it work?

```
lambda l:
    [l[0],l[-1]] # The minimum and maximum, because l is assumed to be sorted in ascending order
    +[(i[x(i)//2]+i[~x(i)//2])/2 # This line computes the median...
    for i in(l[:~((x:=len)(l)//2-1)],l,l[x(l)//2:])] # ...for each of these lists (the first half, the overall list, and the second half)
    # The (x:=len) is an assignment expression from Python 3.8.
    # It assigns the len function to the variable x but also returns len.
    # Therefore, x can be used as len to save a byte (yes, just one byte)

```

# Answer
> 1 votes
# C (gcc), ~~123~~ ~~121~~ 119 bytes

-2 thanks to ceilingcat.

Assumes a list sorted in ascending order.

Outputs in order: min, Q1, Q2, Q3, max.

```
#define M(K,x)(K[~-x/2]+K[x/2])/2.,
f(L,n,m)int*L;{m=n-n/2;printf("%d %f %f %f %d",*L,M(L,m)M(L,n)M((L+n/2),m)L[n-1]);}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 33 bytes

```
≔⊖ＬθηＩＥ⟦⁰⊘÷η²⊘η⁻η⊘÷η²η⟧⊘⁺§θ⌊ι§θ⌈ι

```

Try it online! Link is to verbose version of code. Outputs in ascending or descending order depending on whether the input is in ascending or descending order. Explanation:

```
≔⊖Ｌθη

```

Get the index of the last element.

```
ＩＥ

```

Map over the elements of the following array and cast the result to string for implicit print on separate lines.

```
⟦⁰⊘÷η²⊘η⁻η⊘÷η²η⟧

```

Calculate the positions of the quartile elements, where an extra `0.5` denotes that the value is the average of two adjacent elements.

```
⊘⁺§θ⌊ι§θ⌈ι

```

Calculate the quartile at each position by taking the average of the values at the floor and ceiling of the position.

# Answer
> 1 votes
# Ruby 2.7-preview1, 59 bytes

A direct ~~ripoff~~ port of xnor's Python answer.

```
->a{[1,n=a.size,~n-n,~n,-3].map{(a[~-@1/4]+a[-~@1/4])/2.0}}

```

Try it online! (one byte longer since TiO is using Ruby 2.5 and doesn't have numbered block parameters e.g. `@1`).

# Answer
> 1 votes
# 05AB1E, 18 bytes

```
2F2äнIR})€ÅmIWsà‚«

```

Output-order is: `[Q1, Q3, Q2, min, max]`.

Try it online or verify all test cases. (I've added a sort `{` for the test suite, so the test cases are easier to verify in the order `[min, Q1, Q2, Q3, max]`.)

**Explanation:**

```
2F                 # Loop 2 times:
  2ä               #  Split the list at the top of the stack into two halves
                   #  (which is the (implicit) input-list in the first iteration)
    н              #  Only leave the first halve
     IR            #  Push the input in reverse
       })          # After the loop: wrap all three lists into a list
         €         # For each of the lists:
          Åm       #  Get the middle/median depending on the parity of the size of the list
            I      # Then push the input-list again
             W     # Get the minimum (without popping)
              s    # Swap to get the input-list again
               à   # Get the maximum (by popping the list)
                ‚  # Pair the min-max together to a pair
                 « # And merge both lists together
                   # (after which the result is output implicitly)

```

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


title: Matchmaker, Matchmaker, make me a match

text:
# Question
Title: Matchmaker, Matchmaker, make me a match
(we won't be finding a `Find` or catching a `tryCatch`, though)

This is part two of a multi-part series of implementing some interesting R functions. Part one can be found here.

# The task:

You are to implement R's `match` function in as few bytes as possible.

## Input:

* `x`, a possibly empty list/array of integers
* `table`, a possibly empty list/array of integers
* `nomatch`, a single integer value
* `incomparables`, a possibly empty list/array of integers

## Output:

* a single array/list of integers `O` of equal length to `x`, where each value `O[i]` represents either:
    + The index `j` of the **first** value in `table` where `table[j]==x[i]`
    + `nomatch`, indicating that no value in `table` is equal to `x[i]` **OR** that `x[i]` is in the list of `incomparables`.

# Test Cases

```
All in the form x, table, nomatch, incomparables -> output
outputs

[], [1,2,3], 0, [5] -> []

[1, 2, 3], [], 0, [5] -> [0, 0, 0]

[9, 4, 3, 6, 3], [9, 8, 7, 6, 5, 4, 3, 2, 1], -1, [4] -> [1, -1, 7, 4, 7]

[8, 6, 7, 5, 3, 0, 9], [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6], 1000, [1] -> [12, 8, 14, 5, 1, 1000, 6]

```

More test cases can be generated as needed.

## Additional rules:

* R has 1-based indices, but a consistent alternative-based indices are acceptable. So you can use indices that start at 3 or 17 or whatever, but this must be consistent, and you must indicate this in your answer.
* If you chosen language has a builtin that does this, please also implement your own solution.
* Explanations are appreciated.

This is , so shortest solution in bytes wins!

# Answer
# , 83 bytes

```
function(x,t,n,i)sapply(x,function(a)c(which(a==t/!rowSums(outer(t,i,`==`))),n)[1])

```

Try it online!

Avoids `match`, `%in%` and `setdiff`.
> 9 votes

# Answer
# Jelly,  ~~10~~  8 bytes

-2 thanks to Erik the Outgolfer

```
,⁷y⁵iⱮ⁶o

```

A full program accepting four command line arguments, `incomparables nomatch table x` which prints a Jelly representation\* of the list of R's `match` function results.

**Try it online!**

### How?

e.g. with `incomparables nomatch table x` = `[1,4], 2, [2,4], [4,3,2,1,0]`:

```
,⁷y⁵iⱮ⁶o - Main Link: list, incomparables; list, nomatch
 ⁷       - newline character                                '\n'
,        - pair (incompararables) with (right)              [[1,4],'\n']
   ⁵     - 5th argument (3rd input = table)                 [2,4]
  y      - translate (right) with lookup (left)             [2,'\n']
      ⁶  - 6th argument (4th input = x)                     [4,3,2,1,0]
     Ɱ   - map with:
    i    -   first index of (right) in (left)               [0,0,1,0,0]
       o - logical OR                                       [2,2,1,2,2]

```

---

* An empty list is represented as nothing, a list of lenth one is represented as just the item, while other lists are enclosed in `[]` and delimited by `,`
> 8 votes

# Answer
# , 55 bytes

In this case, the code doesn't use `match` with its full functionality, it is just used as an `index` function. First R answer, so probably incredibly inefficient byte-wise!

**Note** (thanks to Giuseppe for the info)**:** `%in%` and `setdiff` are also both *internally* implemented using `match`, so completely getting rid of this surprisingly useful function will result in a *mess*. Therefore, there is a 150-rep bounty with no deadline for this! (note that `setdiff` is allowed, though)

```
function(x,t,n,i)ifelse(x%in%setdiff(t,i),match(x,t),n)

```

Try it online!

or...

# , 5 bytes

```
match

```

Try it online!
> 6 votes

# Answer
# Jelly, ~~9~~ 8 bytes

```
ṣK¥ƒiⱮo⁶

```

Try it online!

A full program that takes three arguments: `[[table], incomparables]`, `x`, `nomatch` in that order.
> 6 votes

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

```
(a,b,c,d)=>a.Select(x=>d.Contains(x)|(x=b.IndexOf(x))<0?c:x)

```

Try it online!
> 6 votes

# Answer
# Ruby, 44 bytes

Zero-indexed.

```
->x,t,n,i{x.map{|e|i-[e]==i&&t.index(e)||n}}

```

Try it online!
> 5 votes

# Answer
# , 79 bytes

```
function(x,t,n,i)sapply(x,function(y)`if`(any(z<-y==t)&all(y-i),which(z)[1],n))

```

Try it online!

# , 66 bytes

```
function(x,t,n,i)sapply(x,function(y)c(which(y==t&all(y-i)),n)[1])

```

Combining my solution with parts of Nick's solution.

Try it online!
> 5 votes

# Answer
# Python 3, 60 bytes

```
lambda x,t,n,i:[v in{*t}-{*i}and-~t.index(v)or n for v in x]

```

Try it online!
> 4 votes

# Answer
# Japt, 14 bytes

```
Ë!XøD ©ÒVbD ªW

```

Try it
> 4 votes

# Answer
# PowerShell, 63 bytes

```
param($x,$t,$n,$o)$x|%{($n,$t.indexof($_))[$_-in$t*!($_-in$o)]}

```

Try it online!

0-indexed
> 4 votes

# Answer
# JavaScript (ES6), 53 bytes

```
(x,t,n,i)=>x.map(v=>!~i.indexOf(v)*-~t.indexOf(v)||n)

```

Try it online!
> 3 votes

# Answer
# Perl 6, 45 bytes

```
->\b,\c,\d{*>>.&{$_∉d&&~b.first($_,:k)||c}}

```

Try it online!

Anonymous code block that takes input curried, like `f(table, nomatch, incomparables)(x)` and returns the matches 0 indexed.

### Explanation:

```
->\b,\c,\d{                               }    # Anonymous code block taking 3 inputs
           *           # Return an anonymous Whatever lambda
            >>.&{                        }  # Mapping input to
                 $_∉d                       # If the element is not an uncomparable
                     && b.first($_,:k)      # Return the first index in the table
                       ~                    # Stringified so Nils are false
                                      ||c   # Else the nomatch element
~~

```
> 3 votes

# Answer
# Charcoal, 14 bytes

```
ＩＥθ∨∧¬№ει⊕⌕ηιζ

```

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

```
  θ             First input (x)
 Ｅ              Map over elements
       ε        Fourth input (incomparables)
      №         Count occurrences of
        ι       Current element
     ¬          Is zero
    ∧           Logical And
           η    Second input (table)
          ⌕     Find 0-based index of
            ι   Current element
         ⊕      Convert to 1-indexed
   ∨            Logical Or
             ζ  Third input (nomatch)
Ｉ               Cast to string
                Implicitly print on separate lines

```
> 2 votes

# Answer
# C (gcc), 125 bytes

1-indexed.

Given that I can't use a sentinel value in the passed arrays, I need to give the array bounds for each array.

```
f(x,c,t,d,n,i,e,j,f)int*x,*t,*i;{for(;f=0,c-->0;x[c]=--f?n:j){for(j=e;!f&j;x[c]-i[--j]||--f);for(;!f&j<d;x[c]-t[j++]||++f);}}

```

Try it online!
> 2 votes

# Answer
# Attache, 39 bytes

```
${{[_,y][nil=_or x@_in z]}=>x&Index@_4}

```

Try it online!

Pretty simple verification. Note that the argument order differs from that of match; specifically, `x` is the last argument rather than the first, and corresponds to `_4` in the above snippet.

## Explanation

```
${{[_,y][nil=_or x@_in z]}=>x&Index@_4}
${                                    }   named lambda, taking parameters x, y, z, and _4
                            x&Index@_4    short for Index[x, _4];
                                              calculates where each element in _4 occurs in x
                                              returns `nil` for no match
  {                      }=>              over each index:
   [_,y][               ]                     choose y (`nomatch`) if
         nil=_                                    the index is nil
              or x@_in z                          or the element is in `incomparables`
    _                                         otherwise, choose the index

```
> 2 votes

# Answer
## Haskell, ~~57~~ 56 bytes

```
(t#n)i=map$maybe n id.($zip i[n,n..]++zip t[1..]).lookup

```

Argument order is: `table`, `nomatch`, `incomparables`, `x`.

Try it online!
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
õ:Ik®I:

```

0-indexed. Inputs are in the order: `incomparables, table, x, nomatch`.

Try it online.

**Explanation:**

```
õ:       # Replace all values of the (implicit) first incomparables-list in
         # the (implicit) second table-list with an empty string
         #  i.e. incomparables=[4] and table=[9,8,7,6,5,4,3,2,1] → [9,8,7,6,5,"",3,2,1]
  Ik     # Get the index of each value in the third x-list in this list (-1 if not found)
         #  i.e. x=[9,4,3,6,3] → [0,-1,6,3,6]
    ®I:  # Replace all -1 with the fourth input-integer
         #  i.e. nomatch=-99 → [0,-99,6,3,6]
         # (and output the mapped list implicitly as result)

```
> 2 votes

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


title: MQTT subscription topic match

text:
# Question
Title: MQTT subscription topic match
# Background

MQTT (Message Queuing Telemetry Transport) is an ISO standard publish-subscribe-based messaging protocol (Wikipedia).

Each message has a topic, such as the following examples:

* `myhome/groundfloor/livingroom/temperature`
* `USA/California/San Francisco/Silicon Valley`
* `5ff4a2ce-e485-40f4-826c-b1a5d81be9b6/status`
* `Germany/Bavaria/car/2382340923453/latitude`

MQTT clients may subscribe to message topics using wildcards:

* Single level: `+`
* All levels onward: `#`

For example, the subscription `myhome/groundfloor/+/temperature` would produce these results (non-conformances in **bold**):

✅ myhome/groundfloor/livingroom/temperature
✅ myhome/groundfloor/kitchen/temperature
❌ myhome/groundfloor/livingroom/**brightness**
❌ myhome/**firstfloor**/livingroom/temperature
**garage**/groundfloor/**fridge**/temperature

Whereas the subscription `+/groundfloor/#` would produce these results:

✅ myhome/groundfloor/livingroom/temperature
✅ myhome/groundfloor/kitchen/brightness
✅ garage/groundfloor/fridge/temperature/more/specific/fields
❌ myhome/**firstfloor**/livingroom/temperature
❌ myhome/**basement**/corner/temperature

More info here.

# The Task

Implement a function/program accepting two strings and returning a boolean. The first string is the subject topic, the second is the criteria topic. The criteria topic uses the subscription syntax detailed above. The function is truthy when the subject matches the criteria.

Rules for this task:

* Topics are ASCII
* There are no criteria fields beyond the `#` wildcard
* Wildcards do not appear in subject topics
* Number of subject fields \>= number of criteria fields
* There are no 0-character fields nor leading or tailing forward slashes

# Test cases

criteria1 = "myhome/groundfloor/+/temperature"
criteria2 = "+/groundfloor/#"

("abc", "ab") =\> false
("abc", "abc") =\> true
("abc/de", "abc") =\> false
("myhome/groundfloor/livingroom/temperature", criteria1) =\> true
("myhome/groundfloor/kitchen/temperature", criteria1) =\> true
("myhome/groundfloor/livingroom/brightness", criteria1) =\> false
("myhome/firstfloor/livingroom/temperature", criteria1) =\> false
("garage/groundfloor/fridge/temperature", criteria1) =\> false
("myhome/groundfloor/livingroom/temperature", criteria2) =\> true
("myhome/groundfloor/kitchen/brightness", criteria2) =\> true
("garage/groundfloor/fridge/temperature/more/specific/fields", criteria2) =\> true
("myhome/firstfloor/livingroom/temperature", criteria2) =\> false
("myhome/basement/corner/temperature", criteria2) =\> false
("music/kei$ha/latest", "+/kei$ha/+") =\> true

# Answer
# Python 3, 72 bytes

```
lambda a,b:bool(re.match(b.translate({43:"[^/]+",35:".+"}),a))
import re

```

Try it online!

This problem can be trivially simplified to a regex match, though another more interesting method may produce better results.

EDIT I came up with a 107-byte solution not using regex. I don't know if it can get shorter than 72 or maybe I'm just not seeing to correct approach to this. Just the split-zip structure seems to be too large though. Try It Online!
> 3 votes

# Answer
# Jelly, 20 bytes

```
ṣ€”/ZṖF”#eƊ¿œiÐḟ”+ZE

```

A monadic Link accepting a list of lists of characters, `[topic, pattern]`, which returns `1` or `0` for match or no-match respectively.

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

### How?

```
ṣ€”/ZṖF”#eƊ¿œiÐḟ”+ZE - Link: list of lists of characters, [topic, pattern]
 €                   - for each:
ṣ                    -   split at occurrences of:
  ”/                 -     '/' character
    Z                - transpose (any excess of topic is kept)
           ¿         - while...
          Ɗ          - ...condition: last three links as a monad:
       ”#            -   '#' character
         e           -   exists in:
      F              -     flatten
     Ṗ               - ...do: pop the tail off
              Ðḟ     - filter discard those for which:
            œi       -   first multi-dimensional index of: ([] if not found, which is falsey)
                ”+   -     '+' character
                  Z  - transpose
                   E - all equal?

```
> 3 votes

# Answer
# Ruby, 65 bytes

Regex solution. I added `Regex.escape` in case a criteria name just so happens to be something like `com.java/string[]/\n` or something silly that would have regex pieces.

```
->s,c{s=~/^#{Regexp.escape(c).sub('\#','.*').gsub'\+','[^/]*'}$/}

```

Try it online!

Non-regex solution, 77 bytes

Uses a nice simple split, zip, and match technique. I developed this one first before realizing that even with `Regex.escape` the regex solution would've been shorter anyways.

```
->s,c{s.split(?/).zip(c.split ?/).all?{|i,j|i==j||'+#'[j||9]||!j&&c[-1]==?#}}

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-pl`, 50 bytes

```
$_="\Q$_";s|\\\+|[^/]+|g;s/\\\#/.*/;$_=<>=~m|^$_$|

```

Try it online!
> 2 votes

# Answer
# Clojure, ~~107~~ ~~91~~ ~~76~~ ~~65~~ 102 bytes

An anonymous function, returns subject topic as truthy and `nil` as falsey (valid in Clojure).

```
(defn ?[t c](every? #(#{"#""+"(% 0)}(% 1))(apply #(map vector % %2)(map #(re-seq #"[^/]+" %) [t c]))))

```

107 102 working
91 76 65 all defeated with regex chars
> 1 votes

# Answer
## Python 3, ~~99~~ 88 bytes

Without using a regex. With some help from Jonathan Allan and Chas Brown.

```
f=lambda s,p:p in(s,'#')or p[:1]in(s[:1],'+')and f(s[1:],p['+'!=p[:1]or(s[:1]in'/')*2:])

```
> 1 votes

# Answer
# Python 2, ~~85~~ ~~84~~ ~~80~~ ~~92~~ 89 bytes

```
lambda s,c:all(x in('+','#',y)for x,y in zip(c.split('/')+[0]*-c.find('#'),s.split('/')))

```

Try it online!

Thanks to Jonathan Allan and Value Ink for pointing out bugs.
> 1 votes

# Answer
## Haskell, ~~76~~ ~~73~~ ~~71~~ 67 bytes

```
(a:b)#(c:d)=a=='+'&&b#snd(span(/='/')d)||a=='#'||a==c&&b#d
a#b=a==b

```

Try it online!

Edit: -4 bytes thanks to @cole.
> 1 votes

# Answer
# Kotlin, 106 bytes

```
fun f(s:List<String>)=s[1].split("/").filterIndexed{i,v->v!="+"&&v!="#"&&v!=s[0].split("/")[i]}.count()==0

```

Try it online!
> 0 votes

# Answer
# Jelly, ~~22~~ 19 bytes

```
ḟ”+ṣ”/)ZẠƇṖœi”#$¿ZE

```

Try it online!

A monadic link that takes as its argument `[topic], [criterion]` and returns `1` for a match and `0` for no match.
> 0 votes

# Answer
# Charcoal, 36 bytes

```
≔⪪Ｓ/θ≔⪪Ｓ/ηＦ∧№η#⊟η≔…θＬηθＦ⌕Ａη+§≔θι+⁼θη

```

Try it online! Link is to verbose version of code. Outputs `-` (Charcoal's implicit output for `true`) for a match, nothing for no match. Explanation:

```
≔⪪Ｓ/θ

```

Split the subject on `/`s.

```
≔⪪Ｓ/η

```

Split the criteria on `/`s.

```
Ｆ∧№η#⊟η≔…θＬηθ

```

If the criteria contains (i.e. ends with) a `#` then remove it and trim the subject to the new length of the criteria.

```
Ｆ⌕Ａη+§≔θι+

```

Where the criteria contains `+` then replace that element in the subject with `+`.

```
⁼θη

```

Compare the subject with the criteria and implicitly print the result.
> 0 votes

# Answer
# Retina 0.8.2, 42 bytes

```
%`$
/
+`^([^/]+/)(.*¶)(\1|\+/)
$2
^¶$|¶#/$

```

Try it online! Explanation:

```
%`$
/

```

Suffix a `/` to both lines.

```
+`^([^/]+/)(.*¶)(\1|\+/)
$2

```

Repeatedly remove the first element of both subject and criteria while they equal or the criteria element is a (happy) `+`.

```
^¶$|¶#/$

```

The criteria matches if it's just a `#` (with the `/` that was added earlier) otherwise both subject and criteria should be empty by this point.
> 0 votes

# Answer
# Pyth, 22 bytes

```
:Q::E"[+]""[^/]+"\#".*

```

Try it online!
> 0 votes

# Answer
# JavaScript, ~~69~~ 66 bytes

```
t=>s=>new RegExp(s.split`+`.join`[^/]+`.split`#`.join`.+`).test(t)

```

Try it online!
> 0 votes

# Answer
# Python 3, ~~149~~ 148 bytes

```
def f(t,c):t,c=t.split('/'),c.split('/');return all([c[i]=='+'or c[i]==t[i]or c[i]=='#'for i in range(len(c))])and not(len(c)!=len(t)and c[-1]!='#')

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 21 bytes

```
ε'/¡}ζʒ'+å≠}˜'#¡н2ôøË

```

Input as a list in the order `[criteria, topic]`.

Try it online or verify all test cases.

**Explanation:**

```
ε                      # Map both strings in the implicit input-list to:
 '/¡                  '#  Split the string on "/"
                       #   i.e. ["+/+/A/B/#","z/y/A/B/x/w/v/u"]
                       #    → [["+","+","A","B","#"],["z","y","A","B","x","w","v","u"]]
    }ζ                 # After the map: zip/transpose the two string-lists,
                       # with space as (default) filler
                       #  → [["+","z"],["+","y"],["A","A"],["B","B"],["#","x"],[" ","w"],
                       #     [" ","v"],[" ","u"]]
      ʒ    }           # Filter each pair by:
       '+å≠           '#  Only keep those which do NOT contain a "+"
                       #   → [["A","A"],["B","B"],["#","x"],[" ","w"],[" ","v"],[" ","u"]]
            ˜          # Flatten the filtered list
                       #  → ["A","A","B","B","#","x"," ","w"," ","v"," ","u"]
             '#¡      '# Split the list by "#"
                       #  → [["A","A","B","B"],["x"," ","w"," ","v"," ","u"]]
                н      # Only keep the first part
                       #  → ["A","A","B","B"]
                 2ô    # Split this back into pairs of two
                       #  → [["A","A"],["B","B"]]
                   ø   # Zip/transpose them back
                       #  → [["A","B"],["A","B"]]
                    Ë  # And check if both inner lists are equal
                       #  → 1 (truthy)
                       # (after which the result is output implicitly)

```
> 0 votes

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


# Question
Title: Operation Unz̖̬̜̺̬a͇͖̯͔͉l̟̭g͕̝̼͇͓̪͍o̬̝͍̹̻
I'm sure you're all familiar with Z̃͗̇̚͟Ḁ̬̹̈̊̂̏̚L̜̼͊ͣ̈́̿̚G̱̮ͩ̃͑̆ͤ̂̚Õ̷͇͉̺̜̲ͩ́ͪͬͦ͐ ̪̀ͤͨ͛̍̈͢ĝ̭͇̻̊ͮ̾͂e̬̤͔̩̋ͮ̊̈ͭ̓̃n͖͎̘̭̯̳͎͒͂̏̃̾ͯe͕̖̋ͧ͑ͪ̑r̛ͩa̴͕̥̺̺̫̾ͭ͂ͥ̄ͧ͆t͍̻̘̆o͓̥ͤͫ̃̈̂r̹̤͇̰̻̯̐ͮ̈́ͦ͂͞. If not, you can play with the classical generator a bit. Zalgo text is unicode text that started as English text and had a bunch of combining characters to make it hard to read artistic.

This is operation unzalgo. The object is to undo the generate zalgo text operation. Since only combining characters were added, only combining characters have to be removed. We're only going to be operating on English, because of course we are. However, all proper English text must to come through unmutated. That is, if you were fed proper English, you must output your input. Sounds easy, right? Not so fast. English has combining characters, just not very many, and people are slowly forgetting they exist.

The rules:

1) You may either strip combining characters or filter out all invalid characters, at your discretion. This doesn't have to work at all languages because the operation itself makes no sense if we started with something that wasn't English text. Abandon hope all ye who enter here.

2) You may assume that unicode normalization was not executed after zalgo generation; that is all added combining characters are still combining characters.

3) All printable ASCII characters (codepoints between 0x20 and 0x7E inclusive) must survive, as well as tab (0x09), and newline (0x0A).

4) English has diaresis over vowels. These must survive whether expressed as natural characters or combining characters.

Vowel table (Each group of three is in the form (unmodified character, single character, combining characters):

```
a ä ä A Ä Ä
e ë ë E Ë Ë
i ï ï I Ï Ï
o ö ö O Ö Ö
u ü ü U Ü Ü
y ÿ ÿ Y Ÿ Ÿ

```

The combining diaresis character is code-point 0x308.

5) English does not have diaeresis over consonants. You must dump them when constructed as combining characters.

6) British English has four ligatures. These must survive:

```
æ Æ œ Œ

```

7) The following symbols must survive:

Editor substitution table (includes smart quotes in both directions):

```
… ¼ ½ ¾ ‘ ’ “ ” ™

```

Symbol table:

```
$ ¢ £ ¬ † ‡ • ‰ · ° ± ÷

```

8) If you get something like ö̎̋̉͆̉ö͒̿̍ͨͦ̽, both oo and öö are valid answers.

9) Input may contain both zalgo and non-zalgo characters; and the non-zalgo characters should be unmodified: if somebody sends 'cöoperate with dͧḯ̍̑̊͐sc͆͐orͩ͌ͮ̎ͬd̄̚', they should still get back 'cöoperate with discord' not 'cooperate with discord'.

10) If any character is not specified, it doesn't matter what you do with it. Feel free to use this rule to lossily compress the keep-drop rules.

11) Your program must handle all unicode codepoints as input. No fair specifying a code-page that trivializes the problem.

Additional test cases:

```
"z̈ ỏ"        "z o"
"r̈ëën̈ẗr̈ÿ"    "rëëntrÿ"  (don't outsmart yourself)

```

I have been informed this case is also excellent but it's starting point contains a few characters with unspecified behavior. If you maul Θ, Ό, Ɲ, or ȳ I don't care.

A pretty comprehensive test input:

```
    cöoperate with dͧḯ̍̑̊͐sc͆͐orͩ͌ͮ̎ͬd̄̚ æ Æ œ Œ…¼½¾‘’“”™$¢£¬†‡•‰·°±÷

a ä ä A Ä Ä
e ë ë E Ë Ë
i ï ï I Ï Ï   Z̃͗̇̚͟Ḁ̬̹̈̊̂̏̚L̜̼͊ͣ̈́̿̚G̱̮ͩ̃͑̆ͤ̂̚Õ̷͇͉̺̜̲ͩ́ͪͬͦ͐ ̪̀ͤͨ͛̍̈͢ĝ̭͇̻̊ͮ̾͂e̬̤͔̩̋ͮ̊̈ͭ̓̃n͖͎̘̭̯̳͎͒͂̏̃̾ͯe͕̖̋ͧ͑ͪ̑r̛ͩa̴͕̥̺̺̫̾ͭ͂ͥ̄ͧ͆t͍̻̘̆o͓̥ͤͫ̃̈̂r̹̤͇̰̻̯̐ͮ̈́ͦ͂͞
o ö ö O Ö Ö
u ü ü U Ü Ü
y ÿ ÿ Y Ÿ Ÿ
Unz̖̬̜̺̬a͇͖̯͔͉l̟̭g͕̝̼͇͓̪͍o̬̝͍̹̻

ö̎̋̉͆̉ö͒̿̍ͨͦ̽
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅ

```

# Answer
> 77 votes
# JavaScript (Node.js), 45 bytes

```
s=>s.replace(/([aeiouy]̈)|[̀-ͯ҉]/ig,'$1')

```

Try it online!

More readable version:

```
s=>s.replace(/([aeiouy]\u0308)|[\u0300-\u036f\u0489]/ig,'$1')

```

# Answer
> 10 votes
# Perl 5 (`-pC -Mutf8`), ~~30~~ 28 bytes

using tsh regex, upvote him. -2 bytes thanks to DomHastings

```
s/[aeiouy]̈\K|[̀-ͯ҉]//gi

```

TIO

# Answer
> 9 votes
# Japt, 22 bytes

Another port of tsh's solution

```
r"(%ÿ)|[̀-ͯ҉]""$1

```

Try it or run all test cases

# Answer
> 8 votes
# Retina, ~~64~~ 49 bytes (44 chars)

Removes combining diaresis only if not for a vowel, then removes any character not in the character class. `\p{L}` is a handy class for Unicode letters.

```
i`(?<![aeiouy])\u0308

[^	-÷\p{L}‘-™\u0308]

```

**Try it online!**

This successfully ensures no dotted consonants remain, and it preserved the dots over the vowels in a way that passes rules #4 and #9.

Test on a real-world example: **Try it online!**

---

If I copy the regex in @tsh's answer, I get this for **27 chars (31 bytes)**:

```
i`(?!(?<=[aeiouy])̈)[̀-ͯ҉]

```

Try it online!

# Answer
> 7 votes
# Stax, ~~27~~ ~~25~~ 24 bytes

```
Ç╣>ñ↓í$▐wø⌐∞≤Ö1e╖ÖÅ╤Δ╩+º

```

Run and debug it

Now handles the Y, and uses no regex.

Unpacked, ungolfed, and commented, it looks like this:

```
400Vk|r push range array [400, 401, ..., 998, 999]
776X-   store 776 in the X register, and remove it from the array
-       remove all the *remaining* codepoints from the input
{       start a block for filtering the remaining string
  x-    subtract 776 from the codepoint; this will be truthy for all other values
  M     bitwise-or; if there's only a single value on the stack, no-op
  Vv'y+ "aeiouy"
  _]v#  current character in lowercase; is it in the vowels?
  s     swap top two stack entries so the lower value can be used in next iteration
f       complete the filter and output implicitly

```

Run this one

# Answer
> 5 votes
# Jelly, 29 bytes

```
768r2ȷỌ
ẹ9ị¢¤©fẹⱮØyF‘ƊœPḟ€¢j®

```

Try it online!

A full program that unzalgos its argument. Filters out all characters with code points between 768 and 2000 except diareses on vowels.

## Explanation

### Helper link: characters from code point 768 to 2000 inclusive

```
768r2ȷ  | Range from 768 to 2000 inclusive
      Ọ | Convert from code points to characters

```

### Main link

```
ẹ                     | All indices in input string of:
 9ị¢¤©                | - the ninth character in the helper link (i.e.  ̈) (which is also copied to the register for use at the end)
      f      Ɗ        | Filter keeping only those in the result of the following, applied to the original input as a monad:
       ẹⱮ             | - Indices of each of the following:
         Øy           |   - Vowels plus y
           F          | - Flatten
            ‘         | - Decrease by 1
              œP      | Now split the original input at each of these indices, discarding the character at the index itself (which will be a diaresis following a vowel)
                ḟ€¢   | Filter each of these lists discarding any characters in the helper link
                   j® | Join using the stored diaresis

```

# Answer
> 4 votes
# PowerShell, 43 bytes

```
$args-ireplace'([aeiouy]̈)|[̀-ͯ҉]','$1'

```

Try it online!

+1 to @tsh.

Readable versions:

```
$args-ireplace'([aeiouy]\u0308)|[\u0300-\u036f\u0489]','$1'

```

```
$args-ireplace"([aeiouy]$([char]0x308))|[$([char]0x300)-$([char]0x36f)$([char]0x489)]",'$1'

```

# Answer
> 3 votes
# JavaScript (ES6), 51 chars/60 bytes

Complete golfness:

```
x=>x.replace(/([^   -ʷ -₿™̈]|(?![^aeiouy])̈)/giu,"")

```

Escaped golfness: ~~(As Unicode escape sequence doesn't exist, I write u+xxxx as \<xxxx\>.)~~

```
x=>x.replace(/([^\u0009-\u02b7\u2000-\u20bf\u2122\u0308]|(?![^aeiouy])\u0308)/giu,"")

```

# Answer
> 1 votes
# Swift, 115 chars, 119 bytes (UTF-8)

```
import UIKit
let f={(s)in(""+s).replacingOccurrences(of:"([aeiouy]̈)|[̀-ͯ҉]",with:"$1",options:.regularExpression)}

```

(based on tsh regex)

# Answer
> 1 votes
# Java (JDK), ~~120~~ 50 bytes

```
s->s.replaceAll("(?i)([aeiouy]̈)|[̀-ͯ҉]","$1")

```

Try it online!

Based on Holger comment and Benjamin Urquhart comment, itself based on tsh regex.

# Answer
> 1 votes
# Python, 63 bytes

Uses the tsh regex

```
lambda s:re.sub("(?i)([aeiouy]̈)|[̀-ͯ҉]","\\1",s)
import re

```

TIO

# Answer
> 1 votes
# 05AB1E, 32 bytes

```
žAžHŸ776©KçKεÇ¤®Qi¬žOsçlå≠iн]˜çJ

```

This took longer than it should have, and I'm still not very happy with the result.. Definitely room for improvements..

Removes all characters with code-points in the range \\$\[512,65536\]\\$, except for vowels with diareses.

Try it online.

**Explanation:**

```
žA                # Push builtin 512
  žH              # Push builtin 65536
    Ÿ             # Create a list with these ranges: [512,513,514,...,65534,65535,65536]
     776          # Push 776
        ©         # Store it in variable `®` (without popping)
         K        # Remove it from this list
          ç       # Convert all these integers to characters with these code-points
           K      # And remove all those characters from the (implicit) input-string
ε                 # Then map all remaining characters to:
 Ç                #  Get the code-points of the current character
  ¤               #  Get the last code-point (without popping the code-points themselves)
   ®Qi            #  And if it's equal to variable `®` (776):
      ¬           #   Get the first code-point (without popping the code-points themselves)
       žO         #   Push builtin "aeiouy"
         s        #   Swap to get the first code-point again
          ç       #   Convert it to a character
           l      #   Then to lowercase
            å≠i   #   And if it's NOT in the vowel-string:
               н  #    Pop the code-points, and only leave the first code-point
                  #  (implicit elses: keep the code-point list)
]                 # Close both if-statements and the map
 ˜                # Flatten the list of lists of code-points
  ç               # Convert these code-point integers back into characters
   J              # And join the character-list back together to a single string
                  # (after which the result is output implicitly)

```

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