# Question
Title: Alternating sums of multidimensional arrays
Given a multidimensional array, find the recursive alternating sum. An alternating sum is simply the sum of an array, where every other item (starting with the second) is negated. For example, the alternating sum of `[7, 1, 6, -4, -2]` is the sum of `[7, -1, 6, 4, -2]`, or `14`. In this challenge, you'll take the alternating sum of a multidimensional array.

**Task:**

Given an array like this:

```
[
    [
        [1, 2], [2, 4], [4, 8]
    ],
    [
        [-4, -4], [-1, 1], [2, -2]
    ]
]

```

First find the alternating sums of all of the deepest nested arrays:

```
[
    [-1, -2, -4],
    [0, -2, 4]
]

```

Then do this again:

```
[-3, 6]

```

And finally:

```
-9

```

You can choose how input is represented, but it must be able to handle multidimensional arrays of any number of dimensions possible in the language you use. You don't need to support ragged arrays.

**Test cases:**

```
[1]                                                         1
[-1]                                                        -1
[1, 2]                                                      -1
[2, 0, 4]                                                   6
[1, -2]                                                     3
[[1]]                                                       1
[[1, 2], [4, 8]]                                            3
[[-1, -1], [2, 2]]                                          0
[[[[1], [2]], [[4], [8]]]]                                  3
[[[1, 2], [2, 4], [4, 8]], [[-4, -4], [-1, 1], [2, -2]]]    -9

```

**Other:**

This is , so shortest answer (per language) wins!

# Answer
> 15 votes
# APL(Dyalog Unicode), 4 bytes SBCS

```
-/⍣≡

```

Try it on APLgolf!

Alternating sum (aka right-reduce by subtraction) along last axis `-/` until convergence `⍣≡`.

# Answer
> 6 votes
# Python, 58 bytes

```
f=lambda a,s=-1:sum(f(x)*(s:=-s)for x in a)if[]==a*0else a
```

Attempt This Online!

# Whython, 45 bytes

```
f=lambda a,s=-1:sum(f(x)*(s:=-s)for x in a)?a
```

Attempt This Online!

# Answer
> 6 votes
# Python 2, 50 bytes

```
f=lambda A,*a:(f(*A)if f<A else A)-(a>()and f(*a))
```

Attempt This Online!

Expects splatted input. Test harness borrowed from @pxeger.

How?

Hybrid recursion implementing depth first traversal. Detail: `f<A` depends on Python 2's comparability of objects of different types.

# Answer
> 6 votes
# Brachylog, 5 bytes

```
ċ↰ᵐ-|

```

Try it online!

```
 ↰ᵐ      Recur on each element
   -     then take the alternating sum
ċ   |    if it's a list, else return it unchanged.

```

# Answer
> 6 votes
# C++ 20, 87 bytes

```
int f(int a){return a;}int f(auto a){int s=0,i=1;for(auto b:a)s+=f(b)*i,i=-i;return s;}

```

This answer is in the same spirit as @HatsuPointerKun's, but it (ab)uses C++ 20's `auto` parameter declaration, which allows us to ditch the whole `#include<vector>` shenanigans (it works with any container).

Attempt This Online!

# Answer
> 5 votes
# flax, 4 3 bytes

```
-/´

```

Try It Online!

Another port of @ovs' APL answer.

*¯1 byte due to update changing direction of fold/scan to match evaluation order*

# Answer
> 5 votes
# Nekomata, 4 bytes

```
ʷ{£d

```

Attempt This Online!

```
ʷ      Repeat the following function until it fails:
 {     Start a block
  £d   Convert from base -1; fail if the input is not a list

```

# Answer
> 4 votes
# K (ngn/k), 11 bytes

```
({y-x}/|:)/

```

Try it online!

Port of @ovs' APL answer.

# Answer
> 4 votes
# , ~~51~~ 48 bytes

*Edit: -3 bytes thanks to @Dominic van Essen.*

```
f=\(l)"if"(is.list(l),Reduce(`-`,Map(f,l),,T),l)
```

Attempt This Online!

Takes input as a list of lists.

---

Old version:

```
f=\(l)"if"(is.list(l),sapply(l,f)%*%-(-1)^seq(l),l)
```

Attempt This Online!

Takes input as above. Outputs a \\$1\times1\\$ matrix.

# Answer
> 4 votes
# PARI/GP, 33 bytes

```
f(a)=if(#a',f(a[1])-f(a[^1]),a,a)
```

Attempt This Online!

```
f(a)=if(#a',f(a[1])-f(a[^1]),a,a)
f(a)=                                Define a function `f` with argument `a`:
     if(#a',                         If the length of `a`'s derivative is nonzero,
                                       so `a` is a nonempty list:
            f(a[1])                    apply `f` to the first element of `a`,
                   -                   minus
                    f(a[^1]),          apply `f` to `a` with the first element removed.
                             a,      Otherwise, if `a` is truthy,
                                       so `a` is a nonzero integer:
                               a       return `a`.
                                )    (Implicitly) Otherwise, return 0.

```

# Answer
> 4 votes
# Haskell \+ free, 14 bytes

```
iter$foldr(-)0

```

Try it online!

We need the free library to represent arbitrarily nested lists. This code works on any ragged list as well. `foldr(-)0` computes the alternating sum of a flat list and `iter` applies it recursively to a free monad.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 25 bytes

```
Fold[#2-#&]@*Reverse//@#&

```

Try it online!

Right-fold subtraction on every level. Supports ragged arrays.

# Answer
> 3 votes
# Haskell + hgl, 9 bytes

```
itr$lH(-)

```

## Explanation

Seeing how short my haskell answer turned out I couldn't help but port it to hgl. This works *basically* the same.

It takes input as a free monad of lists, that is a ragged list. `lH(-)` is equivalent to the haskell `foldl1(-)` and calculates the alternating sum of a flat list. We use it with `itr` to recursively reduce a ragged list.

## Reflection

This is pretty tight as far as things go.

It feels clunky to use `(-)` here but the alternative is `fsb` which would lose a byte due to spacing. In order for it to save bytes `fsb` would have to be 1 byte long.

The one thing that seems like it could be worthwhile would be an alternating sum builtin. It would probably save 2 bytes here.

# Answer
> 3 votes
## C++, ~~194~~ ~~147~~ ~~141~~ 130 bytes

-17 (6+11) bytes tanks to ceilingcat

TIO Link

This code uses templates to have any kind of vectors as input ( `vector<int>`, `vector<vector<int>>`, `vector<vector<vector<int>>>` ... )

The code :

```
#import<vector>
int f(int a){return a;}template<class T>int f(std::vector<T>a){int s=0,i=1;for(auto x:a)s-=f(x)*(i*=-1);return s;}

```

Here's the code for testing :

```
int main() {

    // Test case [1]
    std::vector<int> v1 = { 1 };
    assert(f(v1) == 1);

    // Test case [-1]
    std::vector<int> v2 = { -1 };
    assert(f(v2) == -1);

    // Test case [1,2]
    std::vector<int> v3 = { 1,2 };
    assert(f(v3) == -1);

    // Test case [2,0,4]
    std::vector<int> v4 = { 2,0,4 };
    assert(f(v4) == 6);

    // Test case [1,-2]
    std::vector<int> v5 = { 1,-2 };
    assert(f(v5) == 3);

    // Test case [[1]] = 1
    std::vector<std::vector<int>> v6 = { {1} };
    assert(f(v6) == 1);

    // Test case [[1, 2], [4, 8]]
    std::vector<std::vector<int>> v7 = { {1,2}, {4,8} };
    assert(f(v7) == 3);

    // Test case [[-1, -1], [2, 2]]
    std::vector<std::vector<int>> v8 = { {-1,-1},{2,2} };
    assert(f(v8) == 0);

    // Test case [[[[1], [2]], [[4], [8]]]]                                  3
    std::vector<std::vector<std::vector<std::vector<int>>>> v9 = { {{{1},{2}},{{4},{8}}} };
    assert(f(v9) == 3);

    // Test case [[[1, 2], [2, 4], [4, 8]], [[-4, -4], [-1, 1], [2, -2]]]
    std::vector<std::vector<std::vector<int>>> v10 = { {{1,2},{2,4},{4,8}},{{-4,-4},{-1,1},{2,-2}} };
    assert(f(v10) == -9);
}

```

# Answer
> 3 votes
# BQN, 15 bytes

```
{0==?;-˝⎉1}

```

Anonymous function. Takes a multidimensional array, returns a 0-dimensional array containing a number.

### Explanation

```
{0==?;-˝⎉1}
{              }  Anonymous function:
   =               Rank (number of dimensions) of
                  the argument
 0=                equals zero?
     ?             If so:
                   Return the argument unchanged
       ;           If not:
          ˝         Right fold
         -          on subtraction
           ⎉1      the innermost axis of
                   the argument
                   and call this function recursively on that array

```

# Answer
> 3 votes
# Java 17, 101 bytes

```
int f(Object[]a){int s=0,m=-1;for(var i:a)s+=(m=-m)*(i instanceof Long j?j:f((Object[])i));return s;}
```

Attempt This Online!

Java 17+ is required for pattern matching; this is probably the first time it is useful in a golf :).

# Answer
> 3 votes
# Arturo, 52 bytes

```
f:$[a][(block? a)?->([]=a)?->0->-f a\0f drop a 1->a]

```

Try it

# Answer
> 3 votes
# Uiua, 9 bytes

```
⍥(/-⇌)⧻△.

```

Try it online!

Similarly to BQN and K, alternating sum in Uiua requires a reverse before reduction by subtraction. Uiua doesn't have "converge" builtin, and "do while" isn't a good fit here because getting the iteration count directly is cheap.

```
⍥(/-⇌)⧻△.    input: a possibly multidimensional array
       ⧻△.    keep input and push number of dimensions
⍥(    )        repeat that many times:
   /-⇌         alternating sum over the leading axis

```

# Answer
> 2 votes
# Julia 1.0, 24 bytes

```
!x::Int=x
!x=!foldr(-,x)

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 46 bytes

```
f=a=>1/a?+a:a.map(n=>p-=(a=-a)*f(n),p=0,a=1)|p

```

Try it online!

Or **43 bytes** with optional chaining (ES11), as suggested by @MatthewJensen:

```
f=a=>a.map?.(n=>s-=(a=-a)*f(n),s=0,a=1)?s:a
```

Attempt This Online!

# Answer
> 2 votes
# Charcoal, 35 bytes

```
⊞υθＦυＦΦι⁺⟦⟧κ⊞υκＦ⮌υ⊞ι↨Ｅ⮌ιΣ⁺⟦⁰⟧⊟ι±¹Ｉθ

```

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

```
⊞υθＦυＦΦι⁺⟦⟧κ⊞υκ

```

Get all of the sublists of the input.

```
Ｆ⮌υ

```

Loop over the sublists in reverse, i.e. from deepest back up to the original input.

```
⊞ι↨Ｅ⮌ιΣ⁺⟦⁰⟧⊟ι±¹

```

Remove all the elements of the sublist in reverse order, convert them from integers or sublists to integers, then interpret them as base `-1` to obtain the alternating sum, and push the result back to the sublist.

```
Ｉθ

```

Output the final result.

# Answer
> 2 votes
# Jelly, 8 bytes

```
ŒJ’§-*ḋF

```

Try it online!

```
ŒJ          Enumerate the multidimensional indices of every element, in flat order.
  ’         Decrement each dimension (indexed from 1) of each index.
   §        Sum each index,
    -*      and raise -1 to the power of each sum.
      ḋF    Take the dot product of that with the flattened input.

```

# Jelly, ~~10~~ 9 bytes

```
ß€ŒḊ¡U_@/

```

Try it online!

```
ß€           Recur on each element of the argument
    ¡        as many times as
  ŒḊ         its depth.
     U       Reverse the list of results (or do nothing to the scalar argument)
      _@/    and left-reduce by reversed subtraction.

```

Previous solution was `ß€NÐeSµ)Ƒ¡`. Gaze upon it and despair.

# Answer
> 2 votes
# 05AB1E, 17 bytes

```
"Ð˜Êi®δ.V}.«-"©.V

```

As always, 05AB1E and recursive functions are not a good match..

Try it online or verify all test cases.

**Explanation:**

```
"..."        # Create the recursive-string explained below
     ©       # Store it in variable `®` (without popping)
      .V     # Evaluate and execute it as 05AB1E code
             # (after which the result is output implicitly)
             #
Ð            # Triplicate the current list
 ˜           # Flatten the top copy
  Êi         # If the top two lists are NOT equal (so there is an inner list):
     δ       #  Map over each inner item:
    ® .V     #   Do a recursive call
   }         # After the if-statement, whether we've executed it or not
    .«       # Right-reduce the list by:
      -      #  Subtracting

```

# Answer
> 2 votes
# Factor, 73 bytes

```
: f ( s -- n ) dup array? [ [ 0 ] [ unclip f swap f - ] if-empty ] when ;

```

Try it online!

# Answer
> 2 votes
# , 7 5 bytes

```
-/^:_

```

Try it online!

*-2 thanks to Bubbler*

Just a J translation of the APL answer, for completeness.

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

```
lambda n:n*0==0and n or sum((1-i%2*2)*f(e)for i,e in enumerate(n))

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 108 bytes

```
\d+(?<=((])|(?<-2>\[)|(?(2).|((,)|.)))*)
$#4$*-$&
--

O^`-?\d+
(-)|\d+|.
$*1$1
1>`-

(1+)-\1
-
r`(1*)-?$
$.1

```

Try it online! Link includes test cases. Explanation:

```
\d+(?<=((])|(?<-2>\[)|(?(2).|((,)|.)))*)
$#4$*-$&

```

Negate each value a number of times given by the sum of its multidimensional indices.

```
--

```

Simplify any double negations.

```
O^`-?\d+

```

Sort the negative numbers to the end.

```
(-)|\d+|.
$*1$1

```

Convert the values to unary but delete everything else that isn't a `-`. This sums the positive values together.

```
1>`-

```

Sum the negative values together.

```
(1+)-\1
-

```

Take the difference between the positive and negative values.

```
r`(1*)-?$
$.1

```

Convert to decimal, ignoring any trailing `-`.

# Answer
> 1 votes
# BQN, 6 bytesSBCS

```
-´⚇1⍟≡

```

alternating sum

`⚇1` at depth 1 (simple lists)

`⍟≡` repeated as many times as the depth of the argument

Run online!

# Answer
> 1 votes
# Vyxal, 12 bytes

```
λ∑u$e;€f?fÞ•

```

Try it Online!

This is like, really, really, really bad.

# Answer
> 1 votes
# Scala, 100 bytes

Golfed version. Try it online!

```
a=>{var(s,m)=(0,-1);for(i<-a){m= -m;i match{case j:Long=>s+=m*j.toInt;case b:Seq[_]=>s+=m*f(b)}};s;}

```

Ungolfed version. Try it online!

```
object Main {
  def f(a: Array[_]): Int = {
    var s = 0
    var m = -1
    for (i <- a) {
      m = -m
      i match {
        case j: Long => s += m * j.toInt
        case arr: Array[_] => s += m * f(arr)
      }
    }
    s
  }

  def main(args: Array[String]): Unit = {
    println(f(Array(1L)))
    println(f(Array(-1L)))
    println(f(Array(1L,2L)))
    println(f(Array(2L,0L,4L)))
    println(f(Array(1L,-2L)))
    println(f(Array(Array(1L))))
    println(f(Array(Array(1L, 2L), Array(4L,8L))))
    println(f(Array(Array(-1L, -1L), Array(2L,2L))))
    println(f(Array(
      Array(
        Array(
          Array(1L),
          Array(2L)
        ),
        Array(
          Array(4L),
          Array(8L)
        )
      )
    )))
  }
}

```

# Answer
> 0 votes
# C++ (GCC), ~~135~~ ~~133~~ 132 bytes

*-2 bytes thanks to ceilingcat*

```
#include<random>
int f(int a){return a;}int f(auto&a){return std::accumulate(rbegin(a),rend(a),0,[](int l,auto&r){return f(r)-l;});}

```

Attempt This Online!

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


# Question
Title: Encode the input to exclude a given character (part 1)
Your task is to write 2 functions/programs. They may share code.

The first function must, given a string and a character, output a new string that does not contain that character.

The second function must, given the string from the previous function and the excluded character, reconstruct the original string.

All input strings will be ASCII printable, all output strings must be ASCII printable. You may choose to include or exclude whitespace, if you exclude whitespace it must be excluded from both the input and the output.

### Examples

One could try to use replace the character with an escape sequence. For example `\#bcda` with excluded character becomes `\\#bcd\#` then you'd know to replace `\#` with whatever character is excluded. However, the excluded character might itself be `#` or `\` so if one uses this method they'd need to be able to dynamically switch to a different escape sequence in that case.

There is no length limit for the censored string so you could try to encode the entire string in unary, but be careful that the unary char you choose may not be the excluded char.

This is code golf, shortest answer in each language wins. Brownie points for interesting solutions even if they are not the shortest though.

# Answer
> 11 votes
# JavaScript (ES6), 59 bytes

### Encoder (30 bytes)

Expects `(string)(char)`.

```
s=>c=>btoa(s).split(c).join`#`

```

Try it online!

### Decoder (29 bytes)

Expects `(encoded_string)(char)`.

```
s=>c=>atob(s.replace(/#/g,c))

```

Try it online!

### Explanation

The encoder turns the input string `s` into a base-64 string, which may only contain `[a-z]`, `[A-Z]`, `[0-9]`, `+`, `/` and `=`. Then it replaces all occurrences of the forbidden character `c` with `#`. If `c` is not a base-64 character, this 2nd step has no effect at all. (In particular, note that the base-64 string can't possibly contain any `#`.)

The decoder does the exact opposite: it replaces all occurrences of `#` with the forbidden character and decodes this as a base-64 string.

# Answer
> 4 votes
# Jelly, 4 + 5 = 9 bytes

(4 + 4 = 8 bytes if we do not need to handle the empty string\*, remove .)

Uses the same approach as others, port of bsoelch's Python answer.

### Encoder

A dyadic Link that accepts the plaintext on the left and the character on the right and yields the ciphertext.

```
OṾṣK - Link: plaintext, P; character, C  e.g. P="20 cats"; C='0'
O    - cast P to ordinals                      [50,48,32,99,97,116,115]
 Ṿ   - unevaluate                               "50,48,32,99,97,116,115"
  ṣ  - split at occurrences of C             ["5",",48,32,99,97,116,115"]
   K - join with spaces                         "5 ,48,32,99,97,116,115"

                     (note that if C=' ' we get "50,48,32,99,97,116,115")

```

### Decoder

A dyadic Link that accepts the ciphertext on the left and the character on the right and yields the plaintext.

```
ḲjVỌ€ - Link: cyphertext X; character C  e.g. X="5 ,48,32,99,97,116,115", C='0'
Ḳ     - split X at spaces                    ["5",",48,32,99,97,116,115"]
 j    - join with C                             "50,48,32,99,97,116,115"
  V   - evaluate as Jelly code                  [50,48,32,99,97,116,115]
   Ọ€ - cast each to a character                "20 cats"

```

* An empty ciphertext evaluates (`V`) to the integer zero, so without  the cast () will convert that to a NULL byte terminated empty string (in all other cases it will vectorise automatically but  will implicitly cast this edge-case zero to an empty range first).

# Answer
> 4 votes
# Ruby, 59 bytes

```
f=->s,c{"#{s.bytes}".tr c,?.}
g=->s,c{(eval s.tr ?.,c).pack"U*"}

```

Try it online!

TIO says 64 byes, because 2 function headers and a newline are included.

Inspired by Arnauld's JS answer.

### Encode

First convert the string to a sequence of 8-bit values, then convert it to a string again, and finally replace the character to be excluded with a dot. The first step is equivalent to `unpack` using UTF-8 byte values, only slightly shorter.

### Decode

Reverse order: first replace the character that was excluded, then convert it to an array of 8-bit values, and finally pack it to a string. This is equivalent to mapping the `&:chr` method on the list, and then joining the characters, only slightly shorter.

# Answer
> 3 votes
# 05AB1E, ~~7~~ 6 + 5 = 11 bytes

Encoder:

-1 thanks to @KevinCruijssen

```
≠sÇ₁β×

```

Attempt This Online!

Decoder:

```
g₁вçJ

```

Attempt This Online!

`J` could be removed for -1 to output a list of characters instead of a string.

Uses unary, with `0` if the character is `1` and `1` otherwise.

# Answer
> 3 votes
# Python, 86 bytes

*inspired by Arnauld's JavaScript solution*

*-25 bytes, thanks to corvus\_192*

Encoder:

```
lambda s,c:str([*map(ord,s)]).replace(c,"#")

```

Decoder:

```
lambda s,c:map(chr,eval(s.replace("#",c)))

```

Attempt This Online!

encodes string as an array sequence of character-codes

---

# Python, 182 bytes

```
def q(S,N,K,n,d):
 k=sum((ord(c)&K)*N**i for i,c in enumerate(S));s=[]
 while k:s+=[chr(k%n+d)];k//=n
 return s
e=lambda s,c:q(s,128,-1,2,48+2*(c in"01"))
d=lambda s,c:q(s,2,1,128,0)

```

Attempt This Online!

The encoder (`e(s,c)`) interprets the string as a base 128 number and converts it to binary (using `2` and `3` if the excluded character is `0` or `1`).

The decoder (`d(s,c)`) converts a binary number to base 128

# Answer
> 2 votes
# Vyxal `Ss`, 5 + 4 = 9 bytes

```
C?¬S*

```

Try it Online!

Input list of characters and then normal input. Outputs a string

```
⌈@ꜝC

```

Try it Online!

Input the string from the encoder.

# Answer
> 2 votes
# Jelly, 9 + 4 bytes

## Encoder

```
OḅȷịØṖxɗ/

```

## Decoder

```
LbȷỌ

```

Try it online!

Both are monadic links. The encoder takes a pair of Jelly strings (character followed by string to encode). The decoder takes the encoded string as the first argument and ignores the second argument (but doesn’t mind if it is the excluded character). This takes inspiration from @CommandMaster’s 05AB1E answer so be sure to upvote that one too!

Now fixed (properly!) to handle all printable ASCII and return strings. Thanks to @JonathanAllan for his patience in highlighting problems with previous versions.

## Explanations

### Encoder

```
O         | Codepoints of strings
 ḅȷ       | Convert both from base 1000
       ɗ/ | Reduce using the following as a dyad:
   ịØṖ    | - Index (the codepoint of the single character) into the list of printable ASCII (will always be a different character)
      x   | - Repeat this as many times as the base-1000 decoded string

```

### Decoder

```
L    | Length
 bȷ  | Convert to base 1000
   Ọ | Convert from code points to ASCII

```

# Answer
> 1 votes
# Charcoal, 9 + 9 = 18 bytes

## Encoder, 9 bytes:

```
⍘⍘Ｓ⁺¶γ⁻γＳ

```

Try it online! Link is to verbose version of code. Explanation: "Decodes" the input as base 97 and "encodes" it as base 95. (Base 97 is needed to prevent the input from having leading zeros.)

## Decoder, 9 bytes:

```
⍘⍘Ｓ⁻γＳ⁺¶γ

```

Try it online! Link is to verbose version of code. Explanation: "Decodes" the input as base 95 and "encodes" it as base 97.

# Answer
> 1 votes
# Python, 68 bytes

```
e=lambda s,c:str([*s]).replace(c,'#')
d=lambda s,c:eval(s.replace('#',c))

```

Attempt This Online!

Inspired by Arnauld's JS answer. The encoder converts to a stringified list of code points, replacing the excluded character with a "#". The decoder replaces "#" with the excluded character and returns a list of code points.

# Python, 73 bytes

```
e=lambda s,c:s.hex().replace(c,'#')
d=lambda s,c:b''.fromhex(s.replace('#',c))

```

Attempt This Online!

Also inspired by Arnauld's JS answer. Converts to/from hex, replacing the excluded character with a "#".

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

```
e=s=>c=>(s+"").split(c).join`#`
d=s=>c=>s.replace(/#/g,c).split`,`

```

Attempt This Online!

(It's five bytes less than on ATO because of `e=`, newline and `d=`.). Encodes as a list of ascii codes, which normally contain only digits and commas. Then the forbidden character is replaced with `#`.

The decoder does the reverse and returns an array of strings of ascii codes, like `["72","101", ...]`. There are JS functions that interpret this as a sequence of integers (in particular `new Uint8Array`). An iterable of integers is a string.

# Answer
> 0 votes
# brainfuck, 122 + 68 = 190 bytes

```
>-[-[-<]>>+<]>[->+>+>+>+<<<<]>>->>->+>+>,[-<<<-<->>>>]<<<[>>-<<[-]]<[>>-<<[-]]>>[->+<]>[<<<<++<++>>>>>-]<<<,[[-<<.>>]<.>,]

```

Try it online!

```
,[->+>+<<]>>[>+<[-<-<+>>]<[>>->.[-]<<<[-<+>]]>>[>+<[-]]<<<[->+<]>>,]

```

Try it online!

A Simple Unary encoder. Typically uses `!` as the unary char and space as the separator, though if either of those chars are the exclusion char, uses `#` and `"` instead. (Char codes 32, 33, 34, and 35 respectively)

## With Comments

### Encoder

```
>-[-[-<]>>+<]>    Load 33
[->+>+>+>+<<<<]>  Smear it across 4 places
                  This is used to check the exclusion character as well as to store them
>->>->            Lower to 32
+>+>              Load two not flags
,                 Load the Exclusion Char
[-<<<-<->>>>]     Subtract any equals will be zeroed
<<<[>>-<<[-]]<[>>-<<[-]]  Invert the invert flags
>>[->+<]                  Add them essentially an or
>[<<<<++<++>>>>>-]        If either are true increment both chars by 2
<<<,
[                 Main Loop WHILE we have input
  [-              decrement the char
    <<.>>         Output the unary char
  ]
  <.>             Output the seperator
  ,               Read the next char
]

```

### Decoder

```
,[->+>+<<] Load the first char as the unary char and spread it to the working char as well
>>[ While we have working chars
    >+< Set up the inverse flag
    [-<-<+>>]   Compare to the unary char
    <[ if theyre not equal
      >>- flip the invert flag
      >.[-] output and clear the running total
      <<<[-<+>]]
    >>[ Otherwise
      >+<
      [-]] Increment the running total
    <<<[->+<] Restore the test char
    >> Go home
,] Repeat

```

# Answer
> 0 votes
# Uiua, 19 + 20 = 39 bytes

Encode:

```
++@0×2<@2∶♭⋯-@\0⊂@a

```

Decode:

```
↘1+@\0⍘⋯↯~7-+@0×2<@2

```

Try them online!

---

To encode, we prepend "a" to the string, convert it to bitwise representation, and then:

* if the excluded letter is less than ASCII '2', we use '2' and '3' for the bits
* otherwise we use '0' and '1' for the bits

The "a" is prepended to the string because it was the most character-efficient way of ensuring that the characters are always encoded into 7 bits each, otherwise a string like "1234" would be encoded as 6-byte characters

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


title: Smallest Bit Rotation

text:
# Question
Title: Smallest Bit Rotation
For a given positive integer, try to find out the smallest possible rotation resulted by rotating it 0 or more bits.

For example, when the given number is 177, whose binary representation is \\$10110001\_{(2)}\\$:

* \\$ 10110001\_{(2)}=177 \\$
* \\$ 01100011\_{(2)}=99 \\$
* \\$ 11000110\_{(2)}=198 \\$
* \\$ 10001101\_{(2)}=141 \\$
* \\$ 00011011\_{(2)}=27 \\$
* \\$ 00110110\_{(2)}=54 \\$
* \\$ 01101100\_{(2)}=108 \\$
* \\$ 11011000\_{(2)}=216 \\$

27 is the smallest rotating result. So we output 27 for 177.

## Input / Output

You may choose one of the following behaviors:

* Input a positive integer \\$n\\$. Output its smallest bit rotation as defined above.
* Input a positive integer \\$n\\$. Output smallest bit rotation for numbers \\$1\dots n\\$.
* Input nothing, output this infinity sequence.

Due to definition of this sequence. You are not allowed to consider it as 0-indexed, and output smallest bit rotate for \\$n-1\\$, \\$n+1\\$ if you choose the first option. However, if you choose the second or the third option, you may optionally include 0 to this sequence, and smallest bit rotation for \\$0\\$ is defined as \\$0\\$. In all other cases, handling \\$0\\$ as an input is not a required behavior.

## Test cases

So, here are smallest bit rotate for numbers \\$1\dots 100\\$:

```
 1  1  3  1  3  3  7  1  3  5
 7  3  7  7 15  1  3  5  7  5
11 11 15  3  7 11 15  7 15 15
31  1  3  5  7  9 11 13 15  5
13 21 23 11 27 23 31  3  7 11
15 13 23 27 31  7 15 23 31 15
31 31 63  1  3  5  7  9 11 13
15  9 19 21 23 19 27 29 31  5
13 21 29 21 43 43 47 11 27 43
55 23 55 47 63  3  7 11 15 19

```

## Notes

* This is as usual.
* This is A163381.
* The largest bit rotation is A163380. A233569 is similar but different. (The first different item is the 37th).

# Answer
# x86-64 machine code, ~~18~~ 16 bytes

```
0F BD D7 0F 43 C7 0F B3 D7 D1 D7 39 F8 75 F4 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes \\$n\\$ in EDI and returns its smallest bit rotation in EAX.

In assembly:

```
f:  bsr edx, edi    # Set EDX to the highest position of a 1 bit in n.
r:  cmovnc eax, edi # (EAX will hold the lowest rotation found so far.)
                    #  Set EAX to EDI if CF=0. The first iteration, CF=0 always:
                    #  the value of CF after BSR is officially undefined, but it is
                    #  consistently 0 (as this code needs) on at least some CPUs.
                    #  (To not rely on this, add CLC before this for +1 byte.)
                    #  On later iterations, CF=1 if EDI ≤ EAX (from the cmp).
    btr edi, edx    # Set the bit at position EDX in EDI to 0.
                    #  Set CF to the previous value of that bit.
    rcl edi, 1      # Rotate EDI and CF together left by 1,
                    #  putting the removed bit back in at the end.
    cmp eax, edi    # Compare EAX and EDI.
    jne r           # Jump back if they are not equal.
                    #  (Once a value repeats, all possible values have been seen.)
    ret             # Return.

```
> 12 votes

# Answer
# 05AB1E, 6 bytes

```
bā._Cß

```

Input \\$n\\$; outputs the smallest bit rotation.

Try it online or verify all test cases.

Both the \\$\[1,n\]\\$ list with an input \\$n\\$ and infinite list would be 2 bytes longer with a leading  or `∞ε` respectively.
Try the infinite version online.

**Explanation:**

```
b       # Convert the (implicit) input-integer to a binary-string
 ā      # Push a list in the range [1,length] (without popping the string)
  ._    # Map each integer v in the list to a v-times (left-)rotated version of the
        # binary-string
    C   # Convert each binary-string in the list back to an integer
     ß  # Pop and leave the minimum
        # (which is output implicitly as result)

```
> 7 votes

# Answer
# Excel, ~~81~~ ~~80~~ ~~71~~ 68 bytes

`=LET(a,DEC2BIN(n),b,LEN(a),c,SEQUENCE(b),MIN(BIN2DEC(MID(a&a,c,b))))`

Input ***n***

*With many thanks to @KevinCruijssen for the great suggestions and 11-byte improvement!*
> 6 votes

# Answer
# Octave, 73 bytes

It's not pretty, and it doesn't work on TIO. But it works in the program itself.

```
x=de2bi(k=input(''));for i=1:k,[ans,bi2de(circshift(x',i)')];end,min(ans)

```

Try it online!

```
x=de2bi(k=input(''));for i=1:k,[ans,bi2de(circshift(x',i)')];end,min(ans)

        k=input('')                   % Take input, k = 177
x=de2bi(k=input(''));                 % Convert input to binary, k = [1 0 0 0 1 1 0 1],
                                      % x = 177
for i=1:k,[...];end                   % Do k times (177 times)
                                      % Shortest way to make something happen enough times
               circshift(x',i)')      % Transpose x to make a vertical vector
                                      % Shift it i times, and transpose it back
                                      % Must be transposed for circshift to work
         bi2de(circshift(x',i)')      % Convert to decimal
    [ans,bi2de(...)]                  % Concatenate into a long vector 'ans'
min(ans)                              % The minimum of this vector

```
> 5 votes

# Answer
# Python, 61 bytes

*-5 bytes thanks to `Shaggy` and -5 bytes thanks to `M Virts`.*

Takes a positive integer `n` as input. Outputs its smallest bit rotation in integer form.

```
lambda n:min(int((a:=f'{n:b}')[i:]+a[:i],2)for i in range(n))

```

Attempt This Online!
> 5 votes

# Answer
# Jelly, 5 bytes

```
BṙRḄṂ

```

Try it online!

#### Explanation

```
BṙRḄṂ  # Implicit input (n)
B      # Convert n into binary
 ṙ     # Rotate this string this many times:
  R    #  Each of the numbers in [1..n]
       # (this will generate some duplicates, but that's fine)
   Ḅ   # Convert each one back from binary
    Ṃ  # Get the minimum of this list
       # Implicit output

```
> 5 votes

# Answer
# , 16 bytes

```
[:<./2#.i.|."{#:

```

Try it online!

* `#:`: Convert \\$n\\$ to binary.
* `i.` `|.` `"` `{`: `i.` makes a list of the integers from 0 (inclusive) to \\$n\\$ (exclusive), then `|.` uses that to rotate the binary expansion of \\$n\\$, with its ranks being set (`"`) to the ranks of `{` so that it takes each integer as a separate rotation.
* `2` `#.`: Convert back from binary expansions to numbers.
* `[:` `<.` `/`: Take the minimum, using a 'cap' to do so monadically.
> 4 votes

# Answer
# \>\<\> (Fish), 91 bytes

```
i0$1>:@$:@)?!v\
 ;n\^@+1$*2@ <r
$@:\?=@:$@:r-1/&~$?)@:&:
2+*2~v?:}:{%2:/.2b-%1:,
1$*2$/.38-

```

Try it

Instead of counting how many iterations happened, which would be expensive, this exits if the current value equals the minimum value.
> 4 votes

# Answer
# , ~~62~~ 59 bytes

*Edit: -3 bytes thanks to pajonk*

```
\(n,j=2^(0:(i=log2(n))))min(j%*%array(n%/%j%%2,2:3+i)[-1,])

```

Attempt This Online!

Instead of iteratively rotating bits, we use them to fill a 2D array with one-too-many rows, with recycling, so that each column ends-up with the bits rotated (plus an extra useless row).
We can then use matrix multiplication (`%*%` in R) with a vector of powers-of-2 to easily calculate the values encoded by each column, and output the minimum one.
> 4 votes

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

```
x=>'0b'+[...y=x.toString(2)].map(t=>y=y.slice(1)+t).sort()[0]-0

```

Try it online!

`t` keeps being the needed digit
> 3 votes

# Answer
# APL (Dyalog Extended), 9 bytes

Anonymous tacit prefix function.

```
⌊/⍳⊥⍤⌽¨⊤¨

```

Try it online!

`⌊/` the smallest (lit. minimum-reduction) of

`¨⊤¨` for each integer in the range 1 through \\$n\\$, combined with the binary representation of \\$n\\$:

…`⍤⌽` rotate that representation that integer steps left, and then:

convert back to a regular number
> 3 votes

# Answer
# , ~~80~~ ~~78~~ ~~75~~ 71 bytes

```
f=\(n,b=2^(0:log2(n)),x=n%/%b%%2)if(n)min(x%*%b,f(n-1,b,c(x[-1],x[1])))

```

Attempt This Online!

Recursive function that in every iteration rotates the binary representation by one place and keeps track of the minimum value.
> 3 votes

# Answer
# C (gcc), ~~73~~ 61 bytes

```
s;l;r;f(n){for(l=r=log2(s=n);r--;s=s<n?s:n)n=n%2<<l|n/2;r=s;}

```

Try it online!

*Saved a whopping 12 bytes thanks to c--!!!*
> 3 votes

# Answer
# Fig, \\$18\log\_{256}(96)\approx\\$ 14.816 bytes

```
[KeBtLbxGWbxO'J]xq

```

Try it online!

Fig is missing a few important builtins, so this is longer than expected.

```
[KeBtLbxGWbxO'J]xq
          bx       # Get the binary form of this number
        GW         # Generate an infinite list from the binary
            O'     # Using the function...
              J]xq # Rotate by prepending the last element to the tailless list
     Lbx           # Length of the binary representation
    t              # Take that many items from the infinite list
  eB               # Convert each from binary
 K                 # Sort ascending
[                  # Take the first element (i.e. the minimum one)

```
> 3 votes

# Answer
# C (gcc) with `-lgmp`, ~~233~~ ~~231~~ 227 bytes

* -6 thanks to ceilingcat

As it uses the GMP library, the maximum integer that this function handles is quite large. Takes a number as a string to avoid overflowing native types.

```
#import<gmp.h>
f(s,v,w,x,y)char*s,*v;{mpz_t c,l;mpz_init_set_str(c,s,10);mpz_init(l);for(y=x=strlen(v=mpz_get_str(0,2,c));y--;mpz_cmp(c,l)>0?mpz_set(c,l):0)w=v[x-1],bcopy(v,v+1,x-1),*v=w,mpz_set_str(l,v,2);gmp_printf("%Zd",c);}

```

Try it online!

Ungolfed:

```
#import<gmp.h>
f(s, // input value
  v, // bit representation of value
  w, // rotated bit
  x,y // bit string length and loop counter
  )char*s,*v; {
  mpz_t c,l; // current lowest value, test value
  mpz_init_set_str(c,s,10); // initialize variables
  mpz_init(l);
  for(
    y=x=strlen(v=mpz_get_str(0,2,c)); // initialize bit string
    y--;
    mpz_cmp(c,l)>0?mpz_set(c,l):0) { // adjust lowest value
    w=v[x-1]; // get rotated bit
    bcopy(v,v+1,x-1); // rotate
    *v=w; // put rotated bit at top
    mpz_set_str(l,v,2); // get test value
  }
  gmp_printf("%Zd",c);
}

```
> 3 votes

# Answer
# Python, 57 bytes

```
lambda n:int(min(h:=f"{n:b}",*[h:=h[1:]+k for k in h]),2)

```

Attempt This Online!

### Old Python, 58 bytes

```
lambda n:int(min([h:=f"{n:b}"]+[h:=h[1:]+k for k in h]),2)

```

Attempt This Online!
> 3 votes

# Answer
# Python 2, 76 bytes

```
i,o=bin(input())[2:],[]
for x in i:i=i[-1]+i[:-1];o+=[int(i,2)]
print min(o)

```

Try it online!

Python2 because it accepts integers directly as input (no int() required) and it saves a space on the print statement by not needing brackets.
> 2 votes

# Answer
# Retina 0.8.2, 55 bytes

```
.+
$*
+r`\1(1+)
0$1
10
1
.
$&$'$`¶
1
10
+`01
110
O`
\G1

```

Try it online! Explanation:

```
.+
$*

```

Convert to unary.

```
+r`\1(1+)
0$1
10
1

```

Convert to mirrored binary i.e. LSB first, MSB last.

```
.
$&$'$`¶

```

Generate all of the rotations.

```
1
10
+`01
110

```

Convert each rotation back to unary.

```
O`

```

Sort.

```
\G1

```

Convert the shortest to decimal.
> 2 votes

# Answer
# Factor, 43 bytes

```
[ >bin all-rotations [ bin> ] map infimum ]

```

Try it online!

```
>bin              ! convert input from decimal to a binary string
all-rotations     ! get every rotation as a sequence of strings
[ bin> ] map      ! convert each to decimal from binary
infimum           ! get the smallest one

```
> 2 votes

# Answer
# JavaScript (ES6), 57 bytes

*-2 bytes thanks to @l4m2*

```
n=>(m=g=q=>x--?g(q%2<<Math.log2(n,m=m<q?m:q)|q/2):m)(x=n)

```

Try it online!

### Commented

```
n => (              // n = input
  m =               // m = minimum value, initially non-numeric
  g =               // g is a recursive function taking
  q =>              // the current rotation q
  x-- ?             // if x is not equal to 0 (decrement it afterwards):
    g(              //   do a recursive call:
      q % 2 <<      //     using the number of bits in the original
      Math.log2(    //     input, left-shift the LSB so that it takes
        n,          //     the place of the MSB
        m = m < q ? //     update m to min(m, q)
          m         //     (this always updates m to q if m is
        :           //     still non-numeric)
          q         //
      ) | q / 2     //     right-shift all other bits by 1 position
    )               //   end of recursive call
  :                 // else:
    m               //   stop and return m
)(x = n)            // initial call to g with q = x = n

```
> 2 votes

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

```
&/2/'{1_x,*x}\2\

```

Try it online!

* `2\` convert (implicit) input to its binary representation
* `{1_x,*x}\` build a list of all rotations of the bits
* `2/'` convert each back to its decimal representation
* `&/` calculate, and (implicitly) return the minimum
> 2 votes

# Answer
# Python 2.7, 73 bytes

```
x=bin(input())[2:]
print min([int(x[i:]+x[:i],2)for i in range(len(x))])

```
> 2 votes

# Answer
# Vyxal `g`, ~~7~~ 6 bytes

```
ƛ?b$ǓB

```

Try it online!

* -1 thanks to a suggestion from Shaggy

#### Explanation

```
ƛ?b$ǓB  # Implicit input
ƛ       # Map over the range:
 ?b     #  Get the input in binary
   $Ǔ   #  Rotate ^ ^^ times
     B  #  Convert it back from binary
        # g flag gets the minimum of this list
        # Implicit output

```

Previous 7-byter:

```
b:ż¨VǓB  # Implicit input
b        # Convert the input to binary
 :ż      # Duplicate and push range(len(^))
   ¨V    # Map over each element in ^:
     Ǔ   #  Rotate ^^^ ^ places to the left
      B  # Convert each back from binary
         # g flag gets the minimum of this list
         # Implicit output

```
> 2 votes

# Answer
# Julia 1.0, ~~84~~ 78 bytes

```
!x=(c=string(x,base=2);r=keys(c);min((r.|>i->parse(Int,"0b"*(c^2)[i.+r]))...))

```

Try it online!

* `c` is the bitstring of input `x`. Another method would be `lstrip(bitstring(x),'0')`.
* `r` contains the indices in `c` and is iterated over the repeated bitstring `c^2` to get each rotation.
* `min` treats a vector `V` as a single value, so the splat operator is used: `min(V...)`. Another method would be `minimum(V)`.

-6 bytes thanks to MarcMush:
> 2 votes

# Answer
# MATL, ~~13~~ 12 bytes

```
:"GB@YSXBvX<

```

*1 byte saved thanks to @lmendo*

Try it at MATL Online!

**Explanation**

```
       % Implicitly grab the input (N)
:      % Create an array from [1...N]
"      % For each value in the array
  G    % Grab the input as a number
  B    % Convert to an array of booleans representing the binary equivalent
  @YS  % Circularly shift by the loop index
  XB   % Convert the result from binary to decimal
  v    % Vertically concatenate the entire stack
  X<   % Compute the minimum value so far
       % Implicitly display the result

```
> 2 votes

# Answer
# Java 10, 118 bytes

```
n->{var b=n.toString(n,2);for(int l=b.length(),i=l,t;i-->0;n=t<n?t:n)t=n.parseInt((b+b).substring(i,i+l),2);return n;}

```

Input \\$n\\$; outputs the smallest bit rotation.

Try it online.

**Explanation:**

```
n->{                       // Method with Integer as both parameter and return-type
  var b=n.toString(n,2);   //  Convert the input-integer to a binary-String
  for(int l=b.length(),    //  Set `l` to the length of this binary-String
      i=l,t;i-->0          //  Loop `i` in the range (l,0]:
      ;                    //    After every iteration:
       n=t<n?              //     If `t` is smaller than `n`:
             t:n)          //      Set `n` to this new minimum `t`
    t=                     //   Set `t` to:
      n.parseInt(          //    The following binary converted to a base-10 integer:
         (b+b)             //     Append the binary-String to itself
         .substring(i,i+l) //     And then get its substring in the range [i,i+l)
       ,2);
  return n;}               //  Return the modified `n` holding the smallest result

```
> 1 votes

# Answer
# Charcoal, 18 bytes

```
≔⍘Ｎ²θＩ⍘⌊Ｅθ⭆θ§θ⁺κμ²

```

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

```
≔⍘Ｎ²θ

```

Convert the input to binary.

```
Ｉ⍘⌊Ｅθ⭆θ§θ⁺κμ²

```

Generate all of the rotations, take the minimum, and convert back to decimal.
> 1 votes

# Answer
# Zsh, 70 bytes

```
b=$[[##2]$1];for i ({1..$#b})m+=($[2#${b:$i}${b:0:$i}]);printf ${(n)m}

```

Try it online!
> 1 votes

# Answer
# Husk, 7 bytes

```
ḋ▼U¡ṙ1ḋ

```

Try it online!

```
      ḋ  # convert to bits,
   ¡     # make infinite list by repeatedly
    ṙ1   #   rotating by one position,
  U      # get the longest unique prefix,
 ▼       # get the minimum of this,
ḋ        # and get the value from the bits.

```
> 1 votes

# Answer
# Japt `-g`, ~~10~~ 8 bytes

```
Æ¤éX ÍÃñ

```

Try it

Saved 2 thanks to Shaggy

```
Æ¤éX ÍÃñ : implicit input number
Æ        : map over the range [0, input - 1]:
 ¤       :   the input as a binary string
  éX     :   rotated n places
     Í   :   converted back to a number
      Ã  : end map, now we have all rotations
       ñ : sort them, ascending
         : -g: first element of list (i.e. the lowest rotation)

```
> 1 votes

# Answer
# Desmos, 95 bytes

```
L=[floor(log_2N)...0]
B=mod(floor(N/2^L),2)
f(N)=[total(join(B[i+1...],B[1...i])2^L)fori=L].min

```

Even worse than the fish answer... at least it beats Java :P

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Scala, 107 bytes

Golfed version. Try it online!

```
n=>{val b=n.toBinaryString;(0 to b.size-1).map(i=>Integer.parseInt(b.substring(i)+b.substring(0,i),2)).min}

```

Ungolfed version.

```
object Main {
  def main(args: Array[String]): Unit = {
    println(minBinaryRotation(177))
  }

  def minBinaryRotation(n: Int): Int = {
    val binaryString = n.toBinaryString
    val rotations = for (i <- 0 until binaryString.length) yield {
      val rotated = binaryString.substring(i) + binaryString.substring(0, i)
      Integer.parseInt(rotated, 2)
    }
    rotations.min
  }
}

```
> 1 votes

# Answer
# Japt, 8 bytes

```
Æ¤éXÃÍÎÍ

```

Try it
> 1 votes

# Answer
# Thunno 2 `M`, 5 bytes

```
ḃż€ẒḂ

```

Try it online!

#### Explanation

```
ḃż€ẒḂ  # Implicit input
ḃ      # Convert to binary
 ż     # Push [1..length]
  €Ẓ   # Rotate right
    Ḃ  # Convert from binary
       # Take the minimum
       # Implicit output

```
> 1 votes

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

```
sub{$r=1<<log($x=pop)/log 2;min map$x=$x%2*$r+($x>>1),1..$r}

```

Try it online!
> 0 votes

# Answer
# Uiua, 11 bytes

```
/↧°⋯≡↻⇡⊃⧻¤⋯

```

Try it!
> 0 votes

---
Tags: code-golf, sequence, integer
---


title: Rotate N Values in a List

text:
# Question
Title: Rotate N Values in a List
Similar to this.

Input a list and rotate N numbers in it given their indices. The following example uses 1-indexing, but feel free to use either.

In other words, take a list of indices and a list of numbers:

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

Separate out the elements at those indices:

[  2   4 5   7]
 1   3     6

Rotate those left:

[  2   4 5   7]
 3   6     1

Insert them back in

[3 2 6 4 5 1 7]

And there's your result!

```

## Testcases

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

```

## Rules

* You can assume the N indices are given in order and they're distinct.
* Default I/O rules apply, standard loopholes are banned. This is code-golf, so shortest code in each language wins.

# Answer
> 8 votes
# , 35 bytes

```
function(a,i){a[i]=a[c(i,i)[-1]];a}

```

Try it online!

# Answer
> 6 votes
# , 11 bytes

```
(1|.{)`[`]}

```

Try it online!

* `}` Amend...
* `]` The right argument...
* `[` At the indexes specified by the left argument...
* `(1|.{)` With the current values at those indexes `{` rotated once `1|.`

# Answer
> 6 votes
# Wolfram Language (Mathematica), 24 bytes

-1 byte thanks to @att.

```
RotateLeft~SubsetMap~##&

```

Try it online!

# Answer
> 4 votes
# MATL, 8 bytes

```
yy)w1YS(

```

Indices are 1-based.

Try it online! Or verify all test cases.

### Explanation

Consider inputs `[10, 20, 30, 40, 50, 60, 70]`, `[1, 3, 6]` as an example. As usual, the stack is shown with the most recent element below.

```
yy    % Take the two inputs implicitly. Duplicate them
      % STACK: [10, 20, 30, 40, 50, 60, 70]
      %        [1, 3, 6]
      %        [10, 20, 30, 40, 50, 60, 70]
      %        [1, 3, 6]
)     % Reference indexing: takes entries in first input indexed by the second
      % STACK: [10, 20, 30, 40, 50, 60, 70]
      %        [1, 3, 6]
      %        [10, 30, 60]
w     % Swap
      % STACK: [10, 20, 30, 40, 50, 60, 70]
      %        [10, 30, 60]
      %        [1, 3, 6]
1YS   % Rotate 1 position to the right
      % STACK: [10, 20, 30, 40, 50, 60, 70]
      %        [10, 30, 60]
      %        [6, 1, 3]
(     % Assignment indexing: overwrites the first input with the values from
      % the second at the positions given by the third
      % STACK: [30, 20, 60, 40, 50, 10, 70]

```

# Answer
> 4 votes
# JavaScript (ES6), 48 bytes

Expects `(list)(indices)`, 0-indexed.

```
a=>b=>a.map((v,i)=>b[j]^i?v:a[b[++j]||b[0]],j=0)

```

Try it online!

### Commented

```
a =>             // a[] = main list
b =>             // b[] = list of indices (0-indexed)
a.map((v, i) =>  // for each value v at position i in a[]:
  b[j] ^ i ?     //   if b[j] is not equal to i or b[j] is undefined:
    v            //     leave v unchanged
  :              //   else:
    a[ b[++j] || //     increment j and use a[b[j]],
       b[0]      //     or a[b[0]] if it's undefined
    ],           //     NB: because the indices are given in order, '0'
                 //     may only appear at position 0 in b[] and cannot
                 //     trigger the b[0] failover
  j = 0          //   start with j = 0
)                // end of map()

```

# Answer
> 4 votes
# Rust, 58 bytes

```
|a:&mut[_],b:&[_]|for w in b.windows(2){a.swap(w[0],w[1])}

```

Try it online!

0-based indexing. Changes the input array in-place.

# Answer
> 4 votes
# Python 3, 54 bytes

```
def f(L,I):
 r=L[I[0]]
 for i in I[::-1]:r,L[i]=L[i],r

```

Try it online!

0-based, in-place. Works for length 1 but not length 0 index list.

# Answer
> 3 votes
# Raku, 18 bytes

```
{@^a[@^i].=rotate}

```

Try it online!

0-based indexing. Changes the input array in-place.

This is the same answer as my answer to the "swap two values in a list" question.

# Answer
> 3 votes
# APL+WIN, 19 bytes

Prompts for inices then vector

```
n[i]←(n←⎕)[1⌽i←⎕]⋄n

```

Try it online!Thanks to Dyalog Classic

# Answer
> 3 votes
# APL(Dyalog Unicode), 8 bytes SBCS

```
{1⌽@⍺⊢⍵}

```

Try it on APLgolf!

A dfn submission which takes indices on the left, array on the right.

# Answer
> 2 votes
# Charcoal, 16 bytes

```
ＩＥθ⎇№ηκ§θ§η⊕⌕ηκι

```

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

```
  θ                 Data array
 Ｅ                  Map over values
    №               Count of
      κ             Current index
     η              In index array
   ⎇                If index present then
        θ           Data array
       §            Indexed by
          η         Index array
         §          Indexed by
            ⌕       Index of
              κ     Current index
             η      In index array
           ⊕        Incremented
                ι    Otherwise original value
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 2 votes
# Core Maude, ~~242~~ 219 bytes

```
mod R is pr LIST{Nat}. ops r x : Nat Nat ~> Nat . var A B I J : Nat . var R X
Y :[Nat]. ceq r(X A Y,I R)= X x(A I Y,R)if size(X)= I . ceq x(A I X B Y,J R)=
B X x(A J Y,R)if size(X)+ s I = J . eq x(A I X,nil)= A X . endm

```

The result is obtained by reducing the `r` function with the two lists (given as Maude lists) with zero-indexing. It is assumed the indices are distinct and ordered.

This solution only works for \\$N \> 0\\$. It wouldn't be difficult to handle \\$N = 0\\$, but it would be expensive byte-wise. (It would require an extra equation.)

### Example Session

```
             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
           Sat Nov  6 01:42:43 2021
Maude> mod R is pr LIST{Nat}. ops r x : Nat Nat ~> Nat . var A B I J : Nat . var R X
> Y :[Nat]. ceq r(X A Y,I R)= X x(A I Y,R)if size(X)= I . ceq x(A I X B Y,J R)=
> B X x(A J Y,R)if size(X)+ s I = J . eq x(A I X,nil)= A X . endm
Maude> red r(1 2 3 4 5 6 7, 0 2 5) .
result NeList{Nat}: 3 2 6 4 5 1 7
Maude> red r(1 2 3 4 5 6 7, 2) .
result NeList{Nat}: 1 2 3 4 5 6 7

```

### Ungolfed

```
mod R is
    pr LIST{Nat} .
    ops r x : Nat Nat ~> Nat .
    var A B I J : Nat .
    var R X Y : [Nat] .
    ceq r(X A Y, I R) = X x(A I Y, R) if size(X) = I .
    ceq x(A I X B Y, J R) = B X x(A J Y, R) if size(X) + s I = J .
    eq x(A I X, nil) = A X .
endm

```

---

Saved 23 bytes by prepending `A` and `I` to the first list rather than passing as a separate parameter. This requires a new function `x`, but `x` can be declared in the same `ops` declaration as `r`.

# Answer
> 2 votes
# Vyxal, 7 bytes

```
İǓZ(n÷Ȧ

```

Try it Online!

```
İ       # Get the elements at those indices
 Ǔ      # Rotate
  Z     # Zip with the indices
   (n   # Foreach
     ÷Ȧ # Assign that index to that value

```

# Answer
> 2 votes
# 05AB1E, 4 bytes

```
èÀ¹ǝ

```

First input-list are the 0-based indices, second the full list.

Try it online or verify all test cases.

A minor alternative could be `è¹Áǝ`: try it online.

**Explanation:**

```
è     # Get the values from the second (implicit) input-list at the indices of the first
      # (implicit) input-list
 À    # Rotate those values once towards the left
  ¹ǝ  # Insert them back into the second (implicit) input-list at the indices of the
      # first input-list
      # (after which the list is output implicitly as result)

è     # Same as above: get the values at the indices
 ¹    # Push the first input-list of indices again
  Á   # Rotate the indices-list once towards the right
   ǝ  # Insert the values at those indices back into the second (implicit) input-list
      # (after which the list is output implicitly as result)

```

# Answer
> 1 votes
# Python 3 \+ numpy, 34, 30 bytes (@Neil)

```
def f(L,I):L[I]=L[I[1:]+I[:1]]

```

Try it online!

Old version

0-based, in-place. Data L must be a numpy array, index I can be many things: range, array, list, but not tuple must be a list. I can be empty.

The fine print

# Answer
> 1 votes
# ErrLess, 44 bytes

```
0ml0$:Y@;2/<1-[{@;$@1+3G$-:1G$r$;$1+$:y}!r.M

```

A macro.

## Explanation

```
0m {...} M { Macro identified by 0, takes two stacks as input: (list indices) }

l0$:Y@;2/<1-[{@;$@1+3G$-:1G$r$;$1+$:y}! { Reverse indices list }
l0$:                                    { Add (0 #-of-indices) to the top of the stack: (list indices (i N)) }
    Y {...} 1-[{ {...} y}               { While }
     @;2/<                              { i < N // 2 }
              @;$@1+                    { (list indices (i N) N i i+1) }
                    3G$-:               { (list indices (i N) (i N-i-1) }
                         1G$            { (list (i N) indices (i N-i-1) }
                            r           { Swap the i-th and i-th from last elements of indices: (list (i N) indices) }
                             $          { Swap: (list indices (i N)) }
                              ;         { (list indices i N) }
                               $1+$     { (list indices i+1 N) }
                                   :    { (list indices (i+1 N) }
                                      ! { Pop: (list indices) }

r. { Rotate & halt (return) }

```

The biggest difficulty was reversing the indices list, as ErrLess rotates to the right, not to the left. If we had to rotate right the macro would be very easy: `0mr.M`. Exactly the same as in this answer, in fact.

You can test it with the following program:

```
0ml0$:Y@;2/<1-[{@;$@1+3G$-:1G$r$;$1+$:y}!r.M

{ Uses 0-based indexing. Appended "1-" to the end of the list of indices to convert to 0-based indexing }

1,2x3x4x5x6x7x 1,3x6x 1- 0"# a? { -> (3 2 6 4 5 1 7) }

4,1x3x2x 1,2x3x 1- 0"# a? { -> (1 3 4 2) }

1,2x3x4x5x6x7x 1,3x6x 1- 0"# a? { -> (3 2 6 4 5 1 7) }

5,6x7x1x2x3x4x 2,4x5x 1- 0"# a? { -> (5 1 7 2 6 3 4) }

3,2x6x4x 1,3x 1- 0"# a? { -> (6 2 3 4) }

.

```

Try it online!

# Answer
> 1 votes
# Ruby, 46 bytes

```
->a,i{eval"a[#{i*B='],a['}]=a[#{i.rotate*B}]"}

```

Try it online!

Lambda: modifies *a* by *i* indexes,
constructs an expression like for example:
*a\[1\],a\[2\],a\[3\]=a\[2\],a\[3\],a\[1\]*
and evaluates it.

# Answer
> 1 votes
# Retina 0.8.2, 114 bytes

```
(\d+).*$
$&,$1
\d+(?=.*$)
$*
\d+(?<=((,)|.)*)(?=.*¶(1*,)*(?<-2>1)*(?(2)$),(1)*)(?<=(?=(?<-4>\d+,)*(\d+)).*)
$5
1G`

```

Try it online! 0-indexed. Explanation:

```
(\d+).*$
$&,$1

```

Duplicate the first index and append it.

```
\d+(?=.*$)
$*

```

Convert all of the indices to unary.

```
\d+

```

Match an array element...

```
(?<=((,)|.)*)

```

... calculating its index...

```
(?=.*¶(1*,)*(?<-2>1)*(?(2)$),(1)*)

```

... where that index exists in the list of indices, capturing the next index...

```
(?<=(?=(?<-4>\d+,)*(\d+)).*)

```

... capture the array element at that index...

```
$5

```

... and replace the original element.

```
1G`

```

Delete the indices.

# Answer
> 1 votes
# Zsh, 60 bytes

**Input**: values as arguments, indices on stdin separated by whitespace. 1-indexed.

```
b=(`<&0`)
for x;{((k=b[(I)$[++i]]))&&x=$@[b[k%$#b+1]];<<<$x}

```

Try it online!

```
b=(`<&0`)  # split stdin on whitespace
for x;{    # for x (implicit 'in "$@"')
   ((k=b[(I)$[++i]])) &&  # If we find $x's index in the array $b
    x=$@[b[k%$#b+1]]      # then update $x to be the elemnt at index $k + 1 (wrapped)
    <<<$x                 # output the element $x
}

```

# Answer
> 1 votes
# TI-Basic, 55 bytes

```
Prompt A,I
ʟA(ʟI(1→F
For(I,2,dim(ʟI
ʟA(ʟI(I→ʟA(ʟI(I-1
End
F→ʟA(ʟI(dim(ʟI

```

`ʟA` is manipulated in-place. Indexes are 1-based.

# Answer
> 0 votes
# Uiua, 6 bytes

```
⍜⊏(↻1)

```

Try it!

0-indexed.

```
⍜⊏(↻1)
⍜       # apply one function 'under' another
 ⊏      # at the given indices
  (↻1)  # rotate left by one

```

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


title: Be big more often

text:
# Question
Title: Be big more often
### Related

You are a manager at a large number factory. You want to show everyone your business is doing well, by showing randomly chosen samples. Unfortunately, your business is not doing that well. But luckily, you have a bit of ingenuity...

---

Write a program or function that when given an array of unique, positive numbers, which may include floats, returns a random number from the array, with **bigger numbers having a higher probability of being chosen \\$\left(a\_n \> a\_m \implies P(a\_n) \> P(a\_m)\right)\\$**, **no two numbers being chosen with the same probability \\$\left(P(a\_n) \not = P(a\_m)\right)\\$**, and **all numbers having a non-zero chance of being chosen \\$\left(P(a\_n) \not = 0\right)\\$**. Anyways, this is , so shortest code wins!

# Answer
# Python, 41 bytes

```
lambda l:choices(l,l)
from random import*

```

Attempt This Online! or run it 100000 times

Uses the list itself as the weights.
> 25 votes

# Answer
# , 27 bytes

(Or 20 bytes in R\>=4.1 using `\` instead of `function`)

```
function(x)-sample(-x,1,,x)

```

Try it online!

The 4th argument of R’s `sample` function is `prob`=“a vector of probability weights for obtaining the elements of the vector being sampled”.

Unfortunately, a “convenience” feature of `sample` changes its behaviour when its first argument is a single positive number, so we need to negate it here to avoid this, and then re-negate the result.

——

# , 31 bytes

(Or 24 bytes in R\>=4.1 using `\` instead of `function`)

```
function(x)max(-sample(-x,2,T))

```

Try it online!

Return the highest of two random picks.
> 14 votes

# Answer
# Python, 64 bytes (also supports negative numbers)

```
lambda l:sorted(l)[int(len(l)*random()**.5)]
from random import*

```

Attempt This Online!

## Explanation

Sort the list, the pick a random element. The square root biases the result towards the end of the list.
> 11 votes

# Answer
# , 8 bytes

```
#~{~1?+/

```

Attempt This Online!

* `1?+/` Sum the numbers and then choose a random index between 0 and the sum
* `#~{~` Take that index from a new array formed by duplicating each number as many times as itself. Eg, `#~ 1 2 3` gives `1 2 2 3 3 3`, and we choose a random index from the interval \\$\[0,6)\\$.
> 8 votes

# Answer
# WolframLanguage, 63 48 bytes

*Thanks to att* for shaving of 15

```
Sort[#][[Floor@Log2[Random[](2^Tr[1^#]2-3)+2]]]&

```

Original answer:

```
f[r_]:=Sort[r][[Floor@Log[2,RandomReal[{2,2^(Length@r+1)-1}]]]]

```

Sorts the array and picks a random number between `2` and `2^(l+1)-1`, where `l` is the length of the list. Then takes the logarithm to get the array index. This gives each number a twice as high probability to be chosen as the previous one.

## Example

`{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`

For a run of 2\*10^7 repetitions:

`{{1, 19562}, {2, 39068}, {3, 78145}, {4, 156309}, {5, 313362}, {6, 625087}, {7, 1249297}, {8, 2504498}, {9, 5005805}, {10, 10008867}}`
> 7 votes

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

```
a=>a.sort()[a.length*Math.random()**.5|0]

```

Try it online! or run it 100000 times

Takes an `Float64Array` (so the sorting works properly). Port of bsoelch's Python answer.
+10 bytes to take a regular array.
> 7 votes

# Answer
# Vyxal, 4 bytes

```
℅?℅∴

```

Try it Online!

Return the highest of two random picks

```
℅       # Random choice of single item from input array
 ?      # Input (again)
  ℅     # Random choice of single item from this
    ∴   # Maximum of these two values

```
> 7 votes

# Answer
# Ruby, ~~32~~ 24 bytes

```
->l{(l+l).sample(2).max}

```

Try it online!

Thanks to Dominic van Essen for -4 bytes and the idea to get to -8.
> 5 votes

# Answer
# Jelly, 3 bytes

```
X»X

```

Attempt This Online!

Distribution over 1000 runs: Attempt This Online!

Uses Dominic van Essen's insight: pick a random element (`X`), twice, then take the larger of them (`»`).
> 5 votes

# Answer
# Charcoal, 10 bytes

```
ＦＡＦι⊞υιＩ‽υ

```

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

```
ＦＡ

```

Loop over the input numbers.

```
Ｆι⊞υι

```

Push each number that many times to the predefined empty list.

```
Ｉ‽υ

```

Output a random number from that list.

8 bytes using the newer version of Charcoal on ATO:

```
Ｉ‽ΣＥＡＥιι

```

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

```
    Ａ       Input list
   Ｅ        Map over elements
      ι     Current element
     Ｅ      Map over implicit range
       ι    Outer element
  Σ         Flatten
 ‽          Random element
Ｉ           Cast to string
            Implicitly print

```

A port of @JoyalMathew's JavaScript answer in straight succinct Charcoal is only 6 bytes:

```
Ｉ⌈∨Φθ‽

```

Try it online! Explanation:

```
    θ   Input list
   Φ    Filtered by
     ‽  Random coin flip
  ∨     If empty then implicitly use input list
 ⌈      Take the maximum
Ｉ       Cast to string
        Implicitly print

```
> 4 votes

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

```
a=>a.sort((a,b)=>b-a).filter(_=>Math.random()<.5)[0]||a[0]

```

Try it online!

Sorts the numbers, filters them randomly, then chooses the largest one.
> 4 votes

# Answer
# Raku, 13 bytes

```
*.roll(2).max

```

Attempt This Online!

Picks two elements independently and returns the max of the two.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
RandomChoice[#->#]&

```

Try it online! Like other languages, the builtin can use weights, so the input can serve as the weights as well. Works with nonnegative real numbers.
> 4 votes

# Answer
# Factor, 35 bytes

```
[ [ dup <array> ] map-flat random ]

```

Attempt This Online!

Create n copies of each n, and select one at random (uniformly).

For instance, `{ 5 1 2 }` becomes `{ 5 5 5 5 5 1 2 2 }`.
> 3 votes

# Answer
# Julia, 37 bytes

```
!l=rand([fill.(sort(l),keys(l))...;])

```

Attempt This Online!

sort the list and repeat each element by their index before randomly choosing a number

### with integers only, 25 bytes

```
!l=rand([fill.(l,l)...;])

```

Attempt This Online!

directly repeat each number by itself
> 3 votes

# Answer
# Jelly, 4 bytes

```
ṢxJX

```

A monadic Link that accepts a list of distinct floats and outputs a random one.

**Try it online!** Or see the results of 10,000 runs.

### How?

Weights by the count of lesser-or-equal values.

The probability of picking the \\$a^{\text{th}}\\$ most minor of \\$n\\$ numbers is \\$\frac{2a}{n(n+1)}\\$.

For example given `[2.5, 2.2, 2.4, 2.6, 2.1, 2.3]` (\\$n(n+1)=6(6+1)=42\\$):
$$P(2.1)=\frac{1}{21}, P(2.2)=\frac{2}{21}, \cdots , P(2.6)=\frac{6}{21}$$

```
ṢxJX - Link: list of numbers, A
Ṣ    - sort {A} -> [a1, a2, a3, ...]
  J  - indices {A} -> [1, 2, 3, ...]
 x   - {sorted A} times {indices of A} -> [a1, a2, a2, a3, a3, a3, ...]
   X - uniform random choice

```
> 3 votes

# Answer
# Vyxal, 3 bytes

```
øḊ℅

```

Try it Online!

## Explained

```
øḊ℅
øḊ   # Run length decode the input, using the input as both character source and lengths. Basically, zip and run length decode
  ℅  # Choose randomly from that list.

```

Created with the help of Luminespire.
> 1 votes

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

```
a=>a.sort((a,b)=>b-a)[.4/Math.random()|0]||a[0]

```

Try it online!

# JavaScript (V8), 53 bytes

```
a=>Math.max(...a.map(_=>a[a.length*Math.random()|0]))

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
{.s˜Ω

```

Try it online.

Or alternatively, a port of *@DominicVanEssen*'s second R answer is 5 bytes as well:

```
ΩIΩ‚à

```

Try it online.

**Explanation:**

```
{      # Sort the (implicit) input-list from lowest to highest
 .s    # Pop and push a list of its suffixes
   ˜   # Flatten it
    Ω  # Pop and push a random item from this list
       # (which is output implicitly as result)

```

```
Ω      # Push a random item from the (implicit) input-list
 I     # Push the input-list
  Ω    # Pop and push another random item from it
   ‚   # Pair the two together
    à  # Pop and push its maximum
       # (which is output implicitly as result)

```
> 0 votes

# Answer
# MathGolf, 4 bytes

```
‼ww╙

```

Try it online.

Port of *@DominicVanEssen*'s second R answer.

**Explanation:**

```
‼     # Apply the next two builtins separately on the current stack:
 w    #  Pop and push a random item from the given (implicit) input-list
  w   #  Same
   ╙  # Pop the top two items on the stack, and leave its maximum
      # (after which the entire stack is output implicitly as result)

```
> 0 votes

# Answer
# Uiua, 11 bytes

```
⊡⌊×↥⚂⚂⧻.⊏⍏.

```

Try it online!

Built on a similar principle to lots of others others (randomly pick two items and use the max), but tweaked slightly

## Explanation

```
        ⊏⍏. # sort the array
      ⧻.    # get its length
   ↥⚂⚂      # max of two random numbers [0,1)
  ×         # multiply to scale to [0,len)
⊡⌊          # floor and index into array

```
> 0 votes

# Answer
# Perl 5 `-pa`, 44 bytes

```
@b=map{($_)x++$,}sort{$a-$b}@F;$_=$b[rand@b]

```

Try it online!
> 0 votes

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