title: Shuffle a subsequence

text:
# Question
Title: Shuffle a subsequence
Thanks to rak1507 for the suggestion

> "Random" in this challenge always refers to "uniformly random" - of all possible choices, each has an equal chance of being chosen. Uniform shuffling means that every possible permutation of the array has an equal chance of being chosen.

Given an array consisting of positive digits (`123456789`), select a randomly chosen, non-empty subsequence from the array, shuffle the elements and reinsert them back into the array in the former indices, outputting the result

For example, take `L = [5, 1, 2, 7, 4]`. We choose a random non-empty subsequence, e.g. `[5, 2, 4]`. These are at indices `1, 3, 5` (1-indexed). Next, we shuffle `[5, 2, 4]` to give e.g. `[2, 5, 4]`. We now reinsert these into the list, with `2` at index `1`, `5` at index `3` and `4` at index `5` to give `[2, 1, 5, 7, 4]`.

You may also take the input as an integer or a string, and output it as such, or you may mix and match types.

This is , so the shortest code in bytes wins

# Answer
# Jelly, 11 bytes

```
JŒPḊX,Ẋ$yJị

```

Try It Online!

```
JŒPḊX,Ẋ$yJị  Main Link
J            Get the list of indices [1, 2, ..., n]
 ŒP          Powerset - all possible subsets
   Ḋ         Remove the empty one
    X        Select a random one
     ,Ẋ$     Pair that with a random permutation of itself
        yJ   Translate the original indices according to that mapping
          ị  Index back into the original list

```
> 6 votes

# Answer
# , 37 40 39 35 bytes

```
({~#?#)@:{~`]`[}1 I.@#:@+0{1?_1+2^#

```

Try it online!

+3 after reading hyperneutrino's answer and realizing I had to remove the empty subset

-4 after reading loopy walt's answer and realizing I could make my random choice before converting to binary

Consider `5 1 2 7`:

* `1 ...+0{1?_1+2^#` If `n` is input length, picks a random number between 1 and 2^n.
* `I.@#:@` converts it to binary, and then converts that mask to indices. That is, the first 2 steps amount to choosing a random element from the 2nd column:

```
┌───────┬───────┐
│0 0 0 1│3      │
│0 0 1 0│2      │
│0 0 1 1│2 3    │
│0 1 0 0│1      │
│0 1 0 1│1 3    │
│0 1 1 0│1 2    │
│0 1 1 1│1 2 3  │
│1 0 0 0│0      |
│1 0 0 1│0 3    │
│1 0 1 0│0 2    │
│1 0 1 1│0 2 3  │
│1 1 0 0│0 1    │
│1 1 0 1│0 1 3  │
│1 1 1 0│0 1 2  │
│1 1 1 1│0 1 2 3│
└───────┴───────┘

```
* `({~#?#)@:{~`]`[}` Now "amend" the original input at those indices with the current values at those indices, shuffled.
> 5 votes

# Answer
# Perl 5 List::Util, 47 bytes

```
sub{@_[@s]=@_[shuffle@s=grep.5<rand,0..$#_];@_}

```

Try it online!
> 4 votes

# Answer
# , ~~82~~ ~~79~~ 77 bytes

Or **\>=4.1, 70 bytes** by replacing the word `function` with a `\`.

*Edit: fix for 1-length input thanks to @Dominic van Essen.*

```
function(v,k=seq(!v),`[`=sample)`[<-`(v,m<-k[k[1,,choose(max(k),k)]],sort(m))

```

Try it online!

Different approach to Dominic's R answer (test harness stolen from him).

Samples length of the subsequence to shuffle from a distribution given by a truncated row of Pascal's triangle. Then samples this many indices in random order and substitutes the corresponding values for the sorted counterparts.

```
function(v,             # function taking v as input
k=seq(!v),              # sequence along v (1:length(v))
s=sample){              # rename for golfing purposes
n<-                     # how long the subsequence
 s(k,1,                 # sample from k one number
 prob=choose(max(k),k)) # distribution given by row of Pascal's triangle
                        # without the first 1 (corresponding to empty subsequence)
m<-s(k,n)               # sample n items from k
v[m]=                   # in v: at indices given by m
 v[sort(m)]             # place values from indices at sorted m
v}                      # return v

```
> 4 votes

# Answer
# Vyxal, 13 bytes

```
ẏÞS℅~İṖ℅Z(n÷Ȧ

```

Try it Online!

## Explained

```
ẏÞS℅~İṖ℅Z(n÷Ȧ
ẏ             # Push the input and the range [0, len(input))
 ÞS℅          # Choose a random sublist of indices
    ~İ        # And index into the input at those places, without popping anything
      Ṗ℅      # Choose a random permutation of the indexed items
        Z     # and zip that with the chosen indices - this creates a list of [[original index, new item]...]
         (    # for each pair:
          n÷Ȧ # input[original index] = new item

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 72 bytes

```
SubsetMap[c@*Permutations,#,c@Rest@Subsets[i=0;++i&/@#]]&
c=RandomChoice

```

Try it online!

```
SubsetMap[               ,#,                           ]    replace at indices:
                                   Subsets[i=0;++i&/@#]      of subsequences
                            c@Rest@                           (random nonempty)
          c@*Permutations                                   with a random permutation

```
> 3 votes

# Answer
# Python, 140 bytes

```
from random import*
def f(a):
 n=len(a);s=randint(1,2**n-1);t=[j for j in range(n)if s&2**j]
 while t:u=choice(t);T,*t=t;a[T],a[u]=a[u],a[T]
```

Attempt This Online!

Changes the input list in-place (no return value). It first draws a random integer from `[1,2^n-1])` where `n` is the length of input list `a`. Its binary representation is used as a mask to uniformly select from the allowed subsets (all but the empty one). This subset is then randomly shuffled by applying a series of swaps. The swap is always the lowest active with a randomly chosen active position. I say "active" because after the swap the low element is retired from the active set and no longer eligible for swaps. It is left as an easy exercise for the reader to verify that this draws uniformly from all permutations of the subset.

The test code makes the histogram suggested by @tsh (more or less; I lump together permutations with the same structure) in a comment and the distribution looks ok.
> 3 votes

# Answer
# Charcoal, ~~36~~ 35 bytes

```
≔⌕Ａ⮌⍘⊕‽⊖Ｘ²Ｌθ²1ηＦＬθ⊞υ⎇№ηι‽⁻ηυιＩＥυ§θι

```

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

```
≔⌕Ａ⮌⍘⊕‽⊖Ｘ²Ｌθ²1η

```

Choose a random number from 1 to 2 to the power of the length of the input (exclusive). Convert it to base 2, and get the exponents of the powers of 2 that sum to that number.

```
ＦＬθ⊞υ⎇№ηι‽⁻ηυι

```

Create a random permutation of those exponents, while keeping the unused exponents in their original position.

```
ＩＥυ§θι

```

Apply that permutation to the original input.
> 3 votes

# Answer
# , ~~91~~ ~~85~~ ~~84~~ 82 bytes

*Edit: -1 byte thanks to pajonk, then -2 bytes thanks to Giuseppe*

```
function(v,l=sum(v|T),`?`=sample,m=(l:0)[!(2:2^l-2?1)%/%2^(0:l)%%2]){v[m]=v[?m];v}

```

Try it online!

TIO link includes (reciprocal) distribution of `shuffle_subsequence(1:3)` to check conformity to tsh's calculations.
> 3 votes

# Answer
# BQN, ~~60~~ 53 bytes

*Edit: -7 bytes thanks to mlochbaum, and also thanks to ovs and mlochbaum for bug-spotting*

```
•rand.Deal{(∘≠⊸⊏⌾(((2⋆⊒˜)(2|·⌊÷)˜1+⊑1-˜2⋆≠)⊸/))}

```

Try it at BQN online REPL

Ungolfed, commented (try it here):

```
Deal ← •rand.Deal    # random permutation of 0..-1
Rand ← ⊑Deal         # random number from 0..-1
Shuf ← ⊢⊏˜·Deal≠     # random shuffle of list
num ← 1+Rand 1-˜2⋆≠ vec        # pick a random number from 1..2^len(vec)-1
bits ← {(2⋆⊒˜vec)(2|·⌊÷)˜}num # convert it into bits
ans ← (Shuf⌾(bits⊸/)vec)       # shuffle vec at positions given by bits

```
> 3 votes

# Answer
# APL+WIN, 31 bytes

Prompts for vector of digits. Will also work with a string of characters.

```
v[i]←v[i[(⍴i)?⍴i←(?⍴v)?⍴v←⎕]]⋄v

```

Index origin = 1. Randomly selects the length of the subset from 1 to length. Randomly selects indices corresponding to the length of subset. Randomly shuffles values at those indices.

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~36~~ ~~29~~ 27 bytes

Requires index origin 0.

```
{⍵[?⍨≢⍵]}@{k∘←?{2}¨⍵}⍣{∨/k}

```

Try it online!

If we would allow the empty subsequence as a random choice, `k∘←` and `⍣{∨/k}` could be removed.

**How?**

`{k∘←?{2}¨⍵}` Get a random subsequence and store it's binary mask in `k`
`{2}¨⍵` A 2 for each value in . This could be `2⍨¨⍵` in version 18 and above.
`?` For each, draw a random integer in `[0, 2)` / 0 or 1.
`k∘←` Store that vector in a global variable named `k` and return it.

`{⍵[?⍨≢⍵]}@` Shuffle the selected that subsequence
`{ ... }@` Replace the subsequence indicated by 1's in the boolean mask with the return value of the function on the left.
`≢⍵` `n` = Length of the subsequence
`?⍨` Choose `n` random integers in the interval `[0, n)` (Permutation of `[0,1,2,...,n-1]`).
`⍵[ ... ]` Index into the subsequence with the permutation.

`⍣{∨/k}` ... until `k` contains at least a single 1.
> 2 votes

# Answer
# BQN, 19 bytes

`{⊏˜•rand.Deal≠}⍟≢`

Explanation:-

`{⊏˜•rand.Deal≠}` shuffles array randomly

`⍟≢` shuffles it again if (by chance) the shuffled array is equal to the original array
> 1 votes

# Answer
# C++ (gcc), ~~197~~ \\$\cdots\\$ ~~175~~ 174 bytes

```
#import<regex>
using V=std::vector<int>;int f(V&v){V i=v,r=v;int y=0,n,j;for(int&a:i)a=y++;std::random_shuffle(&i[0],&*end(i));for(j=n=rand()%y+1;j;)r[i[--j]]=v[i[j%n]];v=r;}

```

Try it online!

*Added 2 bytes to fix an error.*
*Saved ~~3~~ 5 bytes thanks to ceilingcat!!!*

Inputs a vector of integers.
Randomly shuffles a random subgroup of the elements in place.
> 1 votes

# Answer
# JavaScript (ES6), 170 bytes

```
x=>(s=n=>n?(w=(x,i,k)=>[x[i],x[k]]=[x[k],x[i]])(y,--n,o()*n|0)&&s(n):y)((r=_=>(y=[...x.keys()].filter(_=>(o=Math.random)()<.5))+y?y:r())().length).map((k,i)=>w(x,i,k))&&x

```
> 1 votes

# Answer
# Python3, 142 bytes:

```
from random import*
r=range
def f(s):g=sample(r(l:=len(s)),randint(1,l));j=g[:];shuffle(j);return[s[j.pop(0)]if i in g else s[i]for i in r(l)]

```

Try it online!
> 1 votes

# Answer
# Japt, 2 bytes

Simply shuffles the array randomly and has the possibility to output the original array, which would seem to satisfy the requirements to me.

```
ö¬

```

Try it

But, if not, then ...

## Japt, 15 bytes

... This version interleaves the array with a random permutation of itself, chooses an element at random from each pair, and continues to do so until the result equals the input when both are sorted.

```
@ÍeXÍ}a@íUö¬ mö

```

Try it
> 0 votes

---
Tags: code-golf, array, random, subsequence
---


# Question
Title: Code Golf: Mix the nuts so that none of the same kind are touching
**Input:**

Input is a randomized array of nuts (in your language), the possible nuts follow. Your program must have a way of representing each kind of nut, such as an integer code. Program must be able to handle any size array of any configuration of nuts.

**Possible Nuts:**

```
Kola nut
Macadamia
Mamoncillo
Maya nut
Mongongo
Oak acorns
Ogbono nut
Paradise nut
Pili nut
Pistachio
Walnut

```

**Output:**

Output must be the array sorted in such a fashion that there are no adjacent nuts of the same kind. If this is impossible, the output should be an empty array.

Example Input (simplified):

```
["walnut", "walnut", "pistachio"]

```

Example Output:

```
["walnut", "pistachio", "walnut"]

```

**Solutions may not simply shuffle the array until it becomes unique by chance. The sort employed must be a deterministic one**

# Answer
> 8 votes
### GolfScript, 42 41 37 38 characters

```
~.`{\`{=}+%1-,}+$.,)2//zip[]*.2<..&=*p

```

The code expects input on STDIN and prints result to STDOUT, e.g.:

```
> ["walnut" "walnut" "walnut" "macadamia" "pistachio"]
["walnut" "macadamia" "walnut" "pistachio" "walnut"]

> ["walnut" "walnut" "walnut" "macadamia" "walnut"]
[]

```

The script became longer than expected but I suppose there is room for improvement.

Edit: The case of a list with a single item costs me 1 character (the best comparison I could come up with is the same as Peter's).

# Answer
> 6 votes
## GolfScript, 32 chars

```
~:x{]x\-,}$.,)2//zip[]*.2<..&=*`

```

Same input and output format as Howard's solution.

# Answer
> 6 votes
# Brachylog v2, 10 bytes

```
p.¬{s₂=}∨Ė

```

Try it online!

Brute-force solution. (This is a function, allowed because the challenge does not say "full program".) It's also mostly a direct translation of the spec (the only real subtlety is that I managed to arrange things so that all the implicit constraints arrived in exactly the right places, thus not needing any extra characters to disambiguate them).

Note that this is a generic algorithm for rearranging any sort of list so that it does not have two touching elements; it can handle string representations of the elements, and it can handle integer codes just as well. So it doesn't really matter how the "Your program must have a way of representing each kind of nut, such as an integer code." requirement from the question is interpreted.

## Explanation

```
p.¬{s₂=}∨Ė
p            Find a permutation of {the input}
  ¬{   }     which does not have the following property:
    s₂         it contains a pair of adjacent elements
      =        that are equal
        ∨    {no constraint on what value the equal elements can have}
 .           If you find such a permutation, output it.
        ∨    If no permutation is found, ignore the input and
         Ė     {output} an empty list

```

# Answer
> 2 votes
# Vyxal `r`, ~~12~~ 8 bytes

```
Ṗ‡ÞǓ⁼c¾∨

```

Try it Online!

*-4 thanks to @Steffan*

#### Explanation (old)

I'll update it when I have time.

```
Ṗ¾wJλ:Ḣ=a¬;c  # Implicit input
Ṗ             # Permutations
 ¾wJ          # With an empty list appended
              # (In case there is no truthy item)
    λ     ;c  # First item such that:
     :Ḣ=      #  Adjacent elements are equal?
        a¬    #  None are true
              # Implicit output

```

# Answer
> 2 votes
# Nibbles, 7 bytes (14 nibbles)

```
/|``p$/!>>$@!*

```

Systematically (non-randomly) finds *all* permutations of the input without adjacent identical nuts, and then returns the first of these (or an empty list if there aren't any).

```
/|``p$/!>>$@!*
 |               # filter
  ``p            # all permutations of
     $           # the input list
                 # by
      /      *   # fold-by-multiplication
       !         #   zip together
        >>$      #     list without first element
           @     #     the same list
            !    #     are elements equal?
/                # finally get first element

```

# Answer
> 1 votes
## J, 80 characters

```
]`_:@.(0<2&([:+/=/\))({.~-:@#),((],.|.)~>.@-:@#)<"1;(\:#&.>)(</.])[;.1' ',1!:1[1

```

Not really in the same league as Golfscript on this one. I suspect there are gains to be made, but the 14 characters needed just to get the list into the program `[;.1' ',1!:1[1` is a major handicap.

Basically the program takes in the list, groups similar items together, sorts by number of items in each group descending, and alternates the output between the first half and the second half of the list. The rest if the code gets rid of extraneous items and decides if the list is valid output (outputting infinity `_` if it isn't).

Example:

```
macadamia walnut walnut pistachio walnut

```

group `(</.])`:

```
macadamia walnut walnut walnut pistachio

```

sort `(\:#&.>)`:

```
walnut walnut walnut macadamia pistachio

```

ravel `((],.|.)~>.@-:@#)`:

```
walnut macadamia walnut pistachio walnut

```

# Answer
> 1 votes
# Jelly, 14 bytes

```
Ġz0UẎḟ0ịµẋ⁻ƝẠ$

```

Try it online!

The last 6 bytes can be removed if we can have undefined behavior for invalid inputs.

# Answer
> 1 votes
# Stax, 10 bytes

```
│éÿ∞å[zàL⌂

```

Run and debug it

Here's the same program unpacked, ungolfed, and commented.

```
|T      get all permutations
{       block to filter by
  :g_=  after dropping repeated elements, it's still equal
f       execute filter
|c      terminate and pop if falsy (no match)
hJ      take the first permutation, and join with spaces

```

Run this one

---
Tags: code-golf, sorting, open-ended-function
---


title: Rotate an Image

text:
# Question
Title: Rotate an Image
This challenge is simple: Take a path to an `png` image file as input and overwrite that file with a copy of itself rotated 90 degrees clockwise. You may assume that the file has dimensions of 128x128 pixels. You may not use image metadata modifications (like Exif) to rotate the image; the pixels themselves must be transformed.

## Examples

Input:

Output:

This is , so shortest answer wins.

# Answer
# Bash/ImageMagick, 21 bytes

```
mogrify -rotate 90 $1

```

Conveniently this command overwrites the source file, and does not need the image to be of any specific dimensions.
> 12 votes

# Answer
# AutoHotkey \+ MSPaint, 77 Bytes

```
f(s){
run mspaint %s%
sleep 999
click 189,116
sleep 200
click 26,13
send ^s
}

```

Autohotkey is not a language that lends itself to golfing very well, though it is uniquely very good at pretending to be a user.

This simply opens paint with the target image, clicks the Rotate, then 90 degrees buttons, then presses CTRL+S to save the image.

Video of it Running
> 10 votes

# Answer
# Python \+ Pillow, ~~64~~ 59 bytes

```
from PIL.Image import*
open(p:=input()).rotate(-90).save(p)

```

*-5 thanks to @tsh*

#### Commented

```
from PIL.Image import*         # Import module
open(                          # Open an image
    p:=input()                 # Input the filename and store in p
).rotate(                      # Rotate the image
    -90                        # -90 degrees anti-clockwise
                               # (= 90 degrees clockwise)
).save(p)                      # And save it back in the original file

```
> 7 votes

# Answer
# MATL, 8 bytes

```
YiIX!GYG

```

Unfortunately the online compilers cannot load/save images so here is a demo that uses an image defined within the interpreter itself.

**Explanation**

```
     % Implicitly grab the first input (the file path) as a string
Yi   % Read in the image
IX!  % Rotate 270 degrees counter-clockwise
G    % Grab the file path again
YG   % Write the rotated image to this file

```
> 7 votes

# Answer
# NodeJS + JIMP, 74 bytes

```
require('jimp').read(n=process.argv[2]).then(x=>x.rotate(270,!1).write(n))

```

The path to image must be passed as third arg:

```
node filename.js imageSrc.png

```

## UPD 87 -\> 84

Thanks to Arnauld for the tip to reduce bytes count

## UPD 84 -\> 74

Thanks to Jacob for the tip to reduce bytes count
> 7 votes

# Answer
# MacOS zsh \+ sips, 13

```
sips -r 90 $1

```

sips (Scriptable Image Processing System) is a lesser-known built-in command-line utility for image manipulation. Confusingly, nothing to do with SIP (System Integrity Protection).

---

# MacOS zsh alias + sips, 10

```
sips -r 90

```

Create the alias with `alias r=sips -r 90`, then run with `r test.png`.
> 7 votes

# Answer
# APL (Dyalog Unicode), 64 bytes

Anonymous prefix lambda.

```
{b.MakePNG⎕NREPLACE,⍨⍵⎕NTIE-≡b.CBits←⌽⍉'CBits'⍎⍨'b'⎕WC'Bitmap'⍵}

```

`{``}` "dfn"; argument is denoted :

`'b'⎕WC'Bitmap'⍵` create a Bitmap `b` from the file

`'CBits'⍎⍨` extract the **C**olour **Bits** from that

transpose

mirror

`b.CBits←` update `b`'s Colour Bits to that value

get the array nesting depth of that (returns 1)

`-` negate (returns −1)

`⍵⎕NTIE` use that as file handle to tie the file (returns −1)

`,⍨` self-concatenate (we need a list of file handle and start position, where −1 means current position, i.e. at the start of the file)

`b.MakePNG⎕NREPLACE` replace the file contents with a render of `b` to PNG file contents
> 6 votes

# Answer
# Factor \+ `image.processing.rotation`, 52 bytes

```
[ dup load-image 90 rotate swap save-graphic-image ]

```

Testing the function in Factor's REPL:
> 6 votes

# Answer
# Python \+ opencv-python, ~~84~~ 62 bytes

```
import cv2
cv2.imwrite(p:=input(),cv2.rotate(cv2.imread(p),0))

```

*-22 thanks to @Stef*

Unfortunately for some reason when I do `from cv2 import*` it just doesn't work:

#### Commented

```
import cv2               # Import module
cv2.imwrite(             # Write to a file:
    p:=input()           #  Get the filename as input and store in p
    cv2.rotate(          #  A rotated version of:
        cv2.imread(p),   #   The contents of p
        0                #   Rotated 90 degrees clockwise
))                       # Close the parentheses

```
> 5 votes

# Answer
# Python + Pygame, 77 bytes

```
from pygame import*
image.save(transform.rotate(image.load(a:=input()),90),a)

```

Guess in terms of golfiness PIL/Pillow \> Pygame \> OpenCV
> 4 votes

# Answer
# Julia, 46 bytes

```
using Images
~f=save(f,imrotate(load(f),π/2))

```
> 4 votes

# Answer
# PowerShell Core, 58 bytes

```
%{$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)}

```

Input comes from the pipeline.

TIO won't work, what with the file, so the following assumes the cat above was downloaded to C:\Temp.

Try it in a PS 7 Console:

```
$path = 'C:\Temp\2iORu.png'
$path |
%{$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)}
Invoke-Item $path

```

# Windows PowerShell, 78 bytes

The System.Drawing assembly must be loaded, which costs 20 bytes as compared to Core.

```
%{Add-Type -A *.*wing;$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)}

```

Try it in a Windows PowerShell console:

```
$path = 'C:\Temp\2iORu.png'
$path |
%{Add-Type -A *.*wing;$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)}
Invoke-Item $path

```

Pretty straightforward: Starts the `%` cmdlet (alias for ForEach-Object)
Adds the assembly System.Drawing (not required in PS Core).
Loads the image file from the pipeline (in `$_`) into $p.
Then a bit of golfing can take place: `$p|% Ro* 1` pipes the image to % (ForEach-Object) and calls the image's method RotateFlip(RotateFlipType), with 1 being Rotate90FlipNone.
Then the image gets saved to the original location.
Invoke-Item shows the image in the default app for .png. You can of course leave out that line and open it with your favorite viewer.
> 3 votes

# Answer
# MATLAB/Octave, 33 bytes

```
@(x)imwrite(rot90(imread(x),3),x)

```
> 3 votes

# Answer
# PHP 7.4.33 + WideImage 11.02.09 \- 88 bytes

This relies on the WideImage library, which is an old library to manipulate images.

```
<?php include($x=WideImage)."/$x.php";$x::load($a=$argv[1])->rotate(90)->saveToFile($a);

```

You can use from PHP 5.2.0 to 7.4.33, but I've confirmed it works in 7.4.33 and 5.6.44.

This is meant to be executed from a command line/shell.

It does exactly what the code says: loads an image, rotates by 90º and overwrites the file.

# How to test this

Just follow these simple steps:

* Install PHP 7.4.33
* Create a PHP file *somewhere* convenient
* Put the code in that file
* Download WideImage \- DO NOT DOWNLOAD THE GITHUB VERSION
* Extract the `lib` folder
* Rename it to `WideImage`

To run it, just execute something like `php -f file.php image.png`.
> 1 votes

# Answer
# `feh` image viewer, 1

`feh` is an image viewer for the Unix X window system, first developed in 1999.

```
>

```

From linux.com:

> Type \> to rotate an image 90 degrees clockwise, and \< to rotate it 90 degrees counterclockwise. Your changes are immediately saved to the file.
> 0 votes

---
Tags: code-golf, image-processing
---


title: Random point inside boundary

text:
# Question
Title: Random point inside boundary
Given an ASCII art with simple closed paths using `|` and `-` (pipes and dashes), output a random point inside the boundary.

Eg. given:

```
----              ----
|  |-   ---  =>   |12|-   ---
|   |   | |       |345|   |6|
-----   ---       -----   ---
Any point 1-6 should have an equal probability of being printed.

```

## Specs

* Take a string, list of strings or a matrix containing `|`, `-`,
* Output either the ASCII art with a space replaced by a constant character other than a pipe, dash or space or print the two-dimensional/one-dimensional index.
* All adjacent pipe-dash pairs are connected
* This is , so the shortest answer wins

## Test cases

```
---
|1|
---

----
|12|-   ---
|345|   |6|
-----   ---

 ---
 |1|
--2--
|345|
-----

-------
|1---2|
|3|4|5|
|6---7|
-------

--- ---
|1| |2|
|3---4|
|56789|
---A---
  |B|
---C---
|DEFGH|
|I---J|
|K| |L|
--- ---

    ---
    |1|
    ---
---     ---
|2|     |3|         (4 simple closed paths)
---     ---
    ---
    |4|
    ---

```

# Answer
# MATL, ~~19~~ ~~18~~ ~~17~~ 15 bytes

```
36yy>t0ZI-flZr(

```

*2 bytes saved thanks to @LuisMendo*

Input is provided as a 2D character array and the random point is replaced by `$`

Try it out at MATL Online

**Explanation**

```
      % Implicitly retrieve the 2D character array input
36    % Push the literal 36 (ASCII for $) to the stack
y     % Make a copy of the character array
y     % Copy the value 36
>     % Create a boolean 2D array where all values with ASCII > '$' (36) are TRUE
      % these are the elements == '|' or '-' that make up the boundary
t     % Duplicate this boolean 2D array
0ZI   % Perform the morphological fill operation to set the value of all elements
      % within the boundaries to TRUE also
-     % Subtract the boundary to leave TRUE values only for elements that are
      % inside the boundary
f     % Find the index values of all remaining TRUE values
lZr   % Pick one at random
(     % And assign the '$' (36) to that element in the original input
      % Implicitly display the result

```
> 5 votes

# Answer
# Charcoal, ~~82~~ ~~81~~ 77 bytes

```
ＷＳ⊞υι≔⌈ＥυＬιθＰ⭆⪫υ¶⎇⁼ι ψι↖Ｂ⁺²θ⁺²Ｌυψ¤_↘ＴθＬυＦＬυＦθ«Ｊκι¤ »ＵＭＫＡ⎇⁼ι_ψι≔ΦＫＡ⁼ι θ§≔θ‽Ｌθ#

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings and marks the random selection with a `#`. Explanation:

```
ＷＳ⊞υι≔⌈ＥυＬιθ

```

Input the strings and calculate the width of the ASCII art.

```
Ｐ⭆⪫υ¶⎇⁼ι ψι

```

Output the art but with spaces replaced with background.

```
↖Ｂ⁺²θ⁺²Ｌυψ¤_↘ＴθＬυ

```

Add extra background padding, fill it with `_`s, and then remove the extra padding.

```
ＦＬυＦθ«Ｊκι¤ »

```

Replace any remaining background with spaces.

```
ＵＭＫＡ⎇⁼ι_ψι

```

Replace any remaining padding with background.

```
≔ΦＫＡ⁼ι θ§≔θ‽Ｌθ#

```

Randomly replace a space with a `#`.
> 4 votes

# Answer
# 05AB1E, ~~81~~ ~~78~~ 77 bytes

```
.B€SðQ2Fø1δ.ø}©˜ƶ®gäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅsM]¤θ©δÜ€¦˜0K®Êðs.;ÐÏSāDΩQ·.;0ð:

```

Uses `2` as random character.

Try it online or verify all test cases.

**Explanation:**

Step 1: Pad the input with trailing spaces to make it a rectangle, and add an additional border of spaces. Then convert it to a matrix of 0s for `|` and `-`, and give each space an unique 1-based integer value.

```
.B           # Blockify the (implicit) multi-line input by adding trailing spaces,
             # and then split it on newlines
  €S         # Convert each line to a list of characters
    ðQ       # Check for each character whether it's a space (1 if space; 0 otherwise)
2Fø1δ.ø}     # Add a border of 1s:
2F     }     #  Loop 2 times:
  ø          #   Zip/transpose; swapping rows/columns
    δ        #   Map over each inner list/row:
   1 .ø      #    Surround it with a leading/trailing 1
©            # After the loop: store the matrix in variable `®` (without popping)
 ˜           # Flatten it to a single list
  ƶ          # Multiply each value by its 1-based index
   ®g        # Push the length (aka amount of rows) of matrix `®`
     ä       # Split the list of integers back into a matrix of that many rows

```

Try just this first step online.

Step 2: Flood-fill the positive values in the matrix to identify the islands of spaces:

```
Δ            # Loop until it no longer changes to flood-fill:
 2Fø0δ.ø}    #  Add a border of 0s around the matrix:
 2F     }    #   Loop 2 times:
   ø         #    Zip/transpose; swapping rows/columns
     δ       #    Map over each row:
    0 .ø     #     Add a leading/trailing 0
 2Fø€ü3}     #  Convert it into overlapping 3x3 blocks:
 2F    }     #   Loop 2 times again:
   ø         #    Zip/transpose; swapping rows/columns
    €        #    Map over each inner list:
     ü3      #     Convert it to a list of overlapping triplets
 ®*          #  Multiply each 3x3 block by the value in matrix `®`
             #  (so the 0s remain 0s)
 εεÅsyøÅsM   #  Get the largest value from the horizontal/vertical cross of each 3x3
             #  block:
 εε          #   Nested map over each 3x3 block:
   Ås        #    Pop and push its middle row
     y       #    Push the 3x3 block again
      ø      #    Zip/transpose; swapping rows/columns
       Ås    #    Pop and push its middle rows as well (the middle column)
         M   #    Push the flattened maximum of the entire (scoped) stack,
             #    which is the flattened maximum of the cross of the current 3x3 block
]            # Close the nested maps and flood-fill loop

```

Try just the first two steps online.

Step 3: Remove the border and all right-padded trailing space-integers. Then replace that same value to 0s and every other value to 1s in the input-string.

```
¤            # Push the last row (without popping the matrix)
 θ           # Pop and push its last item
  ©          # Store this space-integer in variable `®` (without popping)
   δ         # Map over each row with this space-integer as argument:
    Ü        #  Remove all trailing space-integers from the row
     €       # Map over each row again:
      ¦      #  Remove its first character (the leading column of space-integers)
       ˜     # Then flatten the matrix to a list
        0K   # Remove all 0s (the "-" and "|")
          ®Ê # Check for each remaining spaces-value that it's NOT equal to `®`
             # (1 if it's a space inside a boundary; 0 if it's a space outside boundary)
ð            # Push a space character " "
 s           # Swap so this list of 0s/1s is at the top
  .;         # Replace all spaces in the (implicit) input one by one with these 0s/1s

```

Try just the first three steps online.

Step 4: Transform all `1`s into `0`s, except for a random one, which we'll make `2` instead.

```
Ð            # Triplicate the modified input-string
 Ï           # Pop two copies, and only keep all 1s
  S          # Convert this string of 1s to a list of 1s
   ā         # Push a list in the range [1,length] (without popping the list of 1s)
    D        # Duplicate it
     Ω       # Pop and push a random integer from this list
      Q      # Check which one in the list is equal to it
             # (so we have a list of 0s with one random 1)
       ·     # Double each, so the 1 becomes a 2 (0s remains 0)
        .;   # Then replace all 1s in the modified input one by one with these 0s/2s

```

Try just the first four steps online.

Step 5: Finally replace all `0`s back to spaces. After which we output the result.

```
0ð:          # Replace every 0 back to a space
             # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Vyxal, 32 bytes

```
2(ðvø.∩)∩ðÞIk□"λhn÷:k□ẊṠJ↔";Ẋ÷F℅

```

Try it Online!

Expects a rectangular matrix containing `|`, `-`, . Returns a 2D index.

## How?

Surround the input with spaces from all sides.

```
2(     )  # repeat twice:
  ð       #   push a space
   vø.    #   vectorized surround
      ∩   #   transpose
        ∩ # transpose

```

Find the coordinates of all spaces that are in the outside component.

```
ðÞI                  # get the coordinates of all spaces
   k□                # push cardinal directions [[0,1],[1,0],[0,-1],[-1,0]]
     "               # pair
      λ           ;Ẋ # apply the following function until a fixed point:
                         Takes a pair [coordinates of all spaces,  coordinates spaces reached so far]
       h             #   head
        n            #   argument
         ÷           #   push each to stack
          :          #   duplicate
           k□        #   push cardinal directions [[0,1],[1,0],[0,-1],[-1,0]]
             Ẋ       #   cartesian product
              Ṡ      #   vectorising sum
               J     #   join the top two item on the stack
                ↔    #   keep only those items of a that are in b
                 "   #   pair

```

Now we have the pair `[coordinates of all spaces, coordinates of spaces reachable from one of the sides]`.

```
÷   # push each to stack
 F  # remove items from a that are in b
  ℅ # choose a random item

```
> 4 votes

# Answer
# JavaScript (Node.js),~~181 180~~ 178 bytes

```
f=x=>[...x+0,n=0].map(_=>{for(i in x)for(j in e=x[i])for(k of'0123')(x[+i+--k%2]||++n)[+j+--k%2]?r=n=>Math.random()*n|0:1/e[j]?e[j]=0:0})&&x[p=r(x.length)][q=r(n)]<'!'?[p,q]:f(x)

```

Try it online!

Didn't expect it runs in time
> 3 votes

# Answer
# Retina, 114 bytes

```
^
_¶
$
¶_
P`.+
.+
_$&_
+`_ | _|(?<=(.)*)( |_)(.*¶(?<-1>.)*(?(1)$)(?!\2))[ _]
_$3_
@`
#
^_+¶_|_+¶_+$|_+(¶)_
$1
_

```

Try it online! Marks the random selection with a `#`. Explanation:

```
^
_¶
$
¶_
P`.+
.+
_$&_

```

Pad the input and surround it with `_`s on all sides.

```
+`_ | _|(?<=(.)*)( |_)(.*¶(?<-1>.)*(?(1)$)(?!\2))[ _]
_$3_

```

Flood fill the `_`s so that only interior spaces remain.

```
@`
#

```

Randomly replace one with the output marker.

```
^_+¶_|_+¶_+$|_+(¶)_
$1
_

```

Remove the padding and replace any remaining `_`s with spaces.
> 3 votes

# Answer
# Python3, 770 bytes:

```
import random as U
E=enumerate
def T(b,x,y):
 D={}
 for i in b:D[i[x]]=D.get(i[x],[])+[i[y]]
 return D
def B(b):
 P=[(x,y)for x,r in E(b)for y,k in E(r)if' '!=k];p=[*P]
 while p:
  q=[(r:=p.pop(0),[r])]
  while q:
   F=0
   (x,y),r=q.pop(0)
   for X,Y in[(1,0),(-1,0),(0,-1),(0,1)]:
    j,k=x+X,y+Y
    V=(j,k)
    if 0<=j<len(b)and 0<=k<len(b[0])and(len(r)<2 or V!=r[-2]):
     if(j==x and'-'==b[j][k])or(k==y and'|'==b[j][k])or b[x][y]!=b[j][k]:
      if V in r:yield r;p=[*({*p}-{*r})];F=1;break
      elif V in P:q+=[(V,[*r,V])]
   if F:break
def f(b):
 K=[]
 for i in B(b):
  Q,W=T(i,0,1),T(i,1,0)
  K+=[(x,y)for x,r in E(b)for y,k in E(r)if' '==k and x in Q and min(Q[x])<=y<=max(Q[x])and y in W and min(W[y])<=x<=max(W[y])]
 x,y=U.choice(K)
 b[x][y]='*'
 return b

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES11), 168 bytes

Expects a matrix of characters and returns the coordinates `[x,y]` of a cell.

```
m=>(o=[])[m.map((r,y)=>r.map((C,x)=>(g=(x,y,r=m[y],c=r?.[x])=>1/c?[-1,0,1,2].every(d=>g(x+d%2,y+~-d%2),r[x]=g)|(r[x]=c):!!c/C)(x,y)?n=o.push([x,y]):0))|Math.random()*n]

```

Attempt This Online!
(with some post-processing to insert an asterisk at the chosen position)

### How?

For each space in the input matrix, we process a recursive flood-fill to test whether we can 'escape' through a boundary. We keep track of each starting point for which this is not the case and return one of them.

### Commented

```
m =>                      // m[] = input matrix
(o = [])[                 // start with o[] set to an empty array
  m.map((r, y) =>         // for each row r[] at index y in m[]:
    r.map((C, x) =>       //   for each character C at index x in r[]:
      ( g = (             //     g is a recursive function taking:
          x, y,           //       (x, y) = current position
          r = m[y],       //       r[] = current row
          c = r?.[x]      //       c = character at this position
        ) =>              //
        1 / c ?           //     if c is a space:
          [-1, 0, 1, 2]   //       array of directions
          .every(d =>     //       for each direction d:
            g(            //         do a recursive call:
              x + d % 2,  //           add dx to x
              y + ~-d % 2 //           add dy to y
            ),            //         end of recursive call
            r[x] = g      //         start by invalidating the current cell
          ) |             //       end of every()
          (r[x] = c)      //       restore the current cell
        :                 //     else:
          !!c / C         //       return a truthy value (1/0 = +∞) if and
                          //       only if c is defined and C is a space
      )(x, y) ?           //     initial call to g; if truthy:
        n =               //       update n to the length of o[] ...
          o.push([x, y])  //       ... once [x, y] has been added to o[]
      :                   //     else:
        0                 //       do nothing
    )                     //   end of inner map()
  )                       // end of outer map()
  | Math.random() * n     // pick a random item from o[]
]                         //

```
> 2 votes

# Answer
# Python 3.8 (pre-release), 238 bytes

```
e=enumerate
a,*r={i+1j*j:c<'!'for i,r in e(open(0))for j,c in e(r)},
while q:=[i for i in a if a[i]][:1]:
 g,*v=1,
 while q:
  c,*q=q;a[c]=0;v+=[c]
  for i in-1,1,-1j,1j:q+=[c+i]*a.get(c+i,0);g&=c+i in a
 r+=v*g
print({*map(str,r)}.pop())

```

Try it online!

Flood-fills from every space position and stores the ones that do not go out of bounds. Then it relies on hash randomization for strings to pop a random coordinate from the final set.
> 1 votes

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


title: Number Clusters

text:
# Question
Title: Number Clusters
Your task is to create a program or function, that when given an input list of nonnegative integers of length \\$l \ge 2\\$ and a nonnegative integer \\$c\\$ where \\$2 \le c \le l\\$, group the list into \\$c\\$ "clusters." What this means is, the average (population) variance* of all the groups should be as low as possible.

For example, `[[0, 3], [4, 6]]` has an average variance of \\$\frac{\frac{\left(0-\frac{0+3}{2}\right)^2+\left(3-\frac{0+3}{2}\right)^2}{2}+\frac{\left(4-\frac{4+6}{2}\right)^2+\left(6-\frac{4+6}{2}\right)^2}{2}}{2}\\$ or \\$1.625\\$, while `[[0], [3, 4, 6]]` has an average variance of \\$\frac{\frac{\left(0-\frac{0}{1}\right)^2}{1}+\frac{\left(3-\frac{3+4+6}{3}\right)^2+\left(4-\frac{3+4+6}{3}\right)^2+\left(6-\frac{3+4+6}{3}\right)^2}{3}}{2}\\$ or \\$\frac{7}{9}\\$, and \\$\frac{7}{9} \< 1.625\\$, so the latter is the correct output for the first test case. The result will have the closest numbers placed together and the farthest numbers placed in different groups.

<sub>\*This is calculated by squaring the distance between all the numbers in the list and the mean of it, and then taking the mean of those squared distances.</sub>

# Rules

* Groups and numbers inside of the groups can be in any order.
* When there are multiple possible outputs with the same average variance, any of them is acceptable.
* Each group must have at least one number.
* Input and output may be in any convenient format.
* This is , so the shortest answer in bytes wins.

# Test Cases

```
Input                          Output (sorted)

[0, 3, 4, 6], 2                [[0], [3, 4, 6]]
[0, 1, 2, 3], 2                [[0, 1], [2, 3]]
[0, 1, 2, 3, 4], 2             [[0, 1], [2, 3, 4]] or [[0, 1, 2], [3, 4]]
[10, 13, 6, 11, 8], 3          [[6, 8], [10, 11], [13]]
[4, 2, 9], 3                   [[2], [4], [9]]
[1, 19, 8, 12, 3, 19], 3       [[1, 3], [8, 12], [19, 19]]
[8, 8, 8, 8], 2                [[8], [8, 8, 8]] or [[8, 8], [8, 8]]

```

# Answer
# Vyxal, 17 bytes

```
søṖ'L⁰=;‡ƛṁ-²ṁ;∑∵

```

Try it Online!

```
s                 # sort
 øṖ               # all partitions
   '   ;          # filter by:
    L             #   length
      =           #   is equal to
     ⁰            #   last input
        ‡       ∵ # minimum by:
         ƛ    ;   #   map:
          ṁ-      #     subtract mean
            ²     #     square
             ṁ    #     mean
               ∑  #   sum

```
> 4 votes

# Answer
# JavaScript (ES7), 182 bytes

Expects `(list)(c)`.

```
a=>m=c=>eval("for(q=c**a.length;p=a.slice(-c).map((_,j)=>a.filter((_,i)=>!(q/c**i%c^j))),q--;)p.some(A=>A.map(v=>s+=(v-eval(A.join`+`)/w)**2/w,w=A.length)=='',s=0)|s>m||(m=s,o=p);o")

```

Try it online!

### Commented

This is a version without `eval()` for readability.

```
a =>                     // a[] = input list
m =                      // initialize m to a non-numeric value
c => {                   // c = number of clusters
  for(                   // main loop:
    q = c ** a.length;   //   start with q = c ** a.length
    p = a.slice(-c)      //   p[] = partition of length c
    .map((_, j) =>       //   for each value in p[] at index j:
      a.filter((_, i) => //     for each value in a[] at index i:
        !(               //       keep the value if
          q / c ** i % c //       floor(q / c ** i) mod c
          ^ j            //       is equal to j
        )                //
      )                  //     end of filter()
    ),                   //   end of map()
    q--;                 //   stop once q = 0 has been processed
  )                      //
  p.some(A =>            //   for each array A[] in p[]:
    A.map(v =>           //     for each value v in A[]:
      s += (             //       add to s:
        v -              //         v minus
        eval(A.join`+`)  //         the sum of all values in A[]
        / w              //         divided by w (the length of A[])
      ) ** 2 / w,        //       squared and divided by w again
      w = A.length       //       initialize w
    )                    //     end of map()
    == '',               //     trigger the some() if A[] was empty
    s = 0                //     start with s = 0
  )                      //   end of some(); if the result is falsy
  | s > m ||             //   and we don't have s > m:
    (m = s, o = p);      //     update the minimum and the output array
                         // (implicit end of for)
  return o               // return the output array
}                        //

```
> 3 votes

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

```
{.y@*<+/'x''a*a:y-x''y@:='+z\&z=#'?'+!z|^y}{+/x%#x}

```

Try it online!
> 3 votes

# Answer
# Charcoal, ~~45~~ 44 bytes

```
Ｉ⊟⌊ＥΦＥＸηＬθＥηΦθ⁼λ﹪÷ιＸηξη⌊ι⟦ΣＥι∕ΣＥλΣＸ⁻νλ²ＸＬλ²ι

```

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

```
ＥＸηＬθＥηΦθ⁼λ﹪÷ιＸηξη

```

All permutations of the input list elements into `c` clusters...

```
Φ...⌊ι

```

... where no cluster is empty...

```
Ｅ...⟦ΣＥι∕ΣＥλΣＸ⁻νλ²ＸＬλ²ι

```

... calculate the doubled variance of each cluster...

Ｉ⊟⌊...

... output the clusters with the minimum.

Edit: Saved 1 byte by calculating the doubled variance using the last alternative variance formula for finite populations:

$$ \textrm{Variance(X)} = \frac{1}{2N^2} \cdot \sum\_{i=1}^{N} \sum\_{j=1}^{N} (x\_i - x\_j)^2 $$
> 3 votes

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

```
f=([c,...x],n,L=P=x.slice(-n).map(_=>[]))=>1/c?L.map((_,i)=>f(x,0,L.map(x=>i--?x:[...x,c])))&&P:P=B(P)<B(L)?P:L;A=x=>x.map(t=>X+=++Y&&t,X=Y=0)+x?X/Y:1/0;B=L=>A(L.map(x=>A(x.map(v=>(v-A(x))**2))))

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 21 bytes

```
{.œʒg²Q}ΣεDÅA-nÅA}O}н

```

Try it online!

Port of AndrovT's Vyxal answer.

#### Explanation

```
{.œʒg²Q}ΣεDÅA-nÅA}O}н  # Implicit input
{                      # Sort the first input
 .œʒ   }               # Filter its partitions by:
    g                  #  Length of list
     ²Q                #  Equals the second nput
        Σ          }н  # Minimum by:
         ε       }     #  Map:
           ÅA          #   Get mean
          D  -         #   Subtract
              n        #   Square
               ÅA      #   Get mean
                  O    #  Sum
                       # Implicit output

```
> 1 votes

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


title: Implement pow with overflow checking

text:
# Question
Title: Implement pow with overflow checking
Implement a function or program which raises `x` to the power of `y`. Inputs are 16-bit signed integers. That is, both are in the range \[-32768, 32767\]. The output should be in the same range. I chose this range because it should make it possible to do exhaustive testing to ensure all edge-cases are covered.

If the output can't be represented (it's too negative, too positive or not an integer), do one of the following:

* Throw an exception
* Print an error message
* Return a special value (-1, 0 or any other specific value)

Please document what your implementation does in case of error; the behavior should be identical for all error cases — the same exception, message or exceptional value!

By definition, 0 to the power of 0 is 1 (not "error").

I am most interested in non-trivial solutions, but if your language has a suitable `pow` function, you are allowed to use it!

Test cases:

```
pow(-32768, -32768) = error
pow(-32768, -1) = error
pow(-32768, 0) = 1
pow(-32768, 1) = -32768
pow(-32768, 2) = error
pow(-32768, 32767) = error
pow(-100, 100) = error
pow(-180, 2) = 32400
pow(-8, 5) = -32768
pow(-3, -2) = error
pow(-3, 9) = -19683
pow(-2, 15) = -32768
pow(-1, -999) = -1
pow(-1, -100) = 1
pow(-1, 100) = 1
pow(-1, 999) = -1
pow(0, -100) = error
pow(0, -1) = error
pow(0, 0) = 1
pow(0, 999) = 0
pow(1, -999) = 1
pow(1, 10000) = 1
pow(1, 9999) = 1
pow(2, 14) = 16384
pow(2, 15) = error
pow(8, 5) = error
pow(4, 7) = 16384
pow(181, 2) = 32761
pow(182, 2) = error
pow(10000, 1) = 10000

```

# Answer
# Rust, 68 bytes

```
|x:i16,y:i16|x.checked_pow(match x{1|-1=>y&1,_=>y}.try_into().ok()?)
```

Attempt This Online!

Probably not the best language to golf in, but when I saw the description I immediately thought that `checked_pow` would be a perfect built-in for this task. The equivalent doesn't exist in every single other language I know of.

Returns `Some(x**y)` if the result is well-defined and fits in the `i16` range, `None` otherwise.

```
|x:i16,y:i16|           A closure that takes two i16 values
x.checked_pow(...)      Raise x to the power of ... (but the power must be u32)
                        The only cases where negative power makes sense are 1 and -1
match x{                so let's match on x and
1|-1=>y&1,              if it is 1 or -1, use y modulo 2 (non-negative)
_=>y}                   and simply use y otherwise
.try_into()             and try converting to u32 (inferred)
.ok()                   and convert the Result<u32,E> to Option<u32>
?                       and return None immediately if the conversion fails

```
> 14 votes

# Answer
# JavaScript (ES7),  ~~46~~  41 bytes

*Saved 5 bytes thanks to @Neil*

Expects `(x)(y)`. Returns `false` for errors.

```
x=>y=>(q=x**y/(y>=0|x*x<2))==q<<16>>16&&q

```

Try it online!

### Commented

```
x =>            // given x
y =>            // and y
(               //
  q =           // compute and save in q:
    x ** y /    //   x ** y
    (           //   leave it unchanged if:
      y >= 0 |  //     y is non-negative
      x * x < 2 //     or x² is 0 or 1
    )           //   otherwise: divide by 0, leading to +/- Infinity
) ==            // test whether the result is invariant by shifting it ...
q << 16 >> 16   // ... by 16 positions to the left and then to the right
&& q            // if it is: return q (or return false otherwise)

```
> 9 votes

# Answer
# Ruby, <sup>~~30~~</sup> 29 bytes

```
->x,y{[x**=y][x>>15]rescue p}

```

Try it online!

Returns `nil` for errors.
> 8 votes

# Answer
# PARI/GP, 36 bytes

```
f(x,y)=iferr([z=x^y,z][2+z>>15],t,e)
```

Attempt This Online!

A port of Dingus's Ruby answer. Returns `e` for errors.
> 6 votes

# Answer
# Python 3, 41 bytes

```
lambda x,n:int([x**n][x*x>1and x**n>>15])

```

Try it online!

TIO link using codes from movatica's answer.

This function throw errors when failed. But different errors for different testcases.

Code `lambda x,n:[x**n][x**n>>15]` failed when \\$\lvert x\rvert=1 \land n\<0\\$.
> 5 votes

# Answer
# Desmos, ~~86~~ ~~78~~ 77 bytes

```
k=32768
g(n)=\{-k<=n<k\}\{\mod(n,1)=0\}
f(a,b)=g(a)g(a^b)g(b)a^b\{b>=0,aa=1\}

```

Returns `undefined` for errors. Not sure if this is fully correct, but it at least passes all the test cases.

Try It On Desmos!

Try It On Desmos! - Prettified
> 4 votes

# Answer
# Retina, 114 bytes

```
^(-?1,)-
$1
/,-/(K`
T`-`_`.+[02468]$
~`-?(.+),(.+)
\d.+¶$$.($2*$($1$*)_
A`\d{6}
\d+
*_#
A`^(-_)?_{32768}
(_*)#
$.1

```

Try it online! Link includes test cases modified to run in a reasonable amount of time on TIO. Outputs nothing in case of error. Explanation:

```
^(-?1,)-
$1

```

Negating the exponent of `1` or `-1` has no effect.

```
/,-/(K`

```

Other negative exponents are an error, otherwise:

```
T`-`_`.+[02468]$

```

Even exponents always produce a non-negative result.

```
~`-?(.+),(.+)
\d.+¶$$.($2*$($1$*)_

```

Perform the exponentiation by evaluation of repeated multiplication of `1` by the base.

```
A`\d{6}

```

Values of six or more digits are an error.

```
\d+
*_#

```

Convert to unary, with a marker to make it golfier to convert negative numbers back to decimal. (Conveniently it also makes it possible to distinguish between `0` and error.)

```
A`^(-_)?_{32768}

```

Values of `32768` or `-32769` or greater absolute value are an error.

```
(_*)#
$.1

```

Convert to decimal.
> 4 votes

# Answer
# C (gcc), ~~43~~ 42 bytes

```
f(a,b){float c=pow(a,b);a=c-(short)c?0:c;}

```

Try it online!

1 byte shaved off thanks to ceilingcat.

Uses the standard library's `pow()`, which works on `double`s, which themselves might overflow but will then become ±infinity, and then checking if the result is representable as a `short`.
> 4 votes

# Answer
# x86-16 machine code, 12 bytes

Could save 1 byte by using opcode `CE` (`into`) to trap on OF=1, instead of jumping to return from the function.

* 32-bit mode: 13 bytes: need a 66 operand-size prefix for `imul si`, rest can use the same machine code bytes, which will give 32-bit operand-size. (So in source you'd write it as `xor eax,eax`/`inc eax`. And `jecxz`. `loop` automatically uses the address-size as the width of CX/ECX/RCX it uses, so the mode-sized width of that register is significant as an arg.)
* 64-bit mode, 14 bytes: like 32-bit plus `inc eax` is a 2-byte instruction. (Negative exponents will run nearly 2^64 iterations, so rather impractical, unlike 32-bit bit mode where it only takes a couple seconds when the base is `-1` so it doesn't overflow.)

**Fixme: non-competing, doesn't handle `pow(0, -100) = error`, instead returns 0**. Handles any non-zero base with any exponent, or any base with any non-negative exponent. I don't see why it's interesting to have an integer power function allow negative exponents in the first place; unsigned or guaranteed non-negative would make more sense. But I think this is interesting because `0 ** (unsigned)n` with overflow-checked multiply comes so close to handling everything without any special work to deal with negative exponents.

NASM listing: address, machine-code (the answer proper), source

```
                    checked_pow:      ; x in SI,  n in (ER)CX
 00 31C0               xor  ax,ax
 02 40                 inc  ax      ; mov [e]ax,1  and clear OF
 03 E306               jcxz  .exit
                   .loop:              ;do{
 05 F7EE               imul  si         ; total *= x;
 07 7002               jo  .exit        ; break on signed overflow of the low half (i.e. if cwd would change DX)
 09 E2FA               loop .loop      ;}while(--n!=0);
                   .exit:
 0B C3                 ret

```

Function taking args in SI and CX, returning an out-of-band error status in OF (the overflow flag), and a value in AX. **The AX value is meaningful if OF=0, otherwise there was overflow.** (So just like an instruction like `add`; the caller can `into` to trap on overflow if they want, or `jo` like this function did.)

Widening multiply can't actually lose any bits, so x86's `mul` and `imul` instructions set FLAGS according to whether the low half is the same as the full result. i.e. whether the high half is the zero- or sign-extension of the low half respectively. i.e. after `imul`, if `cwd` to sign-extend AX into DX:AX would change anything. If the result doesn't fit in the low half, CF=OF=1, otherwise they're cleared to zero.

Corner case handling:

* `x^0` (including 0^0) correctly returns 1, detected with `jcxz`. If not for this, could save 2 bytes
* `x^negative` correctly overflows for `|x| > 1`, because **`loop` treats the count as unsigned**. Any negative exponent is treated as an unsigned exponent of at least 32768 (in 16-bit mode; much higher in 32 or 64-bit mode if sign-extended into ECX or RCX as required, instead of zero-extended to be large positive).

Any base other than 1, 0, or -1 will result in signed overflow in at most 16 iterations.
* `-1^negative` correctly returns 1 or -1, according to the exponent being odd or even. Negative even two's complement signed integers have their low bit clear, so represent even unsigned numbers. To put it another way, `-1^-n = -1^|n|`, and 2's complement absolute value doesn't change the low bit.
* `0^negative`: **unhandled**, we just do `0 ** (unsigned)n`, producing zero without overflowing like we should for 1/0.

---

Semi-related: Implement Binary Exponentiation shows a more efficient algorithm (more bytes, but much faster for large `n`. Of course overflow happens so fast that it's not a big deal except for degenerate cases like `1` and `-1` with huge exponents. Since we don't need performance here, it's of course smaller code to just use the O(n) algorithm.
> 4 votes

# Answer
# C (gcc), 73 bytes

```
c;f(a,b){c=b?b>0||!(a+1&~2)&&(b=-b)?a*f(a,b-1):0:1;return(short)c-c?0:c;}

```

Try it online!

(-1 bytes @ceilingcat)
(-5 bytes @JuanIgnacioDíaz)

Returns `0` for error.
> 3 votes

# Answer
# Charcoal, 34 bytes

```
ＮθＮη¿∨⁼¹↔θ¬‹η⁰ＩΦ⟦Ｘθ↔η⟧№…±Ｘ⁸¦⁵Ｘ⁸¦⁵ι

```

Try it online! Link is to verbose version of code. Outputs nothing in case of error. Explanation:

```
ＮθＮη

```

Input `x` and `y`.

```
¿∨⁼¹↔θ¬‹η⁰

```

If the absolute value of `x` is `1` or `y` is non-negative, then:

```
ＩΦ⟦Ｘθ↔η⟧№…±Ｘ⁸¦⁵Ｘ⁸¦⁵ι

```

Output `x` to the power of `y` if it lies in the range `[-32768,32768)`.
> 3 votes

# Answer
# Husk, ~~13~~ 11 bytes

```
S&€hṡ32768^

```

Try it online! or try some of the test-cases

Outputs `0` as 'special value' for error.

```
          ^    # pow without overflow/error checking;
    ṡ32768     # range from -32768 to 32768
   h           # without the last element
               # (so: -32768 to 32767);
  €            # is the pow a member of this range?
S&             # if yes, output the pow
               # if no, output falsy = zero

```
> 1 votes

# Answer
## Pascal, 52 B

The ISO standard 10206 “Extended Pascal” defines the integer power operator `pow`. NB: Zero to the power of zero causes an error. Provided that the implementation-defined value of the required constant `maxInt` is greater than or equal to `32768` you can wrap `pow` into a function like this:

```
function f(x,y:integer):integer;begin f:=x pow y end

```

The standard specifies that

> It shall be an error if an integer operation or function is not performed according to the mathematical rules for integer arithmetic.

An *error* is

> A violation by a program of the requirements of this International Standard that a processor is permitted to leave undetected.

Thus *whether* and *how* an overflow is signaled is at the compiler developer’s discretion.
> 1 votes

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


title: Reverse positive runs

text:
# Question
Title: Reverse positive runs
## Input

Your input is a list of single-digit numbers in any reasonable format, including a string of digits. The input will not be empty.

## Output

Your output shall be the input list, but with each maximal run of nonzero digits being reversed.

## Example

Consider the input

```
95883007414830
<--->  <---->

```

where the nonzero runs have been marked with arrows. Reversing each of these runs, we obtain the output

```
38859003841470

```

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

This challenge is related, but much more complex, since it includes additional string processing.

## Test cases

```
4 -> 4
00 -> 00
123 -> 321
0010 -> 0010
12000345 -> 21000543
18161604 -> 61618104
95883007414830 -> 38859003841470
010230456078912 -> 010320654021987
357509902003550 -> 575309902005530
2492882377675046 -> 5767732882942064
03026302053000357099 -> 03036202035000753099

```

## Leaderboard

Here's a Stack Snippet to generate a leaderboard and list of winners by language. To make sure your answer shows up, start it with a header of the form

```
## Language, N bytes

```

You can keep old scores in the header by using the strikethrough tags: `<s>57</s>` will appear as ~~57~~.

```
/* Configuration */

var QUESTION_ID = 78510; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 32014; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
```

# Answer
> 12 votes
# Pyth, 8

```
j0_Mcz\0

```

Split on zeros, reverse and join back on zeros.

Test Suite

# Answer
> 8 votes
# IPOS, 5 bytes

```
'0!r%

```

`%` splits the input string on zeroes, applies the command `r` (reverse) to every substring and joins the result back on zeroes.

# Answer
> 8 votes
## Retina, 15 bytes

```
S`0
O%^$`.

¶
0

```

Try it online! (Slightly modified to run all test cases at once.)

### Explanation

```
S`0

```

Split the input around `0`s that is, put each (possibly empty) run of non-zero digits on its own line.

```
O%^$`.

```

This reverses each line, by:

* Applying the stage to each line individually with `%`.
* Matching each character individually with `.`.
* Sorting it by the result of the substitution (`$`) with the empty string (the empty second line). I.e. it doesn't sort at all, since all sort values are identical.
* Then reverses the order of the sorted characters.

Finally:

```
¶
0

```

Turn the linefeeds back into `0`s.

# Answer
> 5 votes
# 05AB1E, 6 bytes

Code:

```
0¡€R0ý

```

Explanation:

```
0¡      # Split on zeros
  €R    # For each item in the array, reverse it
    0ý  # Join by zeros

```

Uses **CP-1252** encoding. Try it online!.

# Answer
> 5 votes
# Julia, 30 bytes

```
s->replace(s,r"[^0]+",reverse)

```

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.

The `replace` function provides the ability to replace matches of a regular expression with the result of a function applied to each match. In this case we can get nonzeros using `[^0]+` and replace those runs with the result of the `reverse` function applied to the matched text.

Verify all test cases online!

# Answer
> 4 votes
# Jolf, 8 bytes

```
RΜGi0λ_0

```

Try it here!

## Explanation

```
RΜGi0λ_0
  Gi0     split input on zeroes
 Μ   λ_   map over reversal as a lambda
R      0  join by zeroes

```

The code explanation looks sort of like a lambda if you squint.

An equivalent 8-byte answer:

```
RΜGi0΅O0

```

Same thing, but it uses `΅O` (string mirror lambda) instead.

# Answer
> 4 votes
# Retina, ~~25~~ 24

```
O^$#`[^0](?=(.*?0)*)
$#1

```

Try it online

Saved 1 byte thanks to Martin!

Sort the nonzero digits by the number of zeros that follow the digit, in reverse order.

See Martin's solution for a clever use of per-line mode to get a shorter program!

# Answer
> 3 votes
# Mathematica, 30 bytes

```
Join@@Reverse/@#~SplitBy~Sign&

```

e.g. `Join@@Reverse/@#~SplitBy~Sign&[{1,2,3,0,0,5,9,0}]` = `{3, 2, 1, 0, 0, 9, 5, 0}`

# Answer
> 3 votes
## Ruby, 29 bytes

```
->x{x.gsub /[^0]*/,&:reverse}

```

# Answer
> 3 votes
# Jelly, 5 bytes

```
ṣ0Uj0

```

Try it online!

# Answer
> 3 votes
# Python, ~~58~~ 50 bytes

```
lambda x:"0".join([n[::-1] for n in x.split("0")])

```

Takes in a string x and splits on the zeros and reverses each element in the split and adds a zero and returns the this minus last zero.

# Answer
> 2 votes
## PowerShell v2+, 45 bytes

```
($args-split0|%{-join$_[$_.length..0]})-join0

```

Abusing the implicit casting like there's no tomorrow. Likely can't get much shorter, as there's no builtin for reverse that's shorter than this indexing trick.

### Explanation

An example of how this works -- suppose `123045` was the input `$args`. After the `-split` on `0`, the pipeline would contain an array `(123,45)`. The first loop with `|%{...}` has the current element `$_` equal to `123`, which is then implicitly cast as a string, then reversed with the `[]` indexing. That makes it `('3','2','1')` as a char-array. The loop's `-join` puts that back into a string `"321"` and leaves it on the pipeline. The next (last) loop iteration reverses the input to `"54"`. So now our pipeline is `"321"`, `"54"`. That's encapsulated in parens `()` so it's reformed into an array, and re`-join`ed back together with zeros to produce the resultant output string `"321054"`. That's left on the pipeline and output to the console is implicit.

If there are subsequent zeros in the original input, the array would be populated with null elements, so there are the correct number of zeros on the output. For example, `1230045-split0` turns into `(123,,45)` and things continue as above.

# Answer
> 2 votes
## Haskell, 45 bytes

```
r%(0:t)=r++0:[]%t
r%(h:t)=(h:r)%t
r%_=r
([]%)

```

Recursively accumulates the reversed chunk so far in `r`, prepending it when a `0` is reached. When the remaining string is empty, it also discharges `r`.

The first two repeat some code, but I didn't find a shorter way to combine them (45 and 47 bytes):

```
r%(h:t)|h<1=r++h:[]%t|1>0=(h:r)%t
r%_=r
([]%)

r%l|0:t<-l=r++0:[]%t|h:t<-l=(h:r)%t
r%_=r
([]%)

```

# Answer
> 2 votes
# Factor, 35 bytes

Beating Pyfon and Clojure, booyah!

```
[ "0"split [ reverse ] map "0"join ]

```

This anonymous function is a literal translation of this Python answer.

It's quite simple, just split the string on zeroes, reverse every element of the resulting array, and join all the elements (including zero-length strings) with `"0"`.

Here's an example of it running on all test cases:

```
IN: scratchpad auto-use {
        "4"
        "00"
        "123"
        "0010"
        "12000345"
        "18161604"
        "95883007414830"
        "010230456078912"
        "357509902003550"
        "2492882377675046"
        "03026302053000357099"
        }
        [
          "0" split [ reverse ] map "0" join
        ]
        map .

{
    "4"
    "00"
    "321"
    "0010"
    "21000543"
    "61618104"
    "38859003841470"
    "010320654021987"
    "575309902005530"
    "5767732882942064"
    "03036202035000753099"
}

```

`"00120"` -\> `{ "" "" "12" "" }` -\> `{ "" "" "21" "" }` -\> `"00210"`

# Answer
> 1 votes
# J, ~~20~~ 18 bytes

```
0}:@;@(<@|.;.1)@,]

```

Thanks to Zgarb for helping with this! Takes a space-separated list as a right argument.

-2 bytes thanks to Zgarb!

# Answer
> 1 votes
## Pyke, 8 bytes

```
\0cm_\0J

```

Explanation:

```
\0c      -   input().split("0")
   m_    -  map(reversed, ^)
     \0J - "0".join(^)

```

Try it here!

# Answer
> 1 votes
# JavaScript (ES6), ~~50~~ 49 bytes

String version:

```
s=>s.replace(/[^0]+/g,r=>[...r].reverse().join``)

```

*Saved a byte thanks to @Kevin Lau!*

Array version (60 bytes):

```
a=>a.map((n,i)=>n?a[z-i+[...a,0].indexOf(0,i)]:(z=i,0),z=-1)

```

# Answer
> 1 votes
# Clojure/ClojureScript, 44 chars

```
#(flatten(map reverse(partition-by pos? %)))

```

Same solution as others, just more verbose thanks to long function names. Wasn't going to post it because of that, but it beats some other answers so why not?

Works on any sequence type. In ClojureScript, this also works on strings since strings are processable as lists of characters, which are really just 1-length strings, which coerce to numbers for things like `pos?`.

# Answer
> 1 votes
## Haskell, 46 bytes

```
import Data.Lists
(reverse=<<).split(oneOf"0")

```

Usage example: `(reverse=<<).split(oneOf"0") $ "0123004500678090"`-\> `"0321005400876090"`.

Sadly the `split` function requires the expensive import. Split the input list at every `0`, e.g. `split(oneOf"0") "0120030"` -\> `["","0","12","0","","0","3","0",""]`, reverse each chunk and concatenate into a single string.

# Answer
> 1 votes
# F#, 103 bytes

```
let f x=x="";x.Split '0'|>Array.map(fun s->System.String(s|>Seq.toArray|>Array.rev))|>String.concat "0"

```

# Answer
> 1 votes
# Java, 179 bytes(with import)

```
import java.util.*;static void r(String s){StringJoiner x= new StringJoiner("0");for(String a:s.split("0",s.length())){x.add(new StringBuilder(a).reverse());}System.out.print(x);}

```

Takes in a string input and splits the characters by zero then adds them back by calling the add method on the StringJoiner class.

# Answer
> 1 votes
# Oracle SQL 11.2, ~~131~~ 123 bytes

Abusing XML functions.

```
SELECT LISTAGG(REVERSE(COLUMN_VALUE||''))WITHIN GROUP(ORDER BY rownum)FROM XMLTABLE(('"'||REPLACE(:1,'0','","0","')||'"'));

```

# Answer
> 1 votes
# Perl, 22 bytes

Including +1 for `-p` option:

```
s/[^0]+/reverse$&/eg

```

This is a pretty trivial substitution - sorry to be so boring. Note that if your input is newline-terminated (e.g. using `perl -pe 's/[^0]+/reverse$&/eg' <<<21000543` in Bash), it will catch the newline with the digits - use `echo -n` or `printf` to avoid that. Alternatively, for a cost of one additional byte, change the character class to `[1-9]`, and you can provide many inputs, one per line.

# Answer
> 1 votes
## C, 105 bytes

```
#define x(o)for(p=s;*s&&'0'o*s;++s);for(r=s;r-->p;putchar(*r));
f(s,p,r)char*s,*p,*r;{x(^)x(==)*s&&f(s);}

```

Call `f` with the list of digits as a nul-terminated string, and it will print the correct output.

**Ungolfed and explained:**

```
f(s,p,r)
char*s,*p,*r; // K&R style to avoid repeating `char`
{

    // x(^)x(==) expands to...

    // Find the next zero digit
    for(p = s; *s && '0' ^ *s; ++s)
        ;

    // Print that run backwards
    for(r = s; r-- > p; putchar(*r))
        ;

    // Find the next non-zero digit
    for(p = s; *s && '0' == *s; ++s)
        ;

    // Print that run backwards (no difference, it's all zeros)
    for(r = s; r-- > p; putchar(*r))
        ;

    // If there's more string, recurse
    *s && f(s);
}

```

See it live on Coliru

# Answer
> 1 votes
# Husk, 4 bytes

```
ṁ↔ġ¬

```

Try it online! or verify all test cases

Input is a list of digits.

`ġ`roups all adjacent runs of nonzero (`¬`=NOT) digits, then aps the 'reverse a list' (=REV) function across all groups, concatenating the result.

# Answer
> 1 votes
# K (ngn/k), 10 bytes

```
"0"/|'"0"\

```

Try it online!

Similar to many of the other approaches; takes (implicit) input as a string of digits:

* `"0"\` split input on `0`s
* `|'` reverse each chunk
* `"0"/` join with `0`s

# Answer
> 1 votes
# Vyxal, 4 bytes

```
0ẆRṅ

```

Takes input as a string instead. If that's not allowed then the  flag can be added.

Try it online!

Explanation:

```
0     # Push the literal digit 0
 Ẇ    # Split and keep delimiter
  R   # Reverse each one
   ṅ  # Join by nothing

```

# Answer
> 0 votes
# Perl 5, 52 bytes

A subroutine:

```
{$_=pop;y/0/ /;map$i.=reverse,split/\b/;$i=~y/ /0/r}

```

# Answer
> 0 votes
## Actually, 22 bytes

```
k"a%sa"%'0@s♂R'0j#pXdX

```

This actually made me notice that there's a bug in the split command - it doesn't preserve empty splits. As a workaround, I surround the input string with `a`s before doing the split, reverse, and join, then remove the `a`s at the end. Input is taken as a string, output is a list of single-character strings.

Try it online

Explanation:

```
k"a%sa"%'0@s♂R'0j#pXdX
k"a%sa"%                surround input with "a" characters
        '0@s            split on 0
            ♂R          reverse each piece
              '0j       join on 0
                 #pXdX  listify, remove first and last element (the "a"s)

```

# Answer
> 0 votes
## C#, 131 bytes ##

solution flawed!

```
string j(string i){foreach(var s in i.Split('0'))if(s!="")i=i.Replace(s,new string(s.ToCharArray().Reverse().ToArray()));return i;}

```

ungolfed:

```
string j(string input)
    {

        string[] a = input.Split('0');

        foreach (string s in a)
        {
            if (s!="")
            input=input.Replace(s, new string(s.ToCharArray().Reverse().ToArray()));
        }

        return input;
    }

```

# Answer
> 0 votes
## C#, 133 bytes

---

**Golfed**

```
String m(String s){for(int i=0,p=i;i<s.Length;i++){if(s[i]=='0'){p=i+1;}else{s=s.Insert(p,s[i].ToString()).Remove(i+1,1);}}return s;}

```

---

**Ungolfed**

```
String m( String s ) {
    // i = Index on the String
    // p = Pointer of the last '0' found
    for (int i = 0, p = i; i < s.Length; i++) {
        if (s[ i ] == '0') {
            // Move the 'p' pointer to the index after this '0'
            p = i + 1;
        } else {
            // Insert the Char at the Index location to the Pointer location
            //    and remove the one at the Index Location + 1,
            //    since the String was incremented by one char due to the 'Insert()'.
            s = s.Insert( p, s[ i ].ToString() )
                 .Remove( i + 1, 1 );
        }
    }

    return s;
}

```

---

**Full code**

```
using System;
using System.Collections.Generic;

namespace Namespace {
    class Program {
        static void Main( String[] args ) {
            List<String> ls = new List<String>() {
                "4",
                "00",
                "123",
                "0010",
                "12000345",
                "18161604",
                "95883007414830",
                "010230456078912",
                "357509902003550",
                "2492882377675046",
                "03026302053000357099"
            };

            foreach (String s in ls) {
                String f = m( s );

                Console.WriteLine( String.Format( "{0,30}", s.Replace( "0", "0 " ) ) );
                Console.WriteLine( String.Format( "{0,30}", f.Replace( "0", "0 " ) ) );
                Console.WriteLine( "" );
            }

            Console.ReadLine();
        }

        static String m( String s ) {
            for (Int32 i = 0, p = i; i < s.Length; i++) {
                if (s[ i ] == '0') {
                    p = i + 1;
                } else {
                    s = s.Insert( p, s[ i ].ToString() ).Remove( i + 1, 1 );
                }
            }

            return s;
        }
    }
}

```

# Answer
> 0 votes
# Java, 126

```
a->{String r="",t[]=a.split("0");for(String s:t){r+=new StringBuilder(s).reverse()+"0";}return r.substring(0, r.length()-1);}

```

# Answer
> 0 votes
## Clojure, 37 bytes

```
#(mapcat reverse(partition-by #{0}%))

```

Uses `#{0}` instead of `pos?` (save 1 byte by concatenating with `%`) and using `mapcat` instead of `(flatten(map`. Still longer than *Factor*.

# Answer
> 0 votes
# Wonder, 23 bytes

```
rstr[`[^0]*`g;'><"".rev

```

Usage:

```
(rstr[`[^0]*`g;'><"".rev)1230123

```

Reverses all parts of the input that match the global regex `[^0]*`.

# Answer
> 0 votes
# APL (Dyalog Unicode), 20 bytes

```
('[1-9]+'⎕R{⌽⍵.Match})

```

It's just a simple regular expression with an anonymous function.

```
'[1-9]+' ⍝ a regex pattern
  ⎕R ⍝ the replace operator
    {⌽⍵.Match} ⍝ an anonymous function that recieves a regex namespace (object). ⌽ reverses the string.

```

Try it online!

# Answer
> 0 votes
# C (gcc), 90 bytes

```
char*t;f(char*s){*s>48&&putchar(*s,f(s+1),++t);}g(char*s){for(t=s;f(t),*t;putchar(*t++));}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 5 bytes

```
0¡í0ý

```

Try it online!

```
0¡í0ý  # full program
    ý  # join...
       # implicit input...
 ¡     # split by...
0      # literal...
 ¡     # s...
  í    # with each element reversed...
    ý  # by...
   0   # literal...
    ý  # s
       # implicit output

```

# Answer
> 0 votes
# Raku, 22 bytes

```
{S:g[<-[0]>+]=$/.flip}

```

Try it online!

Basic regex solution. `<-[0]>` matches any nonzero character (it's Raku's version of the classic `[^0]`), and `$/.flip` reverses each sequence.

# Answer
> 0 votes
# Arturo, 39 bytes

```
$=>[chunk&=>[0=&]|map=>reverse|flatten]

```

Try it

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


# Question
Title: Approximate a root of an odd degree polynomial
Every odd degree polynomial has at least one real root. However this root does not have to be a rational number so your task is to output a sequence of rational numbers that approximates it.

## Rules

* Your input is an odd degree polynomial \\$f\\$ with integer coefficients in any reasonable format.
* You must output a sequence of rational numbers \\$(a\_n)\_{n=1}^{\infty}\\$ such that \\$f(\lim\_{n\to\infty} a\_n) =0\\$ using the standard rules.
* Your solution may fail because of finite precision however it must work in theory, assuming your language has arbitrary precision rational numbers. If your language doesn't support algebraic numbers, you may not assume that it does. In particular you may not assume that a `find_roots` built-in returns an infinite precision algebraic number if it doesn't.
* This is so the shortest solution in bytes wins.

## Test cases

```
input -> example output

x^3-2 -> 1, 1.2, 1.25, 1.259, ...
x+7 -> -7, -7, -7, ...
x^5-x+1 -> -1.1, -1.167, -1.167304, ...
2x^7-3x^5-x^4-2x+1 -> 3, 0.7, 0.453 ...

```

# Answer
> 9 votes
# 05AB1E, ~~23~~ ~~22~~ ~~19~~ ~~12~~ 8 bytes

```
LÅ¼{.Δβd

```

Try it online!

Takes as an input a number \\$n\\$ and the coefficients list, from the highest power to the smallest one, and returns \\$a\_n\\$.

Requires the leading coefficient to be positive. If that is invalid, we need +2 bytes to fix it by adding  after `β`

If this is invalid because we may not assume \\$\tan\\$ has infinite precision, then the following 13 bytes alternative could be used, which uses a spacing of \\$\frac1 n\\$ for the \\$x\\$s inside a bound:

```
*ÄO(D(Ÿ¹/.Δβd

```

## Explanation

Finds the non-negative value of \\$p(x)\\$ (\\$p(x) \cdot c\_m\\$ in the version which doesn't require a positive leading coefficient) with the smallest \\$x\\$ among the values \\$ x = \tan(i) \\$ for \\$ 1 \leq i \leq n \\$. The \\$\tan\\$ of integers is dense in \\$\mathbb{R}\\$ (Since \\$ n\mod \pi\\$ is dense in the range \\$(0, \pi)\\$ ), so we can get arbitrarily close to the target number, and since we always keep \\$x\\$s as \\$n\\$ increases the sequence is non-increasing. Additionally, uses the fact that base conversion is the same action as evaluating a polynomial at the base, and that 05AB1E's base conversion builtin works well with non-integers.

```
L          Get the range [1, 2, 3, ..., n]
Å¼         Calculate the tangent of each number in that range
{          And sort those
.Δ         Now find the first value such that
 β          When converting the polynomial from that base
 d          It is non-negative

```

# Answer
> 6 votes
# Wolfram Language (Mathematica), 89 or 143 bytes

## Answer #1

If it is enough to find *one (any)* real root we can use next facts:

* All real roots of odd degree polynomial are bounded inside interval \\$\[-M,M\]\\$ where \\$M = \max\left(1,\sum\_{k=0}^{2n}|a\_k|\right)\\$ (\\$\sum\_{k=0}^{2n}|a\_k|\\$ if coefficients are integers)
* Bisection method *always* converges to *some* root of continuous function if they exist in given interval

...and do not use extra-power built-ins.
Fortunately `$MachineEpsilon` works well with TIO. So next code produces stream of *rational* approximations for one of the real roots. Input: array of coefficients.

```
With[{c=#,m=Total[Abs/@#]},If[Abs[Echo@#1-#2]>$MachineEpsilon,p=Fold[x#1+#2&,0,c]/.x->#&;d=(#1+#2)/2;If[p@#1*p@d>0,#0[d,#2],#0[#1,d]]]&[-m,m]]&

```

Try it online!
Optimization is welcome!

## Answer #2

The next code works well with Mathematica desktop (input is array of coefficients and output are approximations of *all* real roots):

```
Do[Echo[x/.NSolve[Fold[x#1+#2&,0,#],x,Reals,WorkingPrecision->n]],{n,∞}]&

```

But on TIO nor `N`, nor `WorkingPrecision` are not working(
So just like this (n\>20 make no sense):

```
Do[Echo@Round[x/.NSolve[Fold[x#1+#2&,0,#],x,Reals],10.^-n],{n,20}]&

```

Try it online!

# Answer
> 5 votes
# , ~~91~~ 90 bytes

```
\(x,n,a=polyroot(x),c=Re(a[!Im(a)])%/%1+0:n/n)c[order(sapply(c,\(y)x%*%y^seq(!x)/y)^2)][1]

```

Attempt This Online!

Uses the R `polyroot` function to find the (limited-precision) root `a`, then for each element `n` of the sequence, divides `floor(a)`-`ceiling(a)` into `n` steps and returns the one with the smallest absolute result after applying the polynomial.
The final result is still limited by R's precision\*, but the approach should work in principle, and is not affected by the limited-precision of the `polyroot` function (as long as it is correct to the nearest integer).

The limit as `n` tends to infinity is the true real root of the polynomial; however, successive elements of the sequence may have increasing absolute differences from the true root, depending on whether partitioning the interval into `n-1` or `n` steps allows a better solution. For a convergent-at-every-step sequence, divide into `2^n` instead of `n` steps, for 4 more bytes: try it here.

---

(\*) Note that this approach is actually *very* limited by R's precision, as the `a[!Im(a)]` part of the code (=get non-complex roots) fails quite easily due to floating-point inaccuracies: the test link overcomes this by redefining R's ``!`` (logical-NOT) operator to return `TRUE` as long as its argument is sufficiently small.

# Answer
> 4 votes
# JavaScript (ES7), 74 bytes

*-26 bytes (!) thanks to @CommandMaster*

A port of @CommandMaster's method.

Expects `(p)(n)` where `p` is the coefficient list from lowest to highest.

```
p=>g=(n,m)=>n?g(n-1,p.reduce((q,c,i)=>q+c*(v=Math.tan(n))**i)<0|v>m?m:v):m

```

Try it online!

### Commented

```
p =>                // p[] = list of coefficients
g = (               // g is a recursive function taking:
  n,                //   n = counter
  m                 //   m = minimum result, initially undefined
) =>                //
n ?                 // if n is not equal to 0:
  g(                //   do a recursive call:
    n - 1,          //     decrement n
    p.reduce(       //     using q as accumulator,
    (q, c, i) =>    //     for each coefficient c at index i:
      q +           //       add to q:
      c * (         //         c multiplied by v ** i
        v =         //         where v = tan(n)
        Math.tan(n) //
      ) ** i        //
    )               //     end of reduce()
    < 0 |           //     if the evaluation of the polynomial is negative
    v > m ?         //     or v is greater than m:
      m             //       keep m unchanged
    :               //     else:
      v             //       update m to v
  )                 //   end of recursive call
:                   // else:
  m                 //   stop and return m

```

# Answer
> 3 votes
# Vyxal `r`, 8 bytes

```
∆P≬İ⌊=cḞ

```

Try it Online!

I think this is valid. Takes list of coefficients and then the nth term to generate.

## Explained

```
∆P≬İ⌊=cḞ
∆P       # Get roots from polynomial with coefficients. Returns a list of exact algebraic numbers because sympy.
  ≬   c  # Get the first root where:
   İ⌊=   #   the root is real
       Ḟ # format to n decimal places

```

# Answer
> 3 votes
# Charcoal, 30 bytes

```
⊞υΣ↔θ⊞υ±ΣυＦη«≔⊘Συζ§≔υ‹↨θζ⁰ζ⟦Ｉζ

```

Try it online! Takes the polynomial and a number of terms (but because it uses floats there's no point asking for more than 50). Assumes that the leading term is positive. Explanation: Simple binary search over the bound of roots given by @CommandMaster.

```
⊞υΣ↔θ

```

Set the upper bound to the sum of the absolute coefficients.

```
⊞υ±Συ

```

Set the lower bound to the negation of the upper bound.

```
Ｆη«

```

Repeat `n` times.

```
≔⊘Συζ

```

Calculate the average of the bounds.

```
§≔υ‹↨θζ⁰ζ

```

Evaluate the polynomial at that point and update the appropriate bound.

```
⟦Ｉζ

```

Also output the next approximation.

---
Tags: code-golf, sequence, open-ended-function, polynomials
---


# Question
Title: Minimum rotation to get the maximum value
I recently solved a coding challenge in one of the challenge papers that my IT teacher gave to us. It was a seemingly simple, but fun challenge, so I thought it will make fun golfing.

## The task

Given an input of a 2x2 matrix that contains 4 strictly positive integers (i.e. non-negative and non-zero), like this:

$$\begin{pmatrix}a&b\\c&d\end{pmatrix}$$

We call the value of the matrix given is \\$\left\lfloor\dfrac{a}{c}\right\rfloor - \left\lfloor\dfrac{b}{d}\right\rfloor\\$.

Your task is to calculate the amount of rotation needed to get the maximum value of the matrix.

A rotation rotates the matrix 90 degrees clockwise.

## Input and Output

The input can be a 2x2 matrix (as shown above), a flattened list `[a b c d]`, or any other reasonable input.

Note that with the case of flattened lists, the numbers can be in any order you preferred. (e.g. `[a b d c]`).

The output must show a number that is the amount of rotation required.

## Clarifications

* In case of a tie, we will choose the one with the least amount of rotation needed.
* In case where no rotation is required, we simply output `0` or `4` (the maximal rotation).
* The division used here is integer division (i.e. the result of the division will always be an integer).

## Examples

```
[a b c d] -> output
[1 2 3 4] -> 3
[5 7 9 2] -> 1
[5 6 7 8] -> 0 or 4
[1 9 2 3] -> 3
[2 5 6 8] -> 3

```

These examples are hand-calculated and written, so correct me if I'm wrong!

As always, standard loopholes are forbidden.

# Answer
> 6 votes
# Jelly, 12 bytes

```
ZU$Ƭ:/€INM’Ḣ

```

Try it online!

## How it works

```
ZU$Ƭ:/€INM’Ḣ - Main link. Takes a matrix M on the left
  $Ƭ         - Do the following until a repeat is found:
Z            -   Transpose
 U           -   Reverse rows. This rotates clockwise 90°
      €      - To each rotation:
    :/       -   Reduce each column by integer division
       I     - Get the (negative) differences
        N    - Negate
         M   - Get the index of the maximal element
          ’  - Decrement
           Ḣ - Get the first (minimal) element

```

# Answer
> 4 votes
# Excel (ms365), ~~153~~, 148 bytes

-5 bytes by @jdt

```
=LET(a,INT(A1/C1)-INT(B1/D1),b,INT(C1/D1)-INT(A1/B1),c,INT(D1/B1)-INT(C1/A1),d,INT(B1/A1)-INT(D1/C1),m,MAX(a,b,c,d),IF(m=a,0,IF(m=b,1,IF(m=c,2,3))))

```

---

Original 153 bytes answer:

```
=XMATCH(9,BYROW(REDUCE(A1:D1,ROW(1:3),LAMBDA(a,b,VSTACK(a,SORTBY(TAKE(a,-1),{2,4,1,3})))),LAMBDA(c,SUM(INT(INDEX(c,{1,2})/INDEX(c,{3,4}))*{1,-1}))),-1)-1

```

It's painstaking in Excel, but my thought process here was:

* `REDUCE(A1:D1,ROW(1:3),LAMBDA(a,b,VSTACK(a,SORTBY(TAKE(a,-1),{2,4,1,3}))))` \- Create a vertical array where we keep stacking a 90° tilted array to our previous array;
* `BYROW(~,LAMBDA(c,SUM(INT(INDEX(c,{1,2})/INDEX(c,{3,4}))*{1,-1})))` \- Loop over each row from said array and do the math as per question: Devide the 1st and 3rd integer by the 2nd and 4th, discard the fractional part and do a negative summation of the resulting integers;
* `XMATCH(9,~,-1)-1` \- Find a nine (the largest possible outcome) or the next lower value. Deduct one from the given index.

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

Expects four BigInts as `[a,b,c,d]`.

```
A=>A.map(m=(_,i)=>(([a,b,c,d]=A,v=a/c-b/d)<=m||(j=i,m=v),A=[c,a,d,b]))|j

```

Try it online!

### Commented

```
A =>                    // A[] = input list
A.map(                  // repeat 4 times,
  m =                   //   with m initialized to a non-numeric value
  (_, i) => (           //   and i as the rotation index:
    (                   //
      [a, b, c, d] = A, //     split A into [a, b, c, d]
      v = a / c - b / d //     compute the value v for this rotation
    ) <= m              //     do nothing if it's less than or equal to m
    || (j = i, m = v),  //     otherwise update m and the best index j
    A = [c, a, d, b]    //     rotate the flattened view of the matrix
  )                     //     (see below)
) | j                   // end of map(); return j

```

### Rotation

Below are the details of the 90° clockwise rotation of the flattened matrix:

$$\[a,b,c,d\]\rightarrow\begin{pmatrix}\color{blue}a&\color{blue}b\\\color{green}c&\color{green}d\end{pmatrix}\rightarrow\begin{pmatrix}\color{green}c&\color{blue}a\\\color{green}d&\color{blue}b\end{pmatrix}\rightarrow\[c,a,d,b\]$$

# Answer
> 3 votes
# 05AB1E, 14 bytes

```
4FDøí})ε`÷Æ}Zk

```

Input as a matrix. Outputs `0` if no rotation is necessary.

Try it online or verify all test cases.

**Explanation:**

```
4F       # Loop 4 times:
  D      #  Duplicate the current matrix
         #  (which will be the implicit input-matrix in the first iteration)
   øí    #  Rotate it once clockwise:
   ø     #   Zip/transpose; swapping rows/columns
    í    #   Reverse each inner row
 })      # After the loop: wrap the stack of five matrices into a list
   ε     # Map over each matrix:
    `    #  Pop and push both pairs/rows separated to the stack
     ÷   #  Integer-divide the items at the same positions in the pairs
      Æ  #  Reduce the pair by subtracting
   }Z    # After the map: push the maximum (without popping the list)
     k   # Get the (first 0-based) index of this maximum in the list
         # (which is output implicitly as result)

```

# Answer
> 3 votes
# Factor, 81 bytes

Thanks to @chunes for -22

```
[ 3 [ dup reverse flip ] times 4array [ first2 v/ vfloor first2 - ] map arg-max ]

```

Attempt This Online!

## Explanation

| code | explanation |
| --- | --- |
| `3 [ dup reverse flip ] times 4array` | Generate a 4-item array of all rotations, by sequential `reverse` and `flip`s |
| `[ first2 v/ vfloor first2 - ] map` | Calculate the value of each matrix, according to the scheme. (First does vectorized floor division, then outputs difference of first 2 items.) |
| `arg-max` | Index of the largest item |

# Answer
> 2 votes
# Java 8, ~~116~~ 99 bytes

```
a->{int r=0,i=-1,m=0,t;for(;++i<4;a=new int[]{a[2],a[0],a[3],a[1]})if((t=a[0]/a[2]-a[1]/a[3])>m){m=t;r=i;}return r;}

```

-17 bytes thanks to *@Neil* by taking four loose integer inputs instead of an integer-array

Try it online.

**Explanation:**

```
(a,b,c,d)->{ // Method with four integer parameters and integer return-type
 int r=0,    //  Result-index, starting at 0
     i=-1,   //  Index-integer, starting at -1
     m=0,    //  Max value, starting at 0
     t;      //  Temp-integer, uninitialized
     ++i<4   //  Loop `i` in the range (-1,4) (or [0,3]):
     ;       //    After every iteration:
      t=a,a=c,c=d,d=b,b=t)
             //     Rotate: change a,b,c,d to c,a,d,b
   if((t=a/c-b/d)
             //    Set `t` to a//c-b//d
      >m){   //    And if `t` is larger than `m`:
     m=t;    //     Set maximum `m` to this `t`
     r=i;}   //     And update the result with the current index `i`
  return r;} //  Finally, return the result-index `r`

```

# Answer
> 2 votes
# Ruby, 58 bytes

```
->a,b,c,d{(1..4).max_by{a,b,c,d=c,a,d,b
[a/c-b/d,-_1%-4]}}

```

Attempt This Online!

# Answer
> 2 votes
# Factor, 62 bytes

```
[ 4 [ -rotd swap 4dup [ swap /i ] 2bi@ - ] replicate arg-max ]

```

Attempt This Online!

Takes 4 integers as input in the order `a b c d`.

* `4 [ ... ] replicate` Create a sequence of 4 elements where the elements are determined by the output of `[ ... ]`.

Now let's take a look at what happens inside the `replicate` quotation:

```
                  ! 2 5 6 8          (example input)
-rotd             ! 6 2 5 8
swap              ! 6 2 8 5          (this is the next rotation of the matrix)
4dup              ! 6 2 8 5 6 2 8 5
[ swap /i ] 2bi@  ! 6 2 8 5 0 0      (apply [ swap /i ] to the top two pairs of items)
-                 ! 6 2 8 5 0        (so 0 is the first element of the sequence)
                  ! 6 2 8 5          (now the next element will be determined...)

```
* `arg-max` Get the index of the largest element.

# Answer
> 2 votes
# Python 3, 74 bytes

```
f=lambda a,b,c,d,*m:m.index(max(m))if 3<len(m)else f(c,a,d,b,*m,a//c-b//d)

```

Try it online!

# Answer
> 2 votes
# ARM Thumb-2 machine code, 34 bytes

```
03 24 e7 07 0f b4 08 bc 07 bc b0 fb f3 f5 b1 fb
f2 f6 ad 1b bd 42 a4 bf 2f 46 a4 46 01 3c f1 da
70 47

```

Assembler source:

```
    .syntax unified
    // doesn't work with clang?!
    // .arch armv7ve
    .arch armv7-a
    .arch_extension idiv
    .globl rotation
    .thumb
    .thumb_func
    // input: r0=A, r1=B, r2=D, r3=C
    // output: r12
    // Uses r0-r7, r12
rotation:
    // Register aliases since it is otherwise confusing
    A       .req r0
    B       .req r1
    D       .req r2
    C       .req r3
    rot     .req r4
    res     .req r12
    max     .req r7
    // Current rotation. This loops backwards, so we rotate backwards.
    movs    rot, #3
    // 3 << 31 = 0x80000000 = INT_MIN
    lsls    max, rot, #31
.Lloop:
    // Rotate COUNTER-CLOCKWISE by pushing/popping in a different order
    // Push and pop are the only things that make Thumb viable for this :)
    // A, B, D, C = B, D, C, A
    push    {A, B, D, C}
    pop     {C}
    pop     {A, B, D}
    // r5 = A / C
    udiv    r5, A, C
    // r6 = B / D
    udiv    r6, B, D
    // r5 = (A / C) - (B / D)
    subs    r5, r5, r6
    // Is this less than or equal to the max?
    cmp     r5, max
    // If so, save the new lowest rotation and the new max
    itt     ge
    movge   max, r5
    movge   res, rot
    // Loop while rot >= 0
    subs    rot, rot, #1
    bge    .Lloop
    // Return
    bx      lr

```

Uses the idiv extension.

Accepts arguments as `r0=A`, `r1=B`, `r2=D`, `r3=C`, and returns 0, 1, 2, or 3 in `r12`.

This cannot be called from C so I provide a wrapper which allows it to be called with this signature:

```
int rotation_c_wrapper(int A, int B, int D, int C);

```

```
    .syntax unified
    .arch armv7-a
    .thumb
    .thumb_func
    .globl rotation_c_wrapper
    // Wrapper to be called from C
    // int rotation_c_wrapper(int a, int b, int d, int c);
rotation_c_wrapper:
    // Save callee-saved registers
    push    {r4-r7, lr}
    // call the function
    bl      rotation
    // move result to r0
    mov     r0, r12
    // Restore callee-saved registers and return
    pop     {r4-r7, pc}

```

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

```
y,r;g(a,b,c,d,i){y=i>3?0:g(c,a,d,b,i+1)<(a=a/c-b/d)?r=i,a:y;}f(a,b,c,d){g(a,b,c,d,r=0);r=r;}

```

Try it online!

* function *f* initializes gobal *r* to 0 which is kinda default result. Then calls *g* which recursively sets *r* when a greater combination happens.
* *g* sets global *y* to a greater value or itself or 0 if the recursion loop is completed(*i\>3*), there cannot be greater value less than 0.

# Answer
> 1 votes
# Perl 5, 99 bytes

```
sub f{($a,$b,$c,$d,$i,$m,$I)=@_;$v=$a/$c-$b/$d;$i-4?f($c,$a,$d,$b,$i+1,$v>$m?($v,$i):($m,$I)):$I|0}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 41 bytes

```
ＮθＮηＮζＮεＦ⁴«⊞υ⁻÷θζ÷ηε≔θδ≔ζθ≔εζ≔ηε≔δη»Ｉ⌕υ⌈υ

```

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

```
ＮθＮηＮζＮε

```

Input `a`, `b`, `c` and `d`.

```
Ｆ⁴«

```

Repeat four times.

```
⊞υ⁻÷θζ÷ηε

```

Push the value of the current rotation to the predefined empty list.

```
≔θδ≔ζθ≔εζ≔ηε≔δη

```

Rotate the matrix.

```
»Ｉ⌕υ⌈υ

```

Find the index of the maximum value.

I tried working with lists but the best I could do was 42 bytes:

```
≔Ｅ⁴ＮθＦ⁴«⊞υθ≔Ｅ1302§θＩκθ»ＵＭυ⁻÷⊟ι⊟ι÷⊟ι⊟ιＩ⌕υ⌈υ

```

Try it online! Link is to verbose version of code. Takes input in the order `d b c a`. Explanation:

```
≔Ｅ⁴Ｎθ

```

Input `d`, `b`, `c` and `a` into a list.

```
Ｆ⁴«

```

Repeat four times.

```
⊞υθ

```

Push the list to the predefined empty list.

```
≔Ｅ1302§θＩκθ

```

"Rotate" the list.

```
»ＵＭυ⁻÷⊟ι⊟ι÷⊟ι⊟ι

```

Replace each list with the value of the matrix it represents.

```
Ｉ⌕υ⌈υ

```

Find the index of the maximum value.

# Answer
> 1 votes
# C (clang), 84 bytes

```
*t,m,v,i;f(*r,a,b,c,d){r?t=r,i=m=0:0;v=a/c-b/d;v<m||(m=v,*t=i);i++<4&&f(0,c,a,d,b);}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 18 bytes

```
 4(:⁽ḭÞC÷-$∩R)_WÞMh

```

Try it Online!

Unfortunately useful operator `İ` "collect while unique" currently works bad, so simple for-loop is used.

```
4(     # Open for-loop with 4 iterations
:      # Duplicate
⁽ḭÞC   # Reduce columns by integer division
÷-     # Calculate value
$      # Swap
∩R     # Transpose + Reverse = Rotate
)      # Close loop
_      # Pop unnecessary
W      # Wrap stack into list
ÞM     # Find all indices of maximum
h      # Pick and print one (first)

```

# Answer
> 0 votes
# Japt `-h`, 15 bytes

```
4o ñ@zX yÈrzÃr-

```

Try it

```
4o ñ@zX yÈrzÃr-     :Implicit input of 2D-array
4o                  :Range [0,4)
   ñ                :Sort by
    @               :Passing each X through the following function
     zX             :Rotate U clockwise X times
        y           :Transpose
         È          :Map
          r         :  Reduce by
           z        :  Integer division
            Ã       :End map
             r-     :Reduce by subtraction
                    :Implicit output of last element

```

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