title: Moving modest minimum

text:
# Question
Title: Moving modest minimum
*Inspired by a question over at Stack Overflow. The title here is entirely my fault.*

---

## The challenge

Given a list of positive integers containing at least two entries, replace each number by the minimum of all entries excluding itself.

## Test cases

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

```

## Rules

The algorithm should theoretically work for any input size (greater than one) and values (positive integers). It's accepted if the program is limited by time, memory or data types and so only works for numbers up to a given value, or for input size up to a given value.

Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.

Input can be taken by any reasonable means; and with any format. Same for output. Input and output formats may be different.

Shortest code in bytes wins.

# Answer
> 20 votes
# Jelly, ~~9~~ ~~6~~ 5 bytes

```
~~JḟÐ€`ị⁸Ṃ€~~
~~ṙJṖ€Ṃ€~~
ṙJṖ«/     argument: 1D array (z)

 J        [1,2,3,...,len(z)]
ṙ         rotate z by each of the above amount (current array is 2D)
  Ṗ       remove the last array
   «/     reduce by [impliclitly vectorized] minimum

```

Try it online!

Verify all of them at once! (slightly modified)

I'm pretty sure Dennis can out-golf this.

## How it works

The algorithm is rather convoluted. Let us observe what this does to `[4,2,2,5]`.

Firstly, we use `J` to obtain `[1,2,3,4]`. Note that Jelly uses 1-indexing.

Then, we see . It takes two arguments: an array and an integer. It rotates the array to the left by an amount specified by the integer. Here,  would see `[4,2,2,5]` on its left and `[1,2,3,4]` on its right (more about how this works can be found in the tutorial). In Jelly, commands implicitly vectorize. Therefore, this command will be performed over each individual element on the right, which is why we would create a 2D array:

Therefore, `[4,2,2,5]ṙ[1,2,3,4]` becomes `[[4,2,2,5]ṙ1,[4,2,2,5]ṙ2,[4,2,2,5]ṙ3,[4,2,2,5]ṙ4]`, which becomes:

```
[[2,2,5,4],
 [2,5,4,2],
 [5,4,2,2],
 [4,2,2,5]]

```

Notice that the original elements are on the last row, since in that row we rotated to the left by an amount equal to the length of the array, which is why we use  next to remove that row, so that the columns are the collections of the elements of the array which are not at the current index:

```
[[2,2,5,4],
 [2,5,4,2],
 [5,4,2,2]]

```

The following operation, `«/`, is also quite convoluted. Firstly, `«` returns the minimum of the two numbers it sees on its left and on its right. For example, `5«3` returns `3`. Now, if the two arguments are arrays, then it would vectorize as I have said above. What this means it that `[1,5,2,3]«[4,1,5,2]` would become `[1«4,5«1,2«5,3«2]` which is `[1,1,2,2]`. Now, `/` is `reduce`, which means that we do the operation over each row until the end. For example, `[1,2,3,4]+/` would become `((1+2)+3)+4`, which is the sum of the array `[1,2,3,4]`.

So, if we apply `«/` to the 2D array we just obtained, we would get:

```
([2,2,5,4]«[2,5,4,2])«[5,4,2,2]

```

which, because of the vectorization, would be equivalent to:

```
[2«2«5,2«5«4,5«4«2,4«2«2]

```

which computes the minimum of every array without the element at the index.

# Answer
> 44 votes
# Python 2, 41 bytes

```
lambda l:[sorted(l)[x==min(l)]for x in l]

```

Try it online!

For each element `x` we check whether `x==min(l)`. If not, this is `False`, which is treated as `0` when used as a list index into `sorted(l)`, giving the smallest element. Otherwise, it's `True` aka `1`, giving the second-smallest element, since that element itself is smallest and should be ignored.

# Answer
> 19 votes
# Jelly, 3 bytes

### Now possible in 3 bytes, since 2017-08-13:

```
Ṃ-Ƥ - map minimum over overlapping outfixes of length one less than the input

```

Try it online!

---

### Original, 5 bytes

```
=Ṃ‘ịṢ

```

**Try it online!**

#### How?

```
=Ṃ‘ịṢ - Main link: list a     e.g.  [4,3,2,5]
 Ṃ    - minimum of a                2
=     - equals? (vectorises)        [0,0,1,0]
  ‘   - increment                   [1,1,2,1]
    Ṣ - sort a                      [2,3,4,5]
   ị  - index into                  [2,2,3,2]

```

# Answer
> 12 votes
# Haskell, ~~42~~ ~~41~~ 39 bytes

EDIT:

* -1 byte thanks to nimi!
* -2 bytes. One thanks to xnor! And one by myself.

`f` takes a list of integers (or any `Ord` type) and returns a list.

```
f(x:y)=minimum y:(fst<$>zip(f$y++[x])y)

```

Try it online!

`f` recurses while rotating the list. `x` is the first list element and `y` the remainder. Since the recursion is infinite, the result list needs to be cut off: `fst<$>zip...y` is a shorter way of saying `take(length y)...`.

# Answer
> 9 votes
# Octave, 26 bytes

```
@(x)sort(x)((x==min(x))+1)

```

A similar approach as used in this answer, which happens to be the same as this.

I'm not really a fan of just porting other answers, which is why I'd like to note that I had a similar idea before I saw the other ones.

**Explanation:**

Jonathan Allan has already provided a good explanation for the Jelly-code, so this covers the Octave-bit, and why it works (and wouldn't work in MATLAB).

```
@(x)                       % An unnamed anonymous function taking a vector x as input
    sort(x)                % Gives a sorted version of x
            (x==min(x))    % Checks if each element is equal to the minimum value
           ((x==min(x))+1) % Adds 1 to the boolean vector, to use as indices
@(x)sort(x)((x==min(x))+1) % Complete function

```

This doesn't work in MATLAB, since inline assignments and direct indexing doesn't work. `sort(x)(1)` gives an error in MATLAB, not the first element in the sorted vector.

# Answer
> 8 votes
# Brachylog, ~~13~~ 12 bytes

```
l+₁:?⊇ᶠ⁽⌋ᵐb↔

```

Try it online!

*Saved one byte thanks to @ais523.*

### Explanation

```
l+₁:?            The list [length(Input) + 1, Input]
     ⊇ᶠ⁽         Find the length(Input) + 1 first subsets of the Input
        ⌋ᵐ       Get the min of each subset
           b↔    Remove the first element and reverse

```

We exploit the fact that  unifies subsets from biggest to smallest. For example for `[1,2,3]`, the subsets we get are in this order: `[1,2,3], [1,2], [1,3], [2,3], [1], [2], [3], []`.

We can see that the subsets `[1,2], [1,3], [2,3]` are the ones we want the minimum from, but are in the reverse order compared to the input list (hence the ). We can select those subsets only by finding the first `length(Input) + 1` subsets, which will contain all of them + the entire list first. We discard that entire list with `b`.

# Answer
> 8 votes
## Haskell, 41 bytes

```
a#(b:c)=minimum(a++c):(b:a)#c
a#b=b
([]#)

```

Usage example: `([]#) [4,3,2,5]`-\> `[2,2,3,2]`. Try it online!

Start with an empty accumulator `a` and run down the input list. The next element in the output list is the minimum of the accumulator `a` and all but the first element of the input list (-\>`c`) followed by a recursive call with the first element `b` added to the accumulator and `c`. Stop when you reach the end of the input list.

# Answer
> 7 votes
## JavaScript (ES6), ~~50~~ 46 bytes

```
a=>a.map((_,i)=>Math.min(...a.filter(_=>i--)))

```

Edit: Saved 4 bytes thanks to @Arnauld.

# Answer
> 7 votes
# R, ~~46~~ 31 bytes

```
l=scan();sort(l)[(min(l)==l)+1]

```

implements Stewie Griffin's solution in R, alas, my original idea is 50% longer! still reads the list from stdin, but now returns a much more readable numeric vector.

Try it online!

### old implementation:

```
l=scan();Map(function(x)min(l[-x]),match(l,l))

```

reads in the list from stdin. A negative index `l[-x]` excludes the element from the list, and `match(l,l)` returns the index of the first occurrence of each element of the list. Returns a list.

# Answer
> 6 votes
# Actually, 13 bytes

```
;;S╝m╗⌠╜=╛E⌡M

```

Uses the same technique that xnor also discovered.

Try it online!

Explanation:

```
;;S╝m╗⌠╜=╛E⌡M
;;             make two extra copies of input list
  S╝           sort one and save it in register 1
    m╗         save the minimum of the other in register 0
      ⌠╜=╛E⌡M  for each value in list:
       ╜=╛E      return the minimum element of the input list if the value is not equal to the minimum, else return the second-smallest element

```

# Answer
> 6 votes
# Uiua, 8 bytes

```
/↧÷⊞≠.⍏.

```

Vyxal port is 10 bytes:

```
⊏⊃'=/↧'⊏⍏.

```

Try these online!

```
/↧÷⊞≠.⍏.    input: a positive integer vector
   ⊞≠.⍏     a matrix of the size of the input where the diagonal is 0s and
              the rest are 1s
  ÷      .    divide each number in the input by each row of the above matrix,
              giving infinities where division by 0 occurs
/↧            minimum of each column

⊏⊃'=/↧'⊏⍏.
 ⊃        .   fork on two functions with two copies of input vectors as arguments:
   '=/↧        for each element, 1 if it is the minimum, 0 otherwise
       '⊏⍏    input sorted
⊏              select 0th or 1st item from the sorted list

```

Alternative 8:

```
⊏=0⊃⍏⊏⍏.

```

Try it online!

```
⊏=0⊃⍏⊏⍏.
   ⊃⍏⊏⍏.    take the input array and push (rank, sorted)
     ⍏  ⍏     rank: lowest number is replaced with 0, next lowest 1, ...
       ⊏⍏.     sorted: lowest number is placed first, next 2nd, ...
 =0             for each element, 1 if rank is 0, 0 otherwise
⊏               select 1st in the sorted array if rank 0, 0th otherwise

```

# Answer
> 5 votes
# Python 2, 51 bytes

I know there's already a better Python solution, but I still want to post mine.

```
lambda L:[min(L[:i]+L[i+1:])for i in range(len(L))]

```

**Try it online**

# Answer
> 5 votes
## Mathematica 34 Bytes

```
Min[#~Drop~{i}]~Table~{i,Tr[1^#]}&

```

# Answer
> 5 votes
# PowerShell, 68 59 bytes

```
($a=$args)|%{$b+=@((($c=$a|sort)[0],$c[1])[$_-eq$c[0]])};$b

```

Try it online!

I'm pretty confident it can be shortened, I will continue to look at it

# Answer
> 4 votes
## C, 85 bytes

```
i,j,m;f(d,o,n)int*d,*o;{for(i=n;i--;)for(m=d[!i],j=n;j;o[i]=m=--j^i&&d[j]<m?d[j]:m);}

```

First argument is the input integer array. The second argument is the output integer array. The third argument is the element count for both arrays.

See it work online.

# Answer
> 3 votes
## Clojure, ~~36~~ ~~81~~ ~~62~~ 71 bytes

Newest (shouldn't really submit these in a hurry):

```
#(for[c[(zipmap(range)%)]i(sort(keys c))](apply min(vals(dissoc c i))))

```

Try it online.

Aaaand this one has a bug (62 bytes), zipmap produces an unordered map so this won't produce the correct sequence on larger inputs.

```
#(for[c[(zipmap(range)%)][i v]c](apply min(vals(dissoc c i))))

```

`v` is not actually used for anything but this is shorter than `i (keys c)`.

Previous at 81 bytes:

Try it online.

```
#(let[r(range(count %))](for[i r](apply min(for[j r :when(not= i j)](nth % j)))))

```

Try it online.

Oh damn the original (36 bytes) does not work when the minimum number is repeated, `[4 2 2 5]` results in `[2 4 4 2]` as both `2`s are removed :(

```
#(for[i %](apply min(remove #{i}%)))

```

`#{i}` is the set which contains only `i`, it returns truthy for `i` and falsy for others, meaning that the minimum is calculated from all other numbers within the input list.

Try it online.

# Answer
> 3 votes
# Perl 6,  ~~26 24~~  19 bytes

## 26

```
{.map: (.Bag∖*).min.key}

```

Note that is  U+2216 not `\` U+5C

Try it

```
{.map: (.Bag⊖*).min.key}

```

Try it

## 24

```
{(.min X%$_)X||.sort[1]}

```

Try it

## 19

```
{.sort[.min X==$_]}

```

Try it

---

## 26

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

  .map:     # for each of the values in the input (implicit method call on ｢$_｣)
  (
    .Bag    # turn the block's input into a Bag
    ∖       # set-difference           ｢∖｣ U+2216 aka ｢(-)｣
    # ⊖     # symmetric-set-difference ｢⊖｣ U+2296 aka ｢(^)｣
    *       # turn expression into a WhateverCode lambda (this is the parameter)
  ).min.key # get the minimum pair from the Bag, and return its key
}

```

I used the "fancy" unicode operators rather than the ascii equivalents because they would have required a space before them so that they wouldn't be parsed as part of the `.Bag` method call.

## 24

```
{
  (.min X% $_) # the minimum cross modulus-ed with the input
  X||          # cross or-ed
  .sort[1]     # with the second minimum
}

```

## 19

```
{
  .sort\        # sort the values
  [             # index into that
    .min X== $_ # the minimum cross compared with the input
  ]
}

```

---

(The 24 and 19 byte golfs were inspired by a Jelly implementation)

# Answer
> 3 votes
# Pyth, ~~8~~ 7 bytes

```
mh.-SQ]

```

*-1 Byte thanks to @isaacg*

Try it!

# Answer
> 3 votes
# Factor, 38 bytes

```
[ all-rotations [ rest infimum ] map ]

```

Try it online!

Get all the rotations of the input, then get the smallest element in each rotation minus the first element. Like this:

\\$\begin{matrix} 4 & 3 & 2 & 5 \\ \end{matrix} \rightarrow\\$

\\$\require{enclose}\begin{matrix}\enclose{horizontalstrike}{4} & 3 & \color{red}{2} & 5 \\ \enclose{horizontalstrike}{3} & \color{red}{2} & 5 & 4 \\ \enclose{horizontalstrike}{2} & 5 & 4 & \color{red}{3} \\ \enclose{horizontalstrike}{5} & 4 & 3 & \color{red}{2} \\ \end{matrix} \rightarrow\\$

\\$\begin{matrix} 2 & 2 & 3 & 2 \\ \end{matrix}\\$

# Answer
> 3 votes
# , 7 bytes

```
1<./\.]

```

Attempt This Online!

J's outfix adverb `\.` is made for this. It applies a verb (in this case min) to every outfix of a list of a specified size (in this case 1). Outfix being the inverse operation of "window" functions which exist in most languages -- a list composed of the original list without a window as that window moves across the list.

# Answer
> 2 votes
# PHP, 72 Bytes

```
<?$k=$g=$_GET;sort($k);foreach($g as&$v)$v=$k[$v==$k[0]?:0];print_r($g);

```

Online Version

# Answer
> 2 votes
# PHP, 47 bytes

```
while(++$i<$argc)echo@min([z,$i=>z]+$argv),' ';

```

# Answer
> 2 votes
# Scala, 37 bytes

```
l.indices map(i=>l diff Seq(l(i))min)

```

`l` is any collection of Int.

Test cases:

```
scala> val l = List(4,3,2,5)
l: List[Int] = List(4, 3, 2, 5)

scala> l.indices map(i=>l diff Seq(l(i))min)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 2, 3, 2)

scala> val l = List(4,2,2,5)
l: List[Int] = List(4, 2, 2, 5)

scala> l.indices map(i=>l diff Seq(l(i))min)
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 2, 2, 2)

scala> val l = List(6,3,5,5,8)
l: List[Int] = List(6, 3, 5, 5, 8)

scala> l.indices map(i=>l diff Seq(l(i))min)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 3, 3, 3)

scala> val l = List(7,1)
l: List[Int] = List(7, 1)

scala> l.indices map(i=>l diff Seq(l(i))min)
res3: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 7)

scala> val l = List(9,9)
l: List[Int] = List(9, 9)

scala> l.indices map(i=>l diff Seq(l(i))min)
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(9, 9)

scala> val l = List(9,8,9)
l: List[Int] = List(9, 8, 9)

scala> l.indices map(i=>l diff Seq(l(i))min)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(8, 9, 8)

```

This can probably still be golfed, I couldn't find a shorter way to remove an element from a list than `l diff Seq(l(i))`

# Answer
> 2 votes
# C#, 36 Bytes

```
i.Select((x,a)=>i.Where((y,b)=>b!=a).Min())

```

Takes the elements (i) and looks in the elements without the current item for the minimal value.

It's kind of sad, that some other attempts don't work, as we work with primitive types, and therefore don't have lists with references to compare the items from.

# Answer
> 2 votes
# 05AB1E, 5 bytes

```
{sWQè

```

Port of *@xnor*'s Python 2 answer.

Try it online or verify all test cases.

**Explanation:**

```
{        # Sort the (implicit) input-list
         #  i.e. [4,1,3,6] → [1,3,4,6]
 s       # Swap, so the (implicit) input-list is at the top of the stack again
  W      # Get the minimum without popping from the list
         #  i.e. [4,1,3,6] → 1
   Q     # Check for each element if they are equal to this value (1/0 as truthy/falsey)
         #  i.e. [4,1,3,6] and 1 → [0,1,0,0]
    è    # Use these 0s and 1s to index in the sorted list
         #  i.e. [1,3,4,6] and [0,1,0,0] → [1,3,1,1]

```

# Answer
> 2 votes
# APL (Dyalog Extended), 7 bytes

Port of xnor's Python 2 answer. Requires `⎕IO←0`:

```
∧⊇⍨⊢=⌊/

```

Try it online!

Explanation:

```
∧⊇⍨⊢=⌊/  ⍝ Monadic function train
      ⌊/  ⍝ The minimum element of the input
    ⊢=    ⍝ Element-wise compare the input to the above
          ⍝ Results in a boolean vector, let's call it "X"
∧         ⍝ Sort the input
 ⊇⍨      ⍝ Index into sorted input by X

```

# Answer
> 2 votes
# PowerShell, ~~49~~ 38 bytes

<sup>-11 bytes thanks to mazzy</sup>

```
($a=$args)|%{($c=$a|sort)[$_-eq$c[0]]}

```

Try it online!

Improvement of Sinusoid's lovely answer. Saves 10 bytes by using explicit output instead of building an array. Indexes into the sorted array to either spot 0 (i.e. smallest value) or spot 1 if the conditional is true.

# Answer
> 2 votes
# Husk, 6 bytes

```
mo▼`-¹

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), 12 bytes

```
{(&/x_)'!#x}

```

Try it online!

Uses `list _ int` to remove individual values from the input, then takes the minimum of the remaining values.

# Answer
> 2 votes
# Vyxal, 5 bytes

```
s∇g=İ

```

Try it Online!

## How?

```
s∇g=İ
s      # Sort the input
 ∇     # Push this two values down so that there are two copies of the input on top
  g    # Get the minimum of the input
   =   # For each in the input, is it equal to that?
    İ  # Index this into the sorted list

```

# Answer
> 2 votes
# Arturo, 28 bytes

```
$[a][map a=>[min a--.once&]]

```

Try it

```
$[a][             ; a function taking an argument a
    map a=>[      ; map over each element in a
        min       ; the minimum element of
        a--.once& ; a with the current element removed (only once)
    ]             ; end map
]                 ; end function

```

# Answer
> 2 votes
# Japt, 8 bytes

```
£éYn)Årm

```

Try it

Try all test cases

Explanation:

```
£        # For each index Y in the input, copy the input then:
 é  )    #  Rotate right by
  Yn     #   Negative Y
     Å   #  Remove the first item
      rm #  Get the minimum of the rest
         # Implicitly return an array of the results

```

# Answer
> 2 votes
# Desmos, 26 bytes

```
f(x)=x.sort[1+0^{x-x.min}]

```

Try it on Desmos!

Port of this answer.

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

```
sub{@x=sort{$a<=>$b}@_;map$x[$_==$x[0]],@_}

```

Equivalent to the Python solution. Perl's `sort` unfortunately has the wrong default for numbers (requiring an explicit comparator), and `min` isn't built-in, but it almost makes up for it by `sub` being shorter than `lambda`, `map$_,` being shorter than `x for x in`, and the implicitness of return and args lists.

# Answer
> 1 votes
## CJam, 15 bytes

```
{:S{S:e<=S$=}%}

```

Essentially a translation of xnor's algorithm into CJam.

This is an unnamed block that takes an array from the stack and leaves the result on the stack.

Explanation:

```
{
  :S     e# Save in S
  {      e# For X in S:
    S:e< e#   Push Min(S)
    =    e#   X == Min(S)
    S$=  e#   Sorted(S)[top of stack]
  }%     e# End
}

```

# Answer
> 1 votes
# Ruby, 30 bytes

For each element, sort the array, remove the current element and grab the first element of the remaining array.

```
->a{a.map{|e|(a.sort-[e])[0]}}

```

It's an anonymous function that can be used like this:

```
f = ->a{a.map{|e|(a.sort-[e])[0]}}
p f[[6, 3, 5, 5, 8]] # => [3, 5, 3, 3, 3]

```

# Answer
> 1 votes
# Java 8, 119 bytes

```
a->{int t[]=a.clone(),m=a[0],i=a.length;for(int x:a)m=x<m?x:m;for(java.util.Arrays.sort(t);i-->0;)a[i]=t[a[i]==m?1:0];}

```

Port of *@xnor*'s Python 2 answer.

Modifies the input-array instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
a->{                  // Method with integer-array parameter and no return-type
  int t[]=a.clone(),  //  Make a copy of the input-array
      m=a[0],         //  Minimum `m`, starting at the first value of the input-array
      i=a.length;     //  Index-integer, starting at the length of the input-array
  for(int x:a)        //  Loop over the input-array
    m=x<m?            //   If the current item is smaller than the current `m`
       x              //    Replace `m` with this value
      :               //   Else:
       m;             //    Leave `m` the same
  for(java.util.Arrays.sort(t);
                      //  Sort the copy we've made of the input-array
      i-->0;)         //  Loop `i` in the range (length, 0]
    a[i]=             //   Modify the item at index `i` of the input-array to:
      t[              //    The item in the sorted array at index:
        a[i]==m?      //     If the current item and the minimum are equal:
         1            //      Use index 1 in the sorted array
        :             //     Else:
         0];}         //      Use index 0 in the sorted array

```

# Answer
> 1 votes
# Haskell, 76 bytes

This is considerably longer than the earlier Haskell entries, but it's the first that only performs a linear number of comparisons and a linear amount of additional work.

```
f(x:y)|(z,w)<-x!y=z:w
a![x]=(x,[a])
a!(x:y)|(p,q)<-a#x!y=(x#p,a#p:q)
(#)=min

```

Try it online!

## Explanation

`!` takes two arguments: a running minimum and a nonempty list. It returns the minimum value in the list and the result of processing the given list using the running minimum.

# Answer
> 1 votes
# MathGolf, ~~9~~ 7 bytes

```
s_╓?m=§

```

Try it online!

## Explanation

Basically a port of Kevin Cruijssen's 05AB1E answer, but I lose 2 bytes thanks to having to do things explicitly.

```
s         sort(array)
 _        duplicate TOS
  ╓       minimum of two elements, min of list, minimum by filter
   ?      rot3 pops input on top of stack again
    m=    explicit map to check equality
      §   get from sorted array for each

```

# Answer
> 1 votes
# APL(NARS), 47 chars, 94 bytes

```
{m←⌊/⍵⋄⍵{⍵>≢⍺:⍬⋄t←⍺∇⍵+1⋄m=⍵⊃⍺:(⌊/⍺∼⍦m),t⋄m,t}1}

```

∼⍦ it seems is using for remove one element only 1 times; possible it is too much long for you... test:

```
  f←{m←⌊/⍵⋄⍵{⍵>≢⍺:⍬⋄t←⍺∇⍵+1⋄m=⍵⊃⍺:(⌊/⍺∼⍦m),t⋄m,t}1}
  f 4 3 2 5
2 2 3 2
  f 4 2 2 5
2 2 2 2
  f 6 3 5 5 8
3 5 3 3 3
  f 7 1
1 7
  f 9 9
9 9
  f 8 9 8
8 8 8
  f 9 8 9
8 9 8

```

# Answer
> 1 votes
# Nekomata, 3 bytes

```
ĕ^ṁ

```

Attempt This Online!

```
ĕ^ṁ
ĕ       Extract one item from the list
            For example, there are 4 possible extractions from [4,3,2,5]: 4 [3,2,5], 3 [4,2,5], 2 [4,3,5], 5 [4,3,2]
 ^      Drop the extracted item
            The above example becomes [3,2,5], [4,2,5], [4,3,5], [4,3,2]
  ṁ     Take the minimum of the remaining list
            The above example becomes 2, 2, 3, 2
        All possible solutions are returned

```

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


title: Sort by Multiplying

text:
# Question
Title: Sort by Multiplying
You should write a program or function that given a list of positive integers multiplies each element with the smallest positive integer possible to create a strictly increasing list.

For example if the input is

```
5 4 12 1 3

```

the multiplications will be

```
5*1=5 4*2=8 12*1=12 1*13=13 3*5=15

```

and the output will be the increasing list

```
5 8 12 13 15

```

## Input

* A list of positive integers containing at least 1 element

## Output

* A list of positive integers

## Examples

```
9 => 9
1 2 => 1 2
2 1 => 2 3
7 3 => 7 9
1 1 1 1 => 1 2 3 4
5 4 12 1 3 => 5 8 12 13 15
3 3 3 8 16 => 3 6 9 16 32
6 5 4 3 2 1 => 6 10 12 15 16 17
9 4 6 6 5 78 12 88 => 9 12 18 24 25 78 84 88
8 9 41 5 12 3 5 6 => 8 9 41 45 48 51 55 60
15 8 12 47 22 15 4 66 72 15 3 4 => 15 16 24 47 66 75 76 132 144 150 153 156

```

This is code golf so the shortest program or function wins.

*Fun fact: the last element of the output for the input `N, N-1, ... ,1` seems to be the `(N+1)th` element of the sequence A007952. If you find a proof, you are welcomed to include it in your golf answer or post it as a comment.*

# Answer
> 20 votes
## Jelly, ~~6~~ 5 bytes

```
:‘×µ\

```

First Jelly answer ~~before @Dennis wakes up and beats me.~~ Try it online!

### Explanation

```
:          Integer division, m//n
 ‘         Increment, (m//n+1)
  ×        Multiply, (m//n+1)*n
   µ       Turn the previous links into a new monadic chain
    \      Accumulate on the array

```

Thanks to @Dennis for -1 byte.

# Answer
> 10 votes
# JavaScript (ES6), 28

**Edit** As suggested by @Patrick Roberts, `p` can be a uninitialized parameter. Same byte count but avoid using a global variable

```
(a,p)=>a.map(n=>p=n*-~(p/n))

```

**TEST**

```
f=(a,p)=>a.map(n=>p=n*-~(p/n))

console.log=x=>O.textContent+=x+'\n'

;[
[[9], [ 9]],
[[1, 2], [ 1, 2]],
[[2, 1], [ 2, 3]],
[[7, 3], [ 7, 9]],
[[1, 1, 1, 1], [ 1, 2, 3, 4]],
[[5, 4, 12, 1, 3], [ 5, 8, 12, 13, 15]],
[[3, 3, 3, 8, 16], [ 3, 6, 9, 16, 32]],
[[6, 5, 4, 3, 2, 1], [ 6, 10, 12, 15, 16, 17]],
[[9, 4, 6, 6, 5, 78, 12, 88], [ 9, 12, 18, 24, 25, 78, 84, 88]],
[[8, 9, 41, 5, 12, 3, 5, 6], [ 8, 9, 41, 45, 48, 51, 55, 60]],
[[15, 8, 12, 47, 22, 15, 4, 66, 72, 15, 3, 4], [ 15, 16, 24, 47, 66, 75, 76, 132, 144, 150, 153, 156]]
].forEach(t=>{
  var i=t[0],k=t[1],r=f(i),ok=(k+'')==(r+'')
  console.log(i + ' => ' + r + (ok?' OK':'FAIL expecting '+x))
})
```

```
<pre id=O></pre>
```

# Answer
> 7 votes
# Python 2, 67 64 bytes

First try at code-golfing, so tips are appreciated.

```
def m(l):
 for x in range(1,len(l)):l[x]*=l[x-1]/l[x]+1
 print l

```

# Answer
> 6 votes
# PHP, ~~55~~ ~~46~~ ~~42~~ 41 bytes

Uses ISO 8859-1 encoding.

```
for(;$a=$argv[++$i];)echo$l+=$a-$l%$a,~ß;

```

Run like this (`-d` added for aesthetics only):

```
php -d error_reporting=30709 -r 'for(;$a=$argv[++$i];)echo$l+=$a-$l%$a,~ß;' 10 10 8

```
* Saved 1 byte thx to Ismael Miguel.
* Saved 8 bytes by using modulo instead of floor
* Saved 4 bytes thx to Ismael Miguel (for instead of foreach)
* Saved a byte by using  to yield a space.

# Answer
> 5 votes
# Haskell (~~30~~ ~~28~~ 25 bytes)

```
scanl1(\x y->y*div x y+y)

```

### Expanded version

```
f :: Integral n => [n] -> [n]
f xs = scanl1 increaseOnDemand xs
 where
   increaseOnDemand :: Integral n => n -> n -> n
   increaseOnDemand acc next = next * (1 + acc `div` next)

```

### Explanation

`scanl1` enables you to fold a list and accumulate all intermediate values into another list. It's a specialization of `scanl`, which has the following type:

```
scanl  :: (acc  -> elem -> acc)  -> acc -> [elem] -> [acc]
scanl1 :: (elem -> elem -> elem) ->        [elem] -> [elem]

scanl1 f (x:xs) = scanl f x xs

```

Therefore, all we need is a suitable function that takes two the last element of our list (`acc` in the expanded version) and the one we wish to process (`next` in the expanded version) and return a suitable number.

We can easily derive this number by dividing the accumulator through the next one and flooring the result. `div` takes care of that. Afterwards, we simply have to add `1` to ensure that the list is actually increasing (and that we don't end up with `0`).

# Answer
> 5 votes
# C++, ~~63~~ ~~60~~ 57 bytes

```
void s(int*f,int*e){for(int c=*f;++f!=e;c=*f+=c/ *f**f);}

```

Works inplace given a range `[first, last)`. Originally written as template variant, but that was longer:

```
template<class T>void s(T f,T e){for(auto c=*f;++f!=e;c=*f+=c/ *f**f);}

```

### Extended version

```
template <class ForwardIterator>
void sort(ForwardIterator first, ForwardIterator last){
    auto previous = *first;

    for(++first; first != last; ++first){
        auto & current = *first;
        current += current * (current / previous);
        previous = current;
    }
}

```

# Answer
> 4 votes
## Mathematica, ~~36~~ 32 bytes

```
 #2(Floor[#1/#2]+1)&~FoldList~#&

```

## Test

```
#2(Floor[#1/#2]+1)&~FoldList~#& /@ {{5, 4, 12, 1, 3},
   {15, 8, 12, 47, 22, 15, 4, 66, 72, 15, 3, 4}}
(* {{5, 8, 12, 13, 15}, {15, 16, 24, 47, 66, 75, 76, 132, 144,
  150, 153, 156}} *)

```

# Answer
> 4 votes
# Brachylog, 12 bytes

```
{≤.;?%0∧}ᵐ<₁

```

Weird enough trying to multiply each variable by a number will start at trying to multiply by 2 and not 0 or 1. This seems to work though and beats both other Brachylog implementations

# Explanation

```
{       }ᵐ          --  Map each number
 ≤.                 --      to a number greater or equal to the original
  .;?%0             --      and a multiple of the original
       ∧            --      no more constraints
          <₁        --  so that the list is strictly increasing

```

Try it online!

# Answer
> 3 votes
## CJam, 13 bytes

```
q~{\_p1$/)*}*

```

Input as a CJam-style list. Output is linefeed separated.

Test it here.

### Explanation

```
q~    e# Read and evaluate input.
{     e# Fold this block over the list (i.e. "foreach except first")...
  \   e#   Swap with previous value.
  _p  e#   Duplicate and print previous value.
  1$  e#   Copy current value.
  /   e#   Integer division.
  )*  e#   Increment and multiply current value by the result.
}*

```

The final value is left on the stack and printed automatically at the end.

# Answer
> 3 votes
## Python (3.5), ~~63~~ 62 bytes

```
def f(a):
 r=[0]
 for i in a:r+=i*(r[-1]//i+1),
 return r[1:]

```

## Test

```
>>> print('\n'.join([str(i)+' => '+str(f(i)) for i in [[9],[1,2],[2,1],[7,3],[1,1,1,1],[5,4,12,1,3],[3,3,3,8,16],[6,5,4,3,2,1],[9,4,6,6,5,78,12,88],[8,9,41,5,12,3,5,6],[15,8,12,47,22,15,4,66,72,15,3,4]]]))
[9] => [9]
[1, 2] => [1, 2]
[2, 1] => [2, 3]
[7, 3] => [7, 9]
[1, 1, 1, 1] => [1, 2, 3, 4]
[5, 4, 12, 1, 3] => [5, 8, 12, 13, 15]
[3, 3, 3, 8, 16] => [3, 6, 9, 16, 32]
[6, 5, 4, 3, 2, 1] => [6, 10, 12, 15, 16, 17]
[9, 4, 6, 6, 5, 78, 12, 88] => [9, 12, 18, 24, 25, 78, 84, 88]
[8, 9, 41, 5, 12, 3, 5, 6] => [8, 9, 41, 45, 48, 51, 55, 60]
[15, 8, 12, 47, 22, 15, 4, 66, 72, 15, 3, 4] => [15, 16, 24, 47, 66, 75, 76, 132, 144, 150, 153, 156]

```

## Previous solution

some recursive solutions but larger

```
(68 bytes) f=lambda a,i=0:[i,*f(a[1:],a[0]*(i//a[0]+1))][i==0:]if a!=[]else[i]
(64 bytes) f=lambda a,i=0:a>[]and[i,*f(a[1:],a[0]*(i//a[0]+1))][i<1:]or[i]

```

# Answer
> 3 votes
## Perl, 17 + 3 = 20 bytes

```
$p=$_*=$==1+$p/$_

```

Requires `-p` and `-l` flags:

```
$ perl -ple'$p=$_*=$==1+$p/$_' <<< $'15\n8\n12\n47\n22\n15\n4\n66\n72\n15\n3\n4'
15
16
24
47
66
75
76
132
144
150
153
156

```

Explanation:

```
# '-p' reads each line into $_ and auto print
# '-l' chomp off newline on input and also inserts a new line when printing
# When assigning a number to `$=` it will automatic be truncated to an integer
# * Added newlines for each assignment
$p=
  $_*=
    $==
      1+$p/$_

```

# Answer
> 3 votes
# C (gcc), 37 bytes

```
o(int*_){for(;*++_;)*_*=_[~0]/ *_+1;}

```

Try it online!

# Answer
> 3 votes
# TI-Basic, ~~43~~ ~~40~~ 37 bytes

```
Prompt A
For(I,1,dim(ʟA
ʟA(I)(1+int(Ans/ʟA(I→ʟA(I
End
ʟA

```

-6 bytes thanks to MarcMush.

# Answer
> 2 votes
# Brachylog, 54 bytes

```
:_{h_.|[L:T],LhH,(T_,IH;0:$Ie*H=:T>I),Lb:I:1&:[I]rc.}.

```

### Explanation

```
:_{...}.                § Call sub-predicate 1 with [Input, []] as input. Unify its output
                        § with the output of the main predicate

§ Sub-predicate 1

h_.                     § If the first element of the input is an empty list, unify the
                        § output with the empty list
|                       § Else
[L:T],LhH,              § Input = [L,T], first element of L is H
    (T_,IH              §     If T is the empty list, I = H
    ;                   §     Else
    0:$Ie*H=:T>I),      §     Enumerate integers between 0 and +inf, stop and unify the
                        §     enumerated integer with I only if I*H > T
Lb:I:1&                 § Call sub-predicate 1 with input [L minus its first element, I]
:[I]rc.                 § Unify the output of the sub-predicate with
                        § [I|Output of the recursive call]

```

# Answer
> 2 votes
# Pyth, 11

```
t.u*Yh/NYQ0

```

Test Suite

Does a cumulative reduce, a reduce that returns all intermediate values, starting with `0`. Since the input is guaranteed to contain only positive integers, this is ok. In each step, we take the old value, divide it by the new value and add `1`, then we multiply by the new value.

# Answer
> 2 votes
# C, 79 bytes

```
p;main(x,v)char**v;{for(;*++v;printf("%d ",p=((x+p-1)/x+!(p%x))*x))x=atoi(*v);}

```

## Ungolfed

```
p; /* previous value */

main(x,v) char**v;
{
    /* While arguments, print out x such that x[i] > x[i-1] */
    for(;*++v; printf("%d ", p = ((x+p-1)/x + !(p%x)) * x))
        x = atoi(*v);
}

```

# Answer
> 2 votes
## PowerShell, 26 bytes

```
$args[0]|%{($l+=$_-$l%$_)}

```

Takes input as an explicit array, e.g., `> .\sort-by-multiplying.ps1 @(6,5,4,3,2,1)` via `$args[0]`.

We then for-loop over that with `|%{...}` and each iteration perform *magic*. Nah, just kidding, we use the same modulo trick as other answers (props to @aross because I spotted it there first).

The encapsulating parens `(...)` ensure that the result of the math operation is placed on the pipeline, and thus output. If we left those off, nothing would be output since the `$l` variable is garbage-collected after execution finishes.

### Example

```
PS C:\Tools\Scripts\golfing> .\sort-by-multiplying.ps1 @(8,9,1,5,4)
8
9
10
15
16

```

# Answer
> 2 votes
# Julia 1.0, 27 bytes

```
!L=(x=0;L.|>i->x=(x÷i+1)i)

```

Try it online!

# Answer
> 2 votes
# Rust, 59 bytes

```
|mut l:Vec<u8>|{for i in 1..l.len(){l[i]*=l[i-1]/l[i]+1};l}

```

Try it online!

I am still learning rust, but I am sure there is a better solution using `iter()`. Also I am using `u8` because the examples don't have output value greater than 512.

# Answer
> 2 votes
# Factor, 35 bytes

```
[ 0 [ tuck /i 1 + * ] accumulate* ]

```

Attempt This Online!

# Answer
> 2 votes
# PARI/GP, 25 bytes

```
a->i=0;[i=c*(i\c+1)|c<-a]
```

Attempt This Online!

# Answer
> 2 votes
# Desmos, 78 bytes

```
n->min(n,i.length)+1,o->join(o,i[n]floor(o[n-1]/i[n]+1))
i=\ans_0
n=2
o=[i[1]]

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# Uiua, 9 bytes

```
\(×+1⌊÷,)

```

Try it!

```
\(×+1⌊÷,)
\(      )  # scan by
       ,   # over
      ÷    # divide
     ⌊     # floor
   +1      # increment
  ×        # multiply

```

# Answer
> 2 votes
# Uiua, 8 bytes

```
\(-⊃◿+∶)

```

Try it online!

Given the previous value `x` and the next value `y`, the transformed `y` is the same as `(x+y) - (x+y)%y == (x+y) - x%y`.

```
\(-⊃◿+∶)    input: a vector of positive integers
\(      )    scan by: (input: [x y])
       :       swap [y x]
   ⊃◿+        fork (mod, add) [x%y x+y]
  -            subtract [x+y-x%y]

```

# Answer
> 1 votes
# 05AB1E, 11 bytes

Code:

```
R`[=sŽDŠ/ò*

```

Try it online!

Explanation:

```
R            # Reverse input
 `           # Flatten the list
  [          # While loop
   =         # Print the last item
    s        # Swap the last two items
     Ž       # If the stack is empty, break
      D      # Duplicate top of the stack
       Š     # Pop a,b,c and push c,a,b
        /    # Divide a / b
         ò   # Inclusive round up
          *  # Multiply the last two items

```

Uses CP-1252 encoding.

# Answer
> 1 votes
# Japt, 11 bytes

```
Uå@Y*-~(X/Y

```

Test it online!

### How it works

```
          // Implicit: U = input array of integers
Uå@       // Cumulative reduce: map each previous value X and current value Y to:
-~(X/Y    //  floor(X/Y+1).
          // Implicit: output last expression

```

# Answer
> 1 votes
## Minkolang 0.15, 17 bytes

```
nd1+?.z0c:1+*d$zN

```

Try it here!

### Explanation

```
nd                   Take number from input and duplicate it
  1+                 Add 1
    ?.               Stop if top of stack is 0 (i.e., when n => -1 because input is empty).
      z              Push value from register
       0c            Copy first item on stack
         :           Pop b,a and push a//b
          1+         Add 1
            *        Multiply
             d$z     Duplicate and store in register
                N    Output as number

```

Essentially, the register keeps the latest member of the ascending list and this is divided by the input and incremented to get the multiplier for the next member. The toroidal feature of Minkolang's code field means that it loops horizontally without the need for `()` or `[]` loops.

# Answer
> 1 votes
# Brachylog, 21 bytes

```
l~lCℕ₁ᵐ≤ᵛ~+?&;Cz≜×ᵐ<₁

```

Try it online!

Uses the sum of input values as the upper bound for coefficients C. Pretty slow, times out on TIO for input list lengths beyond 5 or 6 (also depending on the sum of the values). But not as slow as my original version, which requires tiny lists of upto 3 elements, with tiny values, to not time out:

### 21 bytes

```
l~l.&+^₂⟦₁⊇.;?z/ᵐℕ₁ᵐ∧

```

Try it online!

# Answer
> 1 votes
# Python 2, 53 bytes

```
lambda a:reduce(lambda b,v:b+[b[-1]/v*v+v],a,[0])[1:]

```

Try it online!

`k*x>y` implies `k>y/x`; so the smallest `k` can be is `k=floor(y/x)+1`. Since in Python 2.7, integer division is already taken as `floor`, we want `k=y/x+1`, and `k*x = (y/x+1)*x = y/x*x+x`.

# Answer
> 1 votes
# K (oK), 11 bytes

```
{y*1+_x%y}\

```

Try it online!

# Answer
> 1 votes
# , 21 bytes

```
(],[*1+{:@]<.@%[)/@|.

```

Try it online!

# Answer
> 1 votes
# x86-64 machine code, 13 bytes

```
99 F7 3E F7 2E 01 06 AD FF CF 75 F4 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of an array of 32-bit integers in RDI and its address in RSI. The starting point is after the first 7 bytes.

In assembly:

```
                            # Here, EAX holds the modified previous number.
r:  cdq                     # Sign-extend it, preparing for the next instruction.
    idiv DWORD PTR [rsi]    # Divide by the current number, putting the quotient in EAX
                            #  and the remainder in EDX.
    imul DWORD PTR [rsi]    # Multiply the quotient by the current number; the net effect
                            #  is to round EAX down to a multiple of the current number.
    add [rsi], eax          # Add EAX to the current number, producing the first multiple
                            #  greater than the modified previous number.
f:  lodsd       # (Start here.) Load the current number into EAX, advancing the pointer.
    dec edi     # Count down from the length.
    jnz r       # Jump if it hasn't reached 0.
    ret         # Return.

```

# Answer
> 1 votes
# Vyxal, 5 bytes

```
≬ḭ›*r

```

Try it Online!

Port of Jelly answer.

## How?

```
≬ḭ›*r
≬     # Next three elements as a lambda:
 ḭ    # Floor divide: a/b
  ›   # Increment: a/b+1
   *  # Multiply: (a/b+1)*b
    r # Cumulative reduce the (implicit) input by this lambda

```

# Answer
> 1 votes
# MathGolf, 7 bytes

```
æ`/)*]ç

```

Try it online.

**Explanation:**

```
æ        # Loop over the (implicit) input-list,
         # using 4 characters as inner code-block:
         #  (implicitly push the current value)
 `       #  Duplicate the top two values
         #  (which will push a 0 as first item in the first iteration)
  /      #  Integer-divide those two duplicated values
   )     #  Increase it by 1
    *    #  Multiply the top two values together
     ]   # After the loop: wrap all values on the stack into a list
      ç  # Remove the leading 0 with a falsey filter
         # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Oracle SQL 11.2, 210 bytes

```
WITH v AS(SELECT TO_NUMBER(COLUMN_VALUE)a,rownum i FROM XMLTABLE(('"'||REPLACE(:1,' ','","')||'"'))),c(p,n)AS(SELECT a,2 FROM v WHERE i=1UNION ALL SELECT a*CEIL((p+.1)/a),n+1 FROM c,v WHERE i=n)SELECT p FROM c;

```

Un-golfed

```
WITH v AS
(
  SELECT TO_NUMBER(COLUMN_VALUE)a, rownum i            -- Convert the input string into rows
  FROM   XMLTABLE(('"'||REPLACE(:1,' ','","')||'"'))   -- using space as the separator between elements
)
, c(p,n) AS
(
  SELECT a, 2 FROM v WHERE i=1                         -- Initialize the recursive view
  UNION ALL
  SELECT a*CEIL((p+.1)/a),n+1 FROM c,v WHERE i=n       -- Compute the value for the nth element
)
SELECT p FROM c;

```

# Answer
> 0 votes
# Chez Scheme (140 Bytes)

Golfed Version:

```
(define(f l)(define(g l p m)(cond((null? l)l)((<(*(car l)m)(+ p 1))(g l p(+ m 1)))(else(cons(*(car l)m)(g(cdr l)(* m(car l))1)))))(g l 0 1))

```

Ungolfed Version:

```
(define(f l)
  (define(g l p m)
    (cond
      ((null? l) l)
      ((< (* (car l) m) (+ p 1)) (g l p (+ m 1)))
      (else (cons (* (car l) m) (g (cdr l) (* m (car l)) 1)))
    )
  )
  (g l 0 1)
)

```

Try it Online!

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


title: Get the best of two Arrays

text:
# Question
Title: Get the best of two Arrays
You will be given two arrays of floating-point numbers. Your task is to pair the corresponding elements of the two arrays, and get the maximum of each pair. *However*, if the two corresponding elements are equal, you must take their sum instead.

For example, given the lists `[1, 3, 3.2, 2.3]` and `[3, 1, 3.2, 2.6]`, you must do the following:

* Pair the elements (or zip): `[[1, 3], [3, 1], [3.2, 3.2], [2.3, 2.6]]`.
* Go through each pair and apply the process above: `[3, 3, 6.4, 2.6]`.

---

## Specs

* The arrays / lists will always have equal length. They may however be empty.
* The numbers they contain will always fit your language's capabilities, as long as you do not abuse that. They may be positive, zero or negative, you must handle all types.
* If it helps you reduce your byte count, you *may* also take the length of the lists as input.

## Rules

---

# Test Cases

```
Array_1, Array_2 -> Output

[], [] -> []
[1, 2, 3], [1, 3, 2] -> [2, 3, 3]
[1, 3, 3.2, 2.3], [3, 1, 3.2, 2.6] -> [3, 3, 6.4, 2.6]
[1,2,3,4,5,5,7,8,9,10], [10,9,8,7,6,5,4,3,2,1] -> [10, 9, 8, 7, 6, 10, 7, 8, 9, 10]
[-3.2, -3.2, -2.4, 7, -10.1], [100, -3.2, 2.4, -7, -10.1] -> [100, -6.4, 2.4, 7, -20.2]

```

# Answer
# Jelly, 4 bytes

```
=‘×»

```

Try it online!

This uses the exact same approach as my APL answer, except Jelly has a builtin for adding one to a number!
> 9 votes

# Answer
# Python 2, 45 bytes

A mix of my initial solution and @ovs'.

```
lambda*a:map(lambda x,y:max(x,y)*-~(x==y),*a)

```

Try it online!

# Python 2, 49 bytes

```
lambda x,y:[max(a,b)*-~(a==b)for a,b in zip(x,y)]

```

Try it online!

# Python 2, 46 bytes

@ovs suggested this method to save 3 bytes.

```
lambda*x:[max(a,b)*-~(a==b)for a,b in zip(*x)]

```

Try it online!

---

# How?

First off, we pair the corresponding elements, by using either `*` or `zip()`. That allows us to do our further golfing by working either with a map or a list comprehension.

The cool trick in this answer is this part: `max(x,y)*-~(x==y)`. **How does that work?** \- Well, as most of you already know, Python auto-converts bool values to integers when they are used in arithmetic operations. Hence, `(x==y)` gets evaluated as `1`, if the condition is met. However, if the two values are not equal, it returns `0` instead. Then, the bitwise operation `-~` increments the value returned from the bool by `1`, giving us either `2` or `1`. `max(a,b)` gives the maximum value of the pair and `*` multiplies it by the value returned above (so it gets multiplied by `2` only if they are equal, in which case `max()` returns the value of both).

This is based on the fact that the sum of two equal numbers is in fact either of them doubled, and kind of "abuses" Python's bool class being a subclass of int.
> 13 votes

# Answer
# Python 3, ~~48~~ ~~46~~ 44 bytes

*-2 bytes thanks to @nwellnhof*

```
lambda*a:map(lambda*x:max(x)*2/len({*x}),*a)

```

Try it online!
> 11 votes

# Answer
# Kotlin, ~~78~~ ~~75~~ ~~71~~ ~~66~~ ~~65~~ 59 bytes

It's my first attempt, be cool :D

```
a.zip(b).map{(a,b)->when{b>a->b;a>b->a;else->a*2}}.toList()

```

**TIO doesn't work with this solution (and i don't know why), source code for testing below**

```
fun main(args: Array<String>) {
    bestOfTwo(floatArrayOf(), floatArrayOf()).print()
    bestOfTwo(floatArrayOf(0F), floatArrayOf(0F)).print()
    bestOfTwo(floatArrayOf(1F,2F,3F), floatArrayOf(1F,3F,2F)).print()
    bestOfTwo(floatArrayOf(1F,3F,3.2F,2.3F), floatArrayOf(3F,1F,3.2F,2.6F)).print()
    bestOfTwo(floatArrayOf(1F,2F,3F,4F,5F,5F,7F,8F,9F,10F), floatArrayOf(10F,9F,8F,7F,6F,5F,4F,3F,2F,1F)).print()
    bestOfTwo(floatArrayOf(-3.2F,-3.2F,-2.4F,7F,-10.1F), floatArrayOf(100F,-3.2F,2.4F,-7F,-10.1F)).print()
}

fun bestOfTwo(a :FloatArray, b :FloatArray): List<Float> =
    a.zip(b).map{(a,b)->when{b>a->b;a>b->a;else->a*2}}.toList()

fun List<Float>.print() {
    this.forEach { print("$it, ") }; println("")
}

```

**EDIT:**

-3 by replace "a+b\[i\]" by "a\*2"

-4 by replace "mapIndexed" method by "zip" *(Thanks to @AnonymousReality Swift solution)*

-5 by replace "Math.max" method by when condition

-1 by change when condition order

-6 by change toFloatArray() by toList()
> 11 votes

# Answer
# JavaScript (ES6), ~~53~~ ~~49~~ ~~45~~ 43 bytes

```
a=>b=>a.map((x,y)=>(y=b[y])>x?y:y<x?x:x+y)

```
* 4 bytes saved by borrowing a trick from Mr. Xcoder.
* 2 bytes saved thanks to Arnauld.

---

## Try it

```
o.innerText=(f=

a=>b=>a.map((x,y)=>(y=b[y])>x?y:y<x?x:x+y)

)(i.value=[1,3,3.2,2.3])(j.value=[3,1,3.2,2.6]);oninput=_=>o.innerText=f(i.value.split`,`.map(eval))(j.value.split`,`.map(eval))
```

```
<input id=i><input id=j><pre id=o>
```

---

## Explanation

```
a=>b=>

```

Anonymous function taking the 2 arrays as arguments via parameters `a` and `b`, in currying syntax (i.e., call with `f(a)(b)`

```
a.map((x,y)=>                      )

```

Map over the first array, passing each element through a function where `x` is the current element and `y` is the current index.

```
(y=b[y])

```

Get the element at index `y` in the second array and assign that as the new value of `y`.

```
>x?y

```

Check if `y` is greater than `x` and, if so, return `y`.

```
:y<x?x

```

Else, check if `y` is less than `x` and, if so, return `x`

```
:x+y

```

Else, return the sum of `x` and `y`. (Multiplying `x` or `y` by 2 would also work here, for the same number of bytes.)
> 9 votes

# Answer
# Haskell, 34 bytes

```
x!y|x>y=x|x<y=y|1<2=x+y
zipWith(!)

```

Try it online.
> 8 votes

# Answer
# , ~~31~~ 29 bytes

```
function(a,b)pmax(a,b)+a*!a-b

```

`pmax` takes the parallel maximum of the two (or more) arrays (recycling the shorter as needed).

I was looking at Luis Mendo's comment and obviously I realized the approach could work for R as well. That got me to 30 bytes, but then I started playing around with different ways of getting indices instead to improve my original answer, and stumbled upon `!a-b` as `TRUE` where `a==b` and `FALSE` otherwise, equivalent to `a==b`. However, for whatever reason, R doesn't require parentheses around `!a-b` as it does for `a==b`, which saved me two bytes.

As mentioned by JDL in the comments, this works because `!` (negation) has lower precedence than the binary operator `-` in R, which is strange.

Try it online! (new version)

Try it online! (original)
> 7 votes

# Answer
# Dyalog APL, 5 bytes

```
⌈×1+=

```

Try it online!

## How?

* , element-wise maximum of the arguments
* `×`, element-wise multiply
* `1+=`, 1 added to the element-wise equality of the arguments

This works because if the numbers are unequal, `1+=` will be `1`, which when multiplied by the maximum, is the maximum. When the numbers are equal, `1+=` will return `2`, when that is multiplied by the maximum, we get twice the maximum, or the maximum added to itself.
> 7 votes

# Answer
# Jelly, 6 bytes

```
żSṀE?€

```

A dyadic link taking a list of numbers on each side and returning the resulting list.

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

### How?

```
żSṀE?€ - Link: list of numbers L, list of numbers R   e.g. [1,3,3.2,2.3], [3,1,3.2,2.6]
ż      - zip - interleave L & R                       [[1,3],[3,1],[3.2,3.2],[2.3,2.6]]
     € - for each pair:
    ?  - { if:
   E   -   ...condition: equal                          0      0       1         0
 S     -   ...then: sum                                               6.4
  Ṁ    -   ...else: maximum                             3      3                2.6
       - }                                    ... ->   [3     ,3     ,6.4      ,2.6]

```

---

An alternative is this monadic link taking a list of the two lists, also **6 bytes**:

```
+»⁼?"/

```

---

* I don't think I've ever created a test-suite footer almost three times the byte count of the code before!
> 5 votes

# Answer
# 05AB1E, 5 bytes

```
øεMÃO

```

Try it online!

-1 thanks to Emigna.
> 5 votes

# Answer
# Java 8, ~~80~~ ~~69~~ ~~67~~ ~~66~~ ~~65~~ ~~64~~ 63 bytes

```
(a,b,l)->{for(;l-->0;)if(a[l]>=b[l])b[l]=a[l]*(a[l]>b[l]?1:2);}

```

Modifies the second input-array instead or returning a new float-array to save bytes.

-11 bytes by taking the length as additional integer-input, which is allowed according to the challenge rules.
-5 bytes thanks to *@OliverGrégoire* (one byte at a time.. xD)
-1 byte indirectly thanks to *@Shaggy*'s JS answer, by using `a[l]*2` instead of `a[l]+b[l]`.

**Explanation:**

Try it here.

```
(a,b,l)->{          // Method with 2 float-array and integer parameters and no return-type
  for(;l-->0;)      //  Loop over the array
    if(a[l]>=b[l])  //   If the current value in `a` is larger or equal to `b`:
      b[l]=         //   Modify the second input-array:
       a[l]*        //    Use `a` multiplied by:
        (a[l]>b[l]? //     If the current value in `a` is larger than `b`:
          1         //      Multiply by 1
         :          //     Else (`a` is smaller of equal to `b`):
          2)        //      Multiply by 2
                    //  End of loop (implicit / single-line body)
}                   // End of method

```
> 4 votes

# Answer
# MATL, 7 bytes

```
X>tG=s*

```

Input is a two-row matrix, where each row is one of the arrays.

Try it online!

### Explanation

```
X>   % Implicit input. Maximum of each column
t    % Duplicate
G    % Push input
=    % Is equal? Element-wise with broadcast. Gives a two-row matrix
s    % Sum of each column. Gives a row vector containing 1 and 2
*    % Multiply, element-wise. Implicit display

```
> 4 votes

# Answer
# Ruby, 42 bytes

```
->a,b{a.zip(b).map{|x,y|[x+y,x,y][x<=>y]}}

```

Try it online!

The spaceship operator is great.
> 4 votes

# Answer
# 05AB1E, ~~9~~ ~~8~~ 7 bytes

Saved a byte as *Erik the Outgolfer* pointed out that a list of lists is valid input.

```
øεMsËi·

```

Try it online!

**Explanation**

```
ø          # zip the lists
 ε         # apply to each pair
  M        # get max
   s       # swap the top 2 elements on the stack
    Ëi     # if all elements are equal
      ·    # double the max

```
> 3 votes

# Answer
# Pyth, 11 bytes

```
m*eSdhnd{dC

```

**Try it here!**

# Pyth, 12 bytes

```
m*eSdhqhdedC

```

**Try it here!**

**or**

```
m*eSdh!tl{dC

```

**Try it here!**
> 3 votes

# Answer
# Python 3, ~~49~~ ~~46~~ 45 bytes

*3 bytes removed thanks to @Mr.Xcoder (splat instead of two arguments), and 1 byte thanks to @ovs (map instead of list comprehension)*

```
lambda*x:map(lambda a,b:a*(a>=b)+b*(b>=a),*x)

```

Try it online!
> 3 votes

# Answer
# Mathematica, 31 bytes

```
MapThread[If[#==#2,2#,Max@##]&]

```
> 3 votes

# Answer
# J, 7 bytes

```
>.`+@.=

```

Try it online!

Takes one list as the left argument and the other as the right.

Luckily, equality is a rank zero operation.

# Explanation

```
>.`+@.=
      =  Compare equality pairwise
    @.   If equal
   +       Sum
>.       (Else) take greater value

```

`@.` isn't *really* an if statement, but in this case it functions as one (it indexes into the gerund `>.`+` based on the result of its right argument and applies that to the input).
> 3 votes

# Answer
# TI-Basic, ~~23~~ 21 bytes

```
Prompt A,B
(ʟA=ʟB)ʟA+max(ʟA,ʟB

```

Too bad lists take up two bytes each...
> 3 votes

# Answer
# Uiua, 6 bytes

```
×+1⊃=↥

```

Try it!

```
×+1⊃=↥
   ⊃=↥  # elementwise max and equality mask
 +1     # increment
×       # multiply

```
> 3 votes

# Answer
# Octave, 36 Byte

```
@(a,b)a.*(a>b)+b.*(b>a)+2.*a.*(a==b)

```
> 2 votes

# Answer
# Pyth, 7 bytes

```
ms.MZdC

```

Try it here.
> 2 votes

# Answer
# C# (.NET Core), using Linq 47+18=65 bytes

```
x=>y=>x.Zip(y,(a,b)=>a>b?a:b>a?b:b+a).ToArray()

```

Try it online!

# C# (.NET Core), 82 bytes

```
x=>y=>l=>{for(int i=0;i<l;i++)x[i]=x[i]>y[i]?x[i]:y[i]>x[i]?y[i]:y[i]*2;return x;}

```

Try it online!
> 2 votes

# Answer
# Common Lisp, ~~60~~ 59 bytes

```
(mapcar(lambda(x y)(*(max x y)(if(= x y)2 1)))(read)(read))

```

Try it online!

*-1 byte thanks to @Zacharý!*
> 2 votes

# Answer
# Python with numpy, 28 bytes

```
lambda a,b:a*(a>=b)+b*(b>=a)

```

Assumes input is given as two numpy arrays.
> 2 votes

# Answer
# Perl 6, ~~34~~ 28 bytes

```
{map {.max*2/set $_},[Z] $_}

```

Try it online!
> 2 votes

# Answer
# Vyxal, ~~8~~ 7 bytes

```
Zƛ≈[∑|G

```

*-1 byte thanks to @emanresu A*

Add the  flag if you want to see the numbers in decimal format.

Try it Online!

Explanation:

```
Z        # Zip
 ƛ       # On each pair
   [     # If
  ≈      # All are equal
    ∑    # Sum
     |   # Otherwise
      G  # Get the greatest value

```
> 2 votes

# Answer
# Vyxal, 6 bytes

```
₌Þ∴=›*

```

Try it Online!

```
₌      # Do both of these...
 Þ∴    # Elementwise maximum
   =›  # Equality, incremented -> list of 1s where unequal, 2s where equal
     * # Multiply by that.

```
> 2 votes

# Answer
# Swift 3, ~~81~~ 79 Bytes

```
func n(a:[Double],b:[Double]){for(x,y)in zip(a,b){print((x==y) ?x+y:max(x,y))}}

```

Swift has an interesting property in that an Int isn't directly castable to a `Double`, so you have to specify any arrays as being arrays of `Double`s before passing them to the function.

(e.g.) `var k:[Double] = [1,2,3,4,5,5,7,8,9,10]`

Edit: -2 bytes thanks to @EriktheOutgolfer
> 1 votes

# Answer
# C, ~~76~~ 75 bytes

*Thanks to @Kevin Cruijssen for saving a byte!*

```
f(a,b,n)float*a,*b;{for(;n--;++a,++b)printf("%f ",*a>*b?*a:*b>*a?*b:*a*2);}

```

Try it online!
> 1 votes

# Answer
# Japt, 13 bytes

```
íV,È¥Y Ä *XwY

```

Try it online! with the `-Q` flag to format the output array.
> 1 votes

# Answer
# Rust, ~~107~~ 97 bytes

```
|a:V,b:V|a.iter().zip(b).map(|(&x,y)|if x==y{x+y}else{x.max(y)}).collect::<V>();
type V=Vec<f32>;

```

Try it online!

*Saved 8 bytes thanks to @mgc*
> 1 votes

# Answer
# J, 6 bytes

```
>.*1+=

```

A direct translation of my APL answer (and thus works the same as my MY and Jelly answers). Any tips are welcome, since I don't really know J.

Try it online!

## Comparison with APL

```
>.*1+=
⌈ ×1+=

```
> 1 votes

# Answer
# Scala, 61 Bytes

```
x=>y=>x zip y map(v=>if(v._1==v._2)v._1*2 else v._1 max v._2)

```

The above is a function literal in Scala. Here's an explanation.

```
x=>y=>         // Function literal taking 2 * Vector[Float], x and y.
x zip y        // Zip x and y into one list of pairs.
map(           // Replace every element in the list via a function.
v=>            // Function literal that takes a pair of floats.
if(v._1==v._2) // If the pair are equal.
v._1*2         // Set the element to the first member of the pair multiplied by 2.
else           // Otherwise.
v._1 max v._2) // Set it to their max.

```
> 1 votes

# Answer
# Swift 4, 41 bytes

```
{zip($0,$1).map{$0==$1 ?2*$0:max($0,$1)}}

```

Test cases:

```
let f: ([Float], [Float]) -> [Float]
    = {zip($0,$1).map{$0==$1 ?2*$0:max($0,$1)}}

let testcases: [(inputA: [Float], inputB: [Float], expected: [Float])] = [
    (
        inputA: [],
        inputB: [],
        expected: []
    ),
    (
        inputA: [1, 2, 3],
        inputB: [1, 3, 2],
        expected: [2, 3, 3]
    ),
    (
        inputA: [1, 3, 3.2, 2.3],
        inputB:  [3, 1, 3.2, 2.6],
        expected: [3, 3, 6.4, 2.6]
    ),
    (
        inputA: [1,2,3,4,5,5,7,8,9,10],
        inputB:  [10,9,8,7,6,5,4,3,2,1],
        expected: [10, 9, 8, 7, 6, 10, 7, 8, 9, 10]
    ),
    (
        inputA: [-3.2, -3.2, -2.4, 7, -10.1],
        inputB:  [100, -3.2, 2.4, -7, -10.1],
        expected: [100, -6.4, 2.4, 7, -20.2]
    ),
]

for (caseNumber, testcase) in testcases.enumerated() {
    let actual = f(testcase.inputA, testcase.inputB)
    assert(actual == testcase.expected,
        "Testcase #\(caseNumber) \((testcase.inputA, testcase.inputB)) failed. Got \(actual), but expected \(testcase.expected)!")
    print("Testcase #\(caseNumber) passed!")
}

```
> 1 votes

# Answer
# Stax, 8 bytes

```
Ç√'8½B=☺

```

Run and debug it
> 1 votes

# Answer
# Desmos, 26 bytes

```

f(a,b)=\{a=b:2a,a>b:a,b\}

```

Leading newline necessary.

Try it on Desmos!
> 1 votes

# Answer
# Python, ~~57~~ 56 bytes

```
lambda a,b:[x==y and x+y or max(x,y)for x,y in zip(a,b)]

```

## Generators, ~~57~~ 56 bytes

```
lambda a,b:(x==y and x+y or max(x,y)for x,y in zip(a,b))

```

-1 each by Steffan
> 1 votes

# Answer
# BQN, ~~6~~ 5 bytes

*-1 byte by porting emanresu A's Vyxal answer*

```
⌈×1+=

```

Anonymous tacit function that takes equal-length lists as left and right arguments. Try it at BQN online!

### Explanation

```
⌈×1+=
    =  Compare the two lists itemwise (1 for equal, 0 for not equal)
  1+   Add 1 to each (2 for equal, 1 for not equal)
⌈       Get the itemwise maximums of the two lists
 ×     Multiply (itemwise)

```

### Original solution

The spec can be implemented very literally in **6 bytes**:

```
=◶⌈‿+¨
      ¨  Apply this function to corresponding pairs of elements from the arguments:
=          Test if the elements are equal (1 if so, 0 if not)
 ◶         Use that result to pick a function from this list and apply it:
  ⌈         If 0 (not equal), then max
   ‿+      If 1 (equal), then add

```
> 1 votes

# Answer
# Factor, 36 bytes

```
[ [ 2dup = [ + ] [ max ] if ] 2map ]

```

Try it online!
> 1 votes

# Answer
# POSIX Shell + Utilities, 40 bytes

```
paste $@|awk '$0=$1<$2?$2:$1>$2?$1:2*$1'

```

"Arrays" defined as "text files per POSIX".
Obviously buggy insofar as `[0], [0] -> []`. Doesn't come up in the validator, so. Append the 2-byte `""` sequence to also handle that edge case.

Transcript of test cases:

```
$ cat cg; echo; wc -c cg
paste $@|awk '$0=$1<$2?$2:$1>$2?$1:2*$1'
40 cg
$ ./cg /dev/null                               /dev/null
$ ./cg <(printf '%s\n' 1 2 3)                  <(printf '%s\n' 1 3 2)
2
3
3
$ ./cg <(printf '%s\n' 1 3 3.2 2.3)            <(printf '%s\n' 3 1 3.2 2.6)
3
3
6.4
2.6
$ ./cg <(printf '%s\n' 1 2 3 4 5 5 7 8 9 10)   <(printf '%s\n' 10 9 8 7 6 5 4 3 2 1)
10
9
8
7
6
10
7
8
9
10
$ ./cg <(printf '%s\n' -3.2 -3.2 -2.4 7 -10.1) <(printf '%s\n' 100 -3.2 2.4 -7 -10.1)
100
-6.4
2.4
7
-20.2

```
> 1 votes

# Answer
# CJam, 16 bytes

```
{.{a+_:e>\:=)*}}

```

Try it online!

Oh hey look, my code is cute `:=)` but a big dude `\:=)*`
> 0 votes

# Answer
# Clojure, 40 bytes

```
#(map(fn[x y]((if(= x y)+ max)x y))% %2)

```

Try it online!
> 0 votes

# Answer
# PHP, 74 bytes

```
function($a,$b){foreach($a as$i=>$p)echo$p*($p>=$q=$b[$i])+$q*($q>=$p),_;}

```

Prints the results separated by an underscore. Try it online.
> 0 votes

# Answer
# Swift, 80 bytes

```
var o = [Int]();for (c, d) in zip(a,b){o.append(c==d ? c*2 : max(c,d))};return o

```
* Create the output array
* zip together a & b
* for each loop through with c & d
* append result to output array
* return output array
> 0 votes

# Answer
# MY, 20 bytes

```
αωD6ǵ'69ǵ';ƒ⇹(αω=‘×↵

```

Try it online!

This uses the exact same approach as my APL and Jelly answers, except MY doesn't have some of the builtins:

* `D6ǵ'69ǵ';ƒ`, this pushes `<SPACE>⍐` in MY's codepage (where `<SPACE>` is a physical space) as a function, which turns two items into a list, then finds the maximum.
* `⇹(`, map over each argument, then apply the function.
> 0 votes

# Answer
# K, 12 bytes

```
{x|y*(1+x=y)}

```

Exact same strategy as my other answers.

Try it online!

Any golfing tips are welcome, as I don't really know K.
> 0 votes

# Answer
# Erlang, 65 bytes

```
fun(A,B)->lists:zipwith(fun(C,C)->C+C;(D,E)->max(D,E)end,A,B)end

```

example:

```
1> (fun(A,B)->lists:zipwith(fun(C,C)->C+C;(D,E)->max(D,E)end,A,B)end)([1, 3, 3.2, 2.3], [3, 1, 3.2, 2.6] ).
[3,3,6.4,2.6]

```

just a straightforward anonymous fun
> 0 votes

# Answer
# Jq 1.5, ~~49~~ 44 bytes

```
transpose|map(if.0==.1then add else max end)

```

Sample input

```
[[], []]
[[1, 2, 3], [1, 3, 2]]
[[1, 3, 3.2, 2.3], [3, 1, 3.2, 2.6]]
[[1,2,3,4,5,5,7,8,9,10], [10,9,8,7,6,5,4,3,2,1]]
[[-3.2, -3.2, -2.4, 7, -10.1], [100, -3.2, 2.4, -7, -10.1]]

```

Sample run

```
$ jq -Mc 'transpose|map(if.0==.1then add else max end)' input
[]
[2,3,3]
[3,3,6.4,2.6]
[10,9,8,7,6,10,7,8,9,10]
[100,-6.4,2.4,7,-20.2]

```

Character count

```
$ echo -n 'transpose|map(if.0==.1then add else max end)' | wc -c
      44

```

Thanks again to Jonathan Frech for helping eliminate 5 bytes!
> 0 votes

# Answer
# Tcl, 57 bytes

```
proc M A\ B {lmap a $A b $B {expr $a-$b?max($a,$b):2*$a}}

```

Try it online!
> 0 votes

# Answer
# Perl 5, 59 + 1 (`-p`) = 60 bytes

```
say join$",map$_>($t=$F[$i++])?$_:$_<$t?$t:$_*2,split/ /,<>

```

Try it online!
> 0 votes

# Answer
# SmileBASIC, 120 bytes

An answer using ONLY the `ARYOP` function.

```
DEF B A,B,L
DIM C[L],D%[L]ARYOP 6,C,A,A,B
ARYOP.,A,A,B
ARYOP 1,B,A,C
ARYOP 1,B,C,B
ARYOP 6,D%,B,-1,0ARYOP 4,A,C,D%,A
END

```

Function is called as **B** *array1* **,** *array2* **,** *length*. Output is stored in array1.

## Explanation:

```
'get minimum, sum, and maximum of B and A
ARYOP #AOPCLP,C,A,A,B 'c=clamp(a,a,b) (gets the minimum of a and b)
ARYOP #AOPADD,A,A,B 'a=a+b (get the sum)
ARYOP #AOPSUB,B,A,C 'b=a-c (get the maximum)
'check if min==max
ARYOP #AOPSUB,B,C,B 'b=c-c (min-max, will be negative or 0)
ARYOP #AOPCLP,D%,B,-1,0 'd%=clamp(b,-1,0) (d% is an integer array. 0=equal, -1=not equal)
'add subtract min from sum if elements were not equal
ARYOP #AOPMAD,A,C,D%,A 'a=c*d%+a

```

This challenge seemed boring at first, but there are actually a lot of different ways to do it. For example:

-calculate the maximum, add the minimum if B==A

-calculate the sum, subtract A if A\<B, subtract B if B\<A

-b+max(a-b,0)+a\*(a==b)
> 0 votes

# Answer
# APL(Dyalog Unicode), 15 bytes <sup>SBCS</sup>

```
(⊣⌈⊢×1+⊣=⊢)/¨,¨

```

Try it on APLgolf!

Can be golfed as:

```
((⌈×1+=)/¨,¨)
⌈×1+=

```

So it ends up being the same as the other APL answer...
> 0 votes

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


# Question
Title: Remove odd indices and double the even indices
Your task is simple, just remove the odd indices and double the even indices

## Example

the input is `Hello, World!` and we get indices

```
H e l l o , _ W o r  l  d  !
1 2 3 4 5 6 7 8 9 10 11 12 13

```

and remove the odd indices

```
el,Wrd

```

Double!

```
eell,,WWrrdd

```

and you are done

1-Indexing

## Test cases

```
abcdef => bbddff
umbrella => mmrrllaa
looooooooong text => ooooooooooggttxx
abc => bb
xkcd => kkdd
Hello, World! => eell,,WWrrdd
D => <empty>
KK => KK
Hi => ii
odd_length! => dd__eegghh
<empty> => <empty>

```

The input can be list if you want.

# Answer
> 5 votes
# Vyxal, 3 bytes

```
y2•

```

Try it Online!

Vyxal has a better built-in for this than Jelly.

```
y2•     Full Program
y       Uninterleave; push a[::2] and a[1::2]
 2•     Repeat each character twice

```

# Answer
> 17 votes
# brainfuck, 8 bytes

```
,,[..,,]

```

Try it online!

# Answer
> 11 votes
# convey, 8 bytes

*-1 thanks to Wheat Wizard!*

```
v2{
0"!}

```

Try it online!

The 0 and 2 loop around, applying themselves to the input via `!` (take), thus duping the element 0 or 2 times.

# Answer
> 10 votes
# , 8 bytes

```
#~0 2$~#

```

Try it online!

* `0 2$~#` Repeat the pattern `0 2` for the length of the string:

```
Hello, World
020202020202

```
* `#~` Use that mask to "copy" the characters: zeros get deleted, twos get doubled:

```
eell,,WWrrdd

```

# Answer
> 6 votes
# , ~~35~~ ~~34~~ 32 bytes

*Edit: -1 byte thanks to Giuseppe*

```
function(x)rep(x,`[<-`(x,0:1*2))

```

Try it online!

# Answer
> 5 votes
# Jelly, 4 bytes

```
Ḋm2Ḥ

```

Try It Online!

```
Ḋm2Ḥ    Main Link
Ḋ       Remove the first character
 m2     Return every other character
   Ḥ    Double. This turns ["a", "b"] into ["aa", "bb"], which
        is not the correct format for a Jelly string, but displays
        correctly when printed.

```

# Answer
> 5 votes
# Python, 37 bytes

```
lambda a:"".join(x*2for x in a[1::2])
```

Attempt This Online!

# Answer
> 5 votes
# ayr, ~~9~~ 8 bytes

Using Jonah's J method gets me -1 byte

```
]#0 2$`#

```

I have the advantage of `#`'s args being swapped compared to J, but unfortunately monadic 2-trains are not hooks like in J.
Old answer:

```
:,_2]/,@:

```

Try it!

# Explained

`:` is partial application (K-style train)

```
     ,@:   Zip-self with concatenation
 _2]/      Split into groups of two, take right element
,          Flatten

```

# Answer
> 5 votes
# Husk, 5 bytes

```
Ṙ2Ċ2t

```

Try it online!

### Explanation

```
Ṙ2Ċ2t
    t   drop first char
  Ċ2    take every 2-nd char
Ṙ2      repeat each char 2 times

```

# Answer
> 5 votes
# Uiua, 7 bytes

```
▽↯△,0_2

```

Try it online!

```
▽↯△,0_2    input: a string
  ↯△,0_2    [0, 2] cycled to the length of the input:
      0_2      [0, 2]
   △,         shape of the input ([length])
  ↯            reshape [0, 2] to the shape [length]
▽           keep; delete chars at 0s and duplicate at 2s

```

# Answer
> 4 votes
# Factor \+ `sequences.repeating`, 19 bytes

```
[ <odds> 2 repeat ]

```

Get the odd-indexed elements then repeat them twice.

# Answer
> 4 votes
# JavaScript (Node.js), 29 bytes

```
x=>x.replace(/.(.?)/g,'$1$1')

```

Try it online!

# Answer
> 4 votes
# Excel, 46 bytes

```
=CONCAT(REPT(MID(A1,SEQUENCE(2^15,,2,2),1),2))

```

Input is in cell `A1`. Output is wherever the formula is.

Working from the inside out:

* `SEQUENCE(2^15,,2,2)` creates an array of even numbers from 2 to 32,768. This is the limit for how many characters can be in a cell so it's the limit of the input.
* `MID(A1,SEQUENCE(~),1)` pulls out all the even-index characters one at a time.
* `REPT(MID(~),2)` doubles all those characters.
* `CONCAT(REPT(~))` combines them all into a single string.

# Answer
> 3 votes
# 05AB1E, 4 bytes

```
ιθºS

```

I/O as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
ι     # Uninterleave the (implicit) input-list into two parts
      #  e.g. ["a","b","c","d","e","f"] → [["a","c","e"],["b","d","f"]]
 θ    # Only leave the last/second part
      #  → ["b","d","f"]
  º   # Mirror/double each character
      #  → ["bb","dd","ff"]
   S  # Convert the list of strings to a flattened list of characters
      #  → ["b","b","d","d","f","f"]
      # (after which it is output implicitly as result)

```

# Answer
> 3 votes
# Retina 0.8.2, 10 bytes

```
.(.?)
$1$1

```

Try it online! Link includes test cases. Explanation: Port of @l4m2's JavaScript answer. In Retina 1 you can write `2*$1` for the same byte count.

# Answer
> 3 votes
# Charcoal, 8 bytes

```
⭆Ｓ×ι⊗﹪κ²

```

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

```
 Ｓ          Input as a string
⭆           Map over characters and join
   ι        Current character
  ×         Repeated by
      κ     Current index
     ﹪      Modulo
       ²    Literal integer `2`
    ⊗       Doubled

```

# Answer
> 3 votes
# Perl 5 -p, 14 bytes

```
s/.(.?)/$1$1/g

```

Try it online!

# Answer
> 3 votes
# BQN, 9 bytesSBCS

```
⊢/˜≠⥊0‿2˙

```

Run online!

Uses Jonah's J idea.

# BQN, 10 bytesSBCS

```
2/1⊑˘⌊‿2⊸⥊

```

Run online!

# Answer
> 3 votes
# JavaScript (Node.js), 28 bytes

```
f=([,y,...z])=>y?y+y+f(z):''

```

Try it online!

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

```
(2*2!!#:)#

```

Try it online!

* `(...)#` set up a filter/replicate, where the code in `(...)` is run on the (implicit) input and returns a list of numbers. for each such number, that many copies of the corresponding input item will be returned.
* `(2*2!!#:)` return a sequence like `0 2 0 2 ... 0 2` that matches the length of the input. this removes items at even indices (0-based), and doubles those at odd indices

# Answer
> 2 votes
# Haskell, 23 bytes

```
f(a:b:c)=b:b:f c
f _=[]

```

Try it online!

# Answer
> 2 votes
# Red, 53 bytes

```
func[s][foreach c extract/index s 2 2[prin c prin c]]

```

Try it online!

`extract/index s 2 2` says "get every other element of `s` starting at index 2" (keeping in mind Red is 1-indexed). Then print each of those elements twice.

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

```
f(char*c){for(;*c++;c++)c[-1]=*c;}

```

Try it online!

# Answer
> 2 votes
# \>\<\>, 4 bytes

```
i#o:

```

Try it online!

Terminates with an error.

This again?

## How?

```
i     Take an input (instruction pointer (IP) going right)
 #    IP bounces off # and starts going left
i     Take another input
   :  Duplicate it
  o   Output it
 #    IP bounces off # and starts going right
  o   Output again
   :  Duplicate (Useless)

And now, we're back to where we started, at the first character facing right.
The code will continue executing until it terminates with an error when running out of input.

```

# Answer
> 2 votes
# GNU AWK, 35 bytes

```
BEGIN{RS=".|"}{printf NR%2?e:RT RT}

```

or

```
BEGIN{RS=".|";ORS=e}$0=NR%2?e:RT RT

```

Try it online!

This is possible thanks to the `RT` variable, only available in GNU AWK. The characters are stored one at a time in `RT`, and the ternary conditional operator is used to skip the odds and double the even characters.

# AWK, 47 bytes

```
split($0,a,e){for(i in a)printf i%2?e:a[i]a[i]}

```

Try it online!

Splits the input character by characters into the array `a`, and does the skip-and-double magic through the ternary operator `?:`.

# Answer
> 2 votes
## **MATLAB, 25 bytes**

```
@(x)repelem(x(2:2:end),2)

```

# Answer
> 2 votes
# Lua,77 83 bytes

Edited to comply with code golf rules. Assumes at least a space in input because I'm not entirely sure how to make it work with nil input without throwing an error.

```
p,t=io.read(),{} for i=0,#p,2 do t[i],t[i+1]=string.sub(p,i,i),string.sub(p,i,i)end

```

Try it online!

# Answer
> 2 votes
# Fig, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
eh]y

```

Try it online!

## Explanation

```
eh]y
   y   Uninterleave the input - return a list like [a[::2], a[1::2]]
  ]    Get the last element (which is a[1::2])
e      Over each character...
 h     Double it

```

# Answer
> 2 votes
# , 25 bytes

```
3.72372382352352372372394

```

Try it online!

# Answer
> 2 votes
# Thunno 2, 4 bytes

```
zt2Ḅ

```

Attempt This Online!

#### Explanation

```
zt2Ḅ  # Implicit input
z     # Uninterleave
 t    # Leave only the tail
  2Ḅ  # Double each character
      # Implicit output

```

# Answer
> 2 votes
# Coconut, 40 bytes

```
"".join(map(->_*2,input()[1::2]))`print`

```

Try it online!

I'm just learning Coconut, so there's probably a shorter, better way to do this... Feedback 100% welcomed!

Here's how it works:

```
            ->_*2                        - def lambda that dup's a char
                  input()                - read string from STDIN
                         [1::2]          - make a list of even num chars
        map(    ,              )         - map the lambda over char list
"".join(                        )        - convert list to a string
                                 `print` - apply "print" implicit lambda

```

# Answer
> 2 votes
# Uiua, 8 bytes

```
▽+.◿2⇡⧻.

```

Try it!

```
▽+.◿2⇡⧻.
       .  # duplicate
      ⧻   # length
     ⇡    # range
   ◿2     # modulo two
 +.       # double
▽         # keep

```

# Answer
> 2 votes
# Pip, ~~9~~ 8 bytes

```
S*<>aX:2

```

Attempt This Online!

### Explanation

```
    a    ; Command-line argument
  <>     ; Break into two-character substrings
S*       ; Remove the first character of each
     X:2 ; Double each
         ; Concatenate together and output (implicit)

```

If the argument string has an odd number of characters, the final substring created by `<>` will have one character in it. `S` will remove that one character, leaving the empty string. Doubling the empty string and concatenating it to the output does not affect the output.

# Answer
> 2 votes
# Nekomata, 3 bytes

```
ĭ:Ĭ

```

Attempt This Online!

```
ĭ:Ĭ
ĭ   Uninterleave
 :  Duplicate
  Ĭ Interleave

```

# Answer
> 1 votes
# APL+WIN, ~~15~~ 14 bytes

-1 byte thanks to Adám

Prompts for string

```
2/(~2|⍳⍴m)/m←⍞

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# APL (Dyalog Unicode), 13 bytes

```
{2/⍵/⍨~2|⍳≢⍵}

```

Try it online!

pretty self explnatory

# Answer
> 1 votes
# sed 4.2.2, 5 bytes

```
n;p;p

```

Try it online!

Takes string input one character per line (if allowed).

* `-n option` Don't print by default
* `n;` Skips a line.
* `p;p` Print the line twice.

## sed 4.2.2, 15 bytes

```
s/.\(.\)/\1\1/g

```

Try it online!

Solution taking a single string.

* `s/.\(.\)/` Substitute any char, followed by any other char...
* `\1\1/` With the 2nd char repeated twice...
* `g` Globally

# Answer
> 1 votes
# APL (Dyalog Unicode), 12 bytes

```
{⍵/⍨0 2⍴⍨≢⍵}

```

Try it online!

APL port of @jonah 's j answer

# Answer
> 1 votes
# naz, 40 bytes

```
2x1v1x1f1r3x1v2e1r3x1v2e2o1f0x1x2f0a0x1f

```

It's sure been a while, hasn't it? Works for any null-terminated input string.

Try it online!

**Explanation** (with `0x` instructions removed)

```
2x1v                                     # Set variable 1 equal to 0
    1x1f                                 # Function 1
        1r                               # Read a byte of input
          3x1v2e                         # Goto function 2 if it equals variable 1
                1r                       # Read another byte of input
                  3x1v2e                 # Goto function 2 if it equals variable 1
                        2o1f             # Otherwise, output twice and call function 1
                              1x2f       # Function 2
                                  0a     # No-op
                                      1f # Call function 1

```

# Answer
> 1 votes
# Japt `-hP`, ~~5~~ 4 bytes

The `¬` can be removed if we can take input as a character array.

```
¬m²ó

```

Try it

# Answer
> 1 votes
# Python 2, 34 bytes

```
f=lambda s:s and s[1:2]*2+f(s[2:])

```

Try it online!

# Answer
> 1 votes
# Lexurgy, 32 bytes

Docs here.

Due to Lexurgy's input considering strings as "stuff surrounded by whitespace", no whitespace can appear in the input string. Otherwise, Lexurgy will consider `["Hello, world!"]` as `["Hello,", "world!"]`. Whitespace must be replaced with a different character (such as `_`).

```
o:
[] []$1=>* $1 $1
[]=>* /_ $

```

Ungolfed:

```
only-evens:
 [] []$1 => * $1 $1 # capture the second character and dup it
 [] => * / _ $ # remove last odd character as well

```

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

```
#~##&~#&/@#~Drop~;;;;2&

```

Try it online!

Input a list. Drops odd indices and doubles everything left.

# Answer
> 1 votes
# munge, 20 bytes

```
/.(.)?/=>{$1 $1}

```

Munge it!

# Answer
> 1 votes
# Ruby, 32 bytes

```
->s{s.scan(/.(.)/).map{_1*2}*''}
```

Attempt This Online!

# Answer
> 1 votes
# Perl 5 \+ `-p`, 11 bytes

Takes a list of chars (to differentiate from @Kjetil's answer).

2 bytes saved thanks to @Neil!

```
$_ x=$|--*2

```

Try it online!

## Explanation

Uses the string repetition operator (`x`) to repeat `$_` `$|--*2` times which, since `$|` can only be `1` or `0`, will alternate between `0` or `2` for each character of input.

# Answer
> 1 votes
# SimpleTemplate 0.84, 36 bytes

Requires that an array of characters is passed to the `render()` method in PHP. Argument unpacking can be used for convenience. Each argument is 1 character.

```
{@eachargv}{@if__ is mod2}{@echo_,_}

```

This is a full program.

---

## How it works?

It simply loops all over the arguments passed to the `render()` method.

It checks if the index is odd, and, in case it is, displays the character twice.

---

## About the code...

* `{@eachargv}`
This is a simple loop over the elements in `argv`.
Automatically, the current value is stored in the variable `_` and the index is stored in `__`.
A more readable example is `{@each argv as _ key __}`
* `{@if__ is mod2}`
This checks if the key's modulo is a truthy value.
If it is a truthy value, it means we are dealing with an odd index (the language is 0-indexed, like PHP). A readable alternative is `{@if __ is not multiple of 2}`
* `{@echo_,_}`
Simply outputs the character twice.
* Usually, it would be needed to close the loop and the `if`, but it is optional since there isn't any other code to run outside.

---

You can try this on http://sandbox.onlinephpfunctions.com/code/b006b2ec293bab18cd6db2f1b8a2454da047ea49

Please pick PHP 7.4.13.

# Answer
> 1 votes
# Rattle, 25 bytes

```
|!I=@[0q][=#%[1=#1g`bb]]@

```

Try it Online!

Might not be the most elegant solution...

# Explanation

```
|                  parse input
 !                 disables implicit output (necessary only for special case of empty input)
  I                save input as char array in consecutive memory slots, move pointer to next empty slot
   =@              set top of stack to value of pointer
     [0q]          if the pointer is in the zero position (meaning empty input), terminate the program
         [     ]@  repeat x number of times where x is the value of the pointer (to iterate over all input characters)

  =#               set top of stack to current loop iterator
    %              mod 2
     [1       ]    if the result is 1...
       =#1         set top of stack to current loop iterator for main loop
          g`       get value from the memory slot according to the top of the stack
            bb     add char to output buffer twice with no separator

```

# Answer
> 1 votes
# Pyth, 6 bytes

```
.i=%2t

```

Test suite. Slightly more interesting one..

**Explanation:**

```
.i=%2t # whole program

       # take the implicit input (Q)
     t # remove the first letter
   %2  # keep the odd indices only
   %2t # keep the even indices only
  =    # assign this to Q (the variable encountered)
.i     # then interleave this, with
       # newly assigned implicit Q (implicit output)

```

---

### 7 bytes

This one uses a `map` in order to double the characters.

```
s+Rd%2t

```

Test suite

# Answer
> 1 votes
# Rust, 118 bytes

```
fn main(){let y=&mut"".into();std::io::stdin().read_line(y);for(i,c)in(0..).zip(y.chars()){if i%2>0{print!("{c}{c}")}}}

```

Attempt This Online!

Half is just stdin...

Else,

---

# Rust, ~~108~~ ~~106~~ 94 bytes

```
|c:&str|{let mut s=format!("");for(i,c)in(0..).zip(c.chars()){if i%2>0{s.push(c);s.push(c)}}s}

```

Attempt This Online!

# Answer
> 1 votes
# PLIS, 13 bytes

```
&R($0@@i@VfB)

```

Defines a function `R` which takes a sequence as its first and only parameter. The language implements strings as infinite sequences of `0`s preceded by the string itself. This program works for all sequences, strings included.

We define a function instead of using command line parameters because it is currently impossible to supply anything besides big integers through command line parameters. This would be 9 bytes if it were possible to supply, say, a string via command line (`$0@@i@VfB`).

```
print(R("umbrella"))        #=> mmrrllaa
print(R("Hello, World!"))   #=> eell,,WWrrdd
print(R("odd_length!"))     #=> dd__eegghh

```

## Explanation

After expanding shortnames, we have the following, equivalent code:

```
&R($0@@A000035@A004526)
&R(                   )      define a function R
       A000035               a(n) = n%2 ( 0 1 0 1 0 1 0 1 ... )
      @                      indices where true; ( 1 3 5 7 9 11 ... )
                             using shortnames, this is shorter than the equivalent
                             A005408; compare CwB <=> @i
              @              index by
               A004526       non-negative integers repeated ( 0 0 1 1 2 2 ...)
                             this gives ( 1 1 3 3 5 5 7 7 9 9 ... )
   $0@                       index input by this sequence

```

# Answer
> 1 votes
# Dis, 4 bytes

```
}}{{

```

Offline interpreter on dis.web

Easy for this kind of task.

A string of any bytes shall be given from standard input, and outputs to standard output.

## Explained

```
}    store odd-indexed byte to accumulator
     59048 is stored if EOF
 }   same for even-indexed byte
  {  output the accumulator
     halt if accumulator is 59048
   { same
     implicitly NOP until cell 59048
     loop back to cell 0

```

# Answer
> 1 votes
# Rockstar, 70 bytes

```
listen to S
cut S
O's ""
while S
roll S
let O be+roll S*2 or ""

say O

```

Try it (Code will need to be pasted in)

Or, if we can output each pair of characters separately:

## 51 bytes

```
listen to S
cut S
while S
roll S
say roll S*2 or ""

```

# Answer
> 1 votes
# *Acc!!*, 46 bytes

```
N
N
Count i while _/32 {
Write _
Write _
N
N
}

```

Try it online!

### Explanation

```
# Read two characters
N
N
# Loop while the most recent character code is 32 or greater
Count i while _/32 {
  # Write the most recent character twice
  Write _
  Write _
  # Read two more characters
  N
  N
}

```

# Answer
> 0 votes
# \>\<\>, 11 bytes

```
ii::1+?!;oo

```

Try it online!

# Answer
> 0 votes
# MathGolf, ~~6~~ 5 bytes

```
{ï¥∞*

```

-1 byte thanks to *@Neil*.

Try it online.

**Explanation:**

```
{      # Foreach over the characters of the (implicit) input-string:
 ï     #  Push the 0-based loop index
  ¥    #  Modulo-2 this index
   ∞   #  Double it
    *  #  Repeat the current character that many times (0 results in an empty string)
       # (after which the entire stack joined together is output implicitly)

```

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), ~~76~~ 74 bytes

```
	I =INPUT
N	I POS(X) LEN(1) (LEN(1) | '') . E @X =E E	:S(N)
	OUTPUT =I
END

```

Try it online!

# Answer
> 0 votes
# Python 3, 74 bytes

```
from functools import*
lambda s:reduce(tuple.__add__,zip(s[1::2],s[1::2]))

```

Try it online!

# Answer
> 0 votes
# Burlesque, 6 bytes

```
2en)^^

```

Try it online!

```
2en # Take every 2nd
)^^ # Map duplicate char

```

# Answer
> 0 votes
# J-uby, 21 bytes

```
~:gsub&'\1\1'&/.(.)?/

```

Attempt This Online!

# Answer
> 0 votes
# C#, 41 bytes

```
f=x=>x.Length<2?"":""+x[1]+x[1]+f(x[2..])

```

Try it online!

# Answer
> 0 votes
# Headass, 8 bytes

```
{UN)UPP}

```

Try It Online! \- can take input as either list of characters or list of charcodes

##### Explanation:

```
{UN)UPP}  full program
{      }  loop
 U         discard nth input (1 indexed)
  N)       break out of loop if input is exhausted
    UPP    print n+1th input twice (1 indexed)

```

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