title: Compute the Median

text:
# Question
Title: Compute the Median
### Challenge

Given a nonempty list of real numbers, compute its median.

### Definitions

The median is computed as follows: First sort the list,

* if the number of entries is *odd*, the median is the value in the center of the sorted list,
* otherwise the median is the arithmetic mean of the two values closest to the center of the sorted list.

### Examples

```
[1,2,3,4,5,6,7,8,9] -> 5
[1,4,3,2] -> 2.5
[1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] -> 1.5
[1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] -> 1.5

```

# Answer
> 20 votes
# Python 2, 48 bytes

An unnamed function which returns the result. -1 byte thanks to xnor.

```
lambda l:l.sort()or(l[len(l)/2]+l[~len(l)/2])/2.

```

The first step is obviously to sort the array, using `l.sort()`. However, we can only have one statement in a lambda, so we utilise the fact that the sort function returns `None` by adding an `or` \- as `None` is falsy in Python, this tells it to evaluate and return the next part of the statement.

Now we have the sorted list, we need to find either the middle, or the middle two, values.

Using a conditional to check the length's parity would be too verbose, so instead we get the indexes `len(l)/2` and `~len(l)/2`:

* The first is **floor(length / 2)**, which gets the middle element if the length is odd, or the left item in the central pair if the length is even.
* The second is the binary inversion of the list length's, evaluating to **-1 - floor(length / 2)**. Due Python's negative indexing, this essentially does the same as the first index, but backwards from the end of the array.

If the list is of odd length, these indexes will point to the same value. If it is of even length, then they will point to the central two items.

Now that we have these two indexes, we find these values in the list, sum them, and divide them by 2. The trailing decimal place in `/2.` makes sure that it is float division rather than integer division.

The result is implicitly returned, as this is a lambda function.

**Try it online!**

# Answer
> 16 votes
# Python3 - ~~31~~ 30 bytes

*Saved a byte thanks to @Dennis!*

I wasn't planning on a builtin answer, but I found this module and thought it was really cool cuz I had no idea it existed.

```
from statistics import*;median

```

Try it online here.

# Answer
> 9 votes
# Brain-Flak, 914 + 1 = 915 bytes

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

```

Requires the `-A` flag to run.

Try it online!

# Explanation

The backbone of this algorithm is a bubble sort I wrote a while ago.

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

```

I don't remember how this works so don't ask me. But I do know it sorts the stack and even works for negatives

After everything has been sorted I find 2 times the median with the following chunk

```
([]<(()())>(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}<(())>)  #Stack height modulo 2
{((<{}{}          #If odd
 ([[]]())         #Push negative stack height +1
 {                #Until zero
  ({}()()<{}>)    #add 2 to the stack height and pop one
 }{}              #Get rid of garbage
 (({}){}<         #Pickup and double the top value
 ([]){{}{}([])}{} #Remove everything on the stack
 >)               #Put it back down
>))}{}            #End if
{(<{}                     #If even
  ([[]]()())              #Push -sh + 2
  {({}()()<{}>)}{}        #Remove one value for every 2 in that value
  ({}{}<([]){{}{}([])}{}>)#Add the top two and remove everything under them
>)}{}                     #End if

```

Now all that is left is to make convert to ASCII

```
([(({}<((((((()()()){}){}){}()){})[()()()])>)<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}(({}<>)<
{(<{}([{}])>)}{}  #Absolute value (put "/2" beneath everything)

{                 #Until the residue is zero
(({})<            #|Convert to base 10
((()()()()()){})  #|
>)                #|...
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})
({}<({}<>)<>>((((()()()){}){}){}){})((()()()()()){})<>({}<>)
                  #|
(()()){({}[()]<([([({})](<()>))](<>())){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}(({})<>)<>{(<{}([{}])>)}{}({}<>)<>({}<><({}<>)>)>)}{}({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)<>(({}{}[(())])){{}{}(((<{}>)))}{}{}{(<{}<>([{}])><>)}{}<>
}{}               #|
>)
{(<{}(((((()()()()())){}{})){}{})>)}{}  #If it was negative put a minus sign

```

# Answer
> 9 votes
## Jelly, 9 bytes

```
L‘HịṢµ÷LS

```

Try it online!

### Explanation

I'm still getting the hang of Jelly... I wasn't able to find built-ins for either the median or the mean of a list, but it's very convenient for this challenge that Jelly allows non-integer indices into lists, in which case it will return a pair of the two closest values. That means we can work with half the input length as an index, and get a pair of values when we need to average it.

```
L          Get the length of the input.
 ‘         Increment it.
  H        Halve it. This gives us the index of the median for an odd-length list
           (Jelly uses 1-based indexing), and a half-integer between the two indices
           we need to average for even-length lists.
   ịṢ      Use this as an index into the sorted input. As explained above this will
           either give us the median (in case of an odd-length list) or a pair of
           values we'll now need to average.
     µ     Starts a monadic chain which is then applied to this median or pair...
      ÷L     Divide by the length. L treats atomic values like singleton lists.
        S    Sum. This also treats atomic values like singleton lists. Hence this
             monadic chain leaves a single value unchanged but will return the
             mean of a pair.

```

# Answer
> 8 votes
# Actually, 1 byte

Try it online!

# Answer
> 7 votes
# R, 6 bytes

```
median

```

Not surprising that R, a statistical programming language, has this built-in.

# Answer
> 6 votes
# Matlab/Octave, 6 bytes

A boring built-in:

```
median

```

Try it online!

# Answer
> 6 votes
# Octave, 38 bytes

```
@(x)mean(([1;1]*sort(x))(end/2+[0 1]))

```

This defines an anonymous function. Input is a row vector.

Try it online!

### Explanation

```
            sort(x)                 % Sort input x, of length k
      [1;1]*                        % Matrix-multiply by column vector of two ones
                                    % This vertically concatenates sort(x) with
                                    % itself. In column-major order, this effectively
                                    % repeats each entry of sort(x)
     (             )(end/2+[0 1])   % Select the entry at position end/2 and the next.
                                    % Entries are indexed in column-major order. Since
                                    % the array has 2*k elements, this picks the k-th
                                    % and (k+1)-th (1-based indexing). Because entries
                                    % were repeated, for odd k this takes the original
                                    % (k+1)/2-th entry twice. For even k this takes
                                    % the original (k/2)-th and (k/2+1)-th entries
mean(                            )  % Mean of the two selected entries

```

# Answer
> 6 votes
# APL (Dyalog Unicode), 14 bytes

```
≢⊃2+/2/⊂∘⍋⌷÷∘2

```

Try it online!

This is a train. The original dfn was `{(2+/2/⍵[⍋⍵])[≢⍵]÷2}`.

The train is structured as follows

```
┌─┼───┐
≢ ⊃ ┌─┼───┐
    2 / ┌─┼───┐
    ┌─┘ 2 / ┌─┼─┐
    +       ∘ ⌷ ∘
           ┌┴┐ ┌┴┐
           ⊂ ⍋ ÷ 2

```

denotes the right argument.

index

* `⊂∘⍋` the indices which indexed into  results in  being sorted
* `÷∘2` into  divided by 2

`2/` replicate this twice, so `1 5 7 8` becomes `1 1 5 5 7 7 8 8`

`2+/` take the pairwise sum, this becomes `(1+1)(1+5)(5+5)(5+7)(7+7)(7+8)(8+8)`

from this pick

* element with index equal to the length of

Previous solutions

```
{.5×+/(⍵[⍋⍵])[(⌈,⌊).5×1+≢⍵]}
{+/(2/⍵[⍋⍵]÷2)[0 1+≢⍵]}
{+/¯2↑(1-≢⍵)↓2/⍵[⍋⍵]÷2}
{(2+/2/⍵[⍋⍵])[≢⍵]÷2}
{(≢⍵)⊃2+/2/⍵[⍋⍵]÷2}
≢⊃2+/2/2÷⍨⊂∘⍋⌷⊢
≢⊃2+/2/⊂∘⍋⌷÷∘2

```

# Answer
> 5 votes
# MATL, 4 bytes

```
.5Xq

```

This finds the 0.5-quantile, which is the median.

Try it online!

# Answer
> 5 votes
# Pyth - 11 bytes

Finds the average of the middle item taken both backwards and forwards.

```
.O@R/lQ2_BS

```

Test Suite.

# Answer
> 5 votes
# JavaScript, 57 52 bytes

```
v=>(v.sort((a,b)=>a-b)[(x=v.length)>>1]+v[--x>>1])/2

```

Sort the array numerically. If the array is an even length, find the 2 middle numbers and average them. If the array is odd, find the middle number twice and divide by 2.

# Answer
> 4 votes
# Mathematica, 6 bytes

```
Median

```

As soon as I figure out Mthmtca, I'm posting a solution in it.

# Answer
> 4 votes
# Perl 6, 31 bytes

```
*.sort[{($/=$_/2),$/-.5}].sum/2

```

Try it

## Expanded:

```
*\     # WhateverCode lambda ( this is the parameter )

.sort\ # sort it

[{     # index into the sorted list using a code ref to calculate the positions

  (
    $/ = $_ / 2 # the count of elements divided by 2 stored in ｢$/｣
  ),            # that was the first index

  $/ - .5       # subtract 1/2 to get the second index

                # indexing operations round down to nearest Int
                # so both are effectively the same index if given
                # an odd length array

}]\

.sum / 2        # get the average of the two values

```

# Answer
> 4 votes
# TI-Basic, 2 bytes

```
median(Ans

```

Very straightforward.

# Answer
> 4 votes
# , ~~16~~ 14 bytes

```
2%~#{2#/:~+\:~

```

Try it online!

In addition to BMO's array duplication trick, I found that we can add the whole array sorted in two directions. Then I realized that the two steps can be reversed, i.e. add the two arrays, *then* duplicate them and take the `n`th element.

### How it works

```
2%~#{2#/:~+\:~
                Input: array of length n
       /:~      Sort ascending
           \:~  Sort descending
          +     Add the two element-wise
     2#         Duplicate each element
   #{           Take n-th element
2%~             Halve

```

---

# Previous answers

## with `stats` addon, 18 bytes

```
load'stats'
median

```

Try it online!

Library function FTW.

`median`'s implementation looks like this:

## , 31 bytes

```
-:@(+/)@((<.,>.)@(-:@<:@#){/:~)

```

Try it online!

### How it works

```
-:@(+/)@((<.,>.)@(-:@<:@#){/:~)
         (<.,>.)@(-:@<:@#)       Find center indices:
                  -:@<:@#          Compute half of given array's length - 1
          <.,>.                    Form 2-element array of its floor and ceiling
                          {/:~   Extract elements at those indices from sorted array
-:@(+/)                          Sum and half

```

A bit of golfing gives this:

## , 28 bytes

```
2%~[:+/(<.,>.)@(-:@<:@#){/:~

```

Try it online!

# Answer
> 3 votes
# C++ 112 Bytes

Thanks to @original.legin for helping me save bytes.

```
#include<vector>
#include<algorithm>
float a(float*b,int s){std::sort(b,b+s);return(b[s/2-(s&1^1)]+b[s/2])/2;}

```

Usage:

```
    int main()
    {
        int n = 4;
        float e[4] = {1,4,3,2};
        std::cout<<a(e,n); /// Prints 2.5

        n = 9;
        float e1[9] = {1,2,3,4,5,6,7,8,9};
        std::cout<<a(e1,n); /// Prints 5

        n = 13;
        float e2[13] = {1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4};
        std::cout<<a(e2,n); /// Prints 1.5

        return 0;
    }

```

# Answer
> 3 votes
# C#, 126 bytes

```
using System.Linq;float m(float[] a){var x=a.Length;return a.OrderBy(g=>g).Skip(x/2-(x%2==0?1:0)).Take(x%2==0?2:1).Average();}

```

Pretty straightforward, here with LINQ to order the values, skip half the list, take one or two values depending on even/odd and average them.

# Answer
> 3 votes
## Common Lisp, 89

```
(lambda(s &aux(m(1-(length s)))(s(sort s'<)))(/(+(nth(floor m 2)s)(nth(ceiling m 2)s))2))

```

I compute the mean of elements at position `(floor middle)` and `(ceiling middle)`, where `middle` is the zero-based index for the middle element of the sorted list. It is possible for `middle` to be a whole number, like `1` for an input list of size 3 such as `(10 20 30)`, or a fraction for lists with an even numbers of elements, like `3/2` for `(10 20 30 40)`. In both cases, we compute the expected median value.

```
(lambda (list &aux
             (m (1-(length list)))
             (list (sort list #'<)))
  (/ (+ (nth (floor m 2) list)
        (nth (ceiling m 2) list))
     2))

```

# Answer
> 3 votes
# Vim, 62 bytes

I originally did this in V using only text manipulation until the end, but got frustrated with handling \[X\] and \[X,Y\], so here's the easy version. They're about the same length.

```
c$:let m=sort(")[(len(")-1)/2:len(")/2]
=(m[0]+m[-1])/2.0

```

Try it online!

Unprintables:

```
c$^O:let m=sort(^R")[(len(^R")-1)/2:len(^R")/2]
^R=(m[0]+m[-1])/2.0

```

Honorable mention:

* `^O` takes you out of insert mode for one command (the let command).
* `^R"` inserts the text that was yanked (in this case the list)

# Answer
> 3 votes
# Husk, 10 bytes

```
½ΣF~e→←½OD

```

Try it online!

### Explanation

This function uses that the median of \\$\[a\_1 \dots a\_N\]\\$ is the same as the median of \\$\[a\_1 \\; a\_1 \dots a\_N \\; a\_N\]\\$ which avoids the ugly distinction of odd-/even-length lists.

```
½ΣF~e→←½OD  -- example input: [2,3,4,1]
         D  -- duplicate: [2,3,4,1,2,3,4,1]
        O   -- sort: [1,1,2,2,3,3,4,4]
       ½    -- halve: [[1,1,2,2],[3,3,4,4]]
  F         -- fold the following
   ~        -- | compose the arguments ..
     →      -- | | last element: 2
      ←     -- | | first element: 3
    e       -- | .. and create list: [2,3]
            -- : [2,3]
 Σ          -- sum: 5
½           -- halve: 5/2

```

Unfortunately `½` for lists has the type `[a] -> [[a]]` and not `[a] -> ([a],[a])` which doesn't allow `F~+→←` since `foldl1` needs a function of type `a -> a -> a` as first argument, forcing me to use `e`.

# Answer
> 3 votes
# Fig, \\$11\log\_{256}(96)\approx\\$ 9.054 bytes

```
KY
HSt2s{HL

```

Try it online!

-3 chars because bugfixes

```
KY
HSt2s{HL
--------
KY       # First helper function
 Y       # Interleave with self
K        # Sort
-------- # Send the result to the next function:
HSt2s{HL # Main function
     {HL # Compute len(input)/2-1
    s    # Drop that many items from the input
  t2     # Take 2
 S       # Sum
H        # Halve

```

# Answer
> 2 votes
# J, 19 bytes

```
<.@-:@#{(/:-:@+\:)~

```

Explanation:

```
        (        )~   apply monadic argument twice to dyadic function
         /:           /:~ = sort the list upwards
               \:     \:~ = sort the list downwards
           -:@+       half of sum of both lists, element-wise
<.@-:@#               floor of half of length of list
       {              get that element from the list of sums

```

# Answer
> 2 votes
# JavaScript, 273 Bytes

```
function m(l){a=(function(){i=l;o=[];while(i.length){p1=i[0];p2=0;for(a=0;a<i.length;a++)if(i[a]<p1){p1=i[a];p2=a}o.push(p1);i[p2]=i[i.length-1];i.pop()}return o})();return a.length%2==1?l[Math.round(l.length/2)-1]:(l[Math.round(l.length/2)-1]+l[Math.round(l.length/2)])/2}

```

# Answer
> 2 votes
# Java 7, 99 bytes

Golfed:

```
float m(Float[]a){java.util.Arrays.sort(a);int l=a.length;return l%2>0?a[l/2]:(a[l/2-1]+a[l/2])/2;}

```

Ungolfed:

```
float m(Float[] a)
{
    java.util.Arrays.sort(a);
    int l = a.length;
    return l % 2 > 0 ? a[l / 2] : (a[l / 2 - 1] + a[l / 2]) / 2;
}

```

Try it online

# Answer
> 2 votes
# Pari/GP - 37  ~~39~~  Bytes

Let *a* be a rowvector containing the values.

```
b=vecsort(a);n=#b+1;(b[n\2]+b[n-n\2])/2  \\ 39 byte

n=1+#b=vecsort(a);(b[n\2]+b[n-n\2])/2    \\ obfuscated but only 37 byte

```

Since Pari/GP is interactive, no additional command is needed to display the result.

---

For the ***"try-it-online"*** link a line before and after is added. To get printed, the median-result in stored in variable *w*
```
a=vector(8,r,random(999))
n=1+#b=vecsort(a);w=(b[n\2]+b[n-n\2])/2
print(a);print(b);print(w)

```

Try it online!

# Answer
> 2 votes
# Japt, 20 bytes

```
n gV=0|½*Ul)+Ug~V)/2

```

Test it online! Japt really lacks any built-ins necessary to create a really short answer for this challenge...

### Explanation

```
n gV=0|½*Ul)+Ug~V)/2  // Implicit: U = input list
n                     // Sort U.
   V=0|½*Ul)          // Set variable V to floor(U.length / 2).
  g                   // Get the item at index V in U.
            +Ug~V     // Add to that the item at index -V - 1 in U.
                 )/2  // Divide by 2 to give the median.
                      // Implicit: output result of last expression

```

# Answer
> 2 votes
# dc, ~~120~~ 122 bytes

```
9kzsa0si[li:sli1+dsila>A]dsAx[1scddd;sr1-;sli:sr1-:s]sR[lidd1-;sr;s<R1+dsila>S]sS[1si0sclSxlc1=M]dsMxla2/dd1%-;sr.5-;s+2/p

```

Try it online!

*My original code worked for all the provided test cases, but was actually faulty, so +2 bytes for the fix. Dang!*

Lots of bytes since `dc` doesn't have any inbuilt sorting mechanism, and very little in the way of stack manipulation.

`9k` sets the precision to 9 places since we need the possibility of digits past the decimal point. `dc` doesn't float, so hopefully this is satisfactory.

`zsa0si[li:sli1+dsila>A]dsAx` dumps the entirety of the stack into array `s`, and preserves the number of items in register `a`.

Macros `M`, `S`, and `R` all make up a bubble sort. `M` is our 'main' macro, so to speak, so I'll cover that one first.

`[1si0sclSxlc1=M]dsMx` We reset increment register `i` to 1, and check register `c` to 0. We run macro `S`, which is one pass through the array. If `S` (actually, `R`, but `S` by proxy) made any changes, it would have set register `c` to one, so if this is the case we loop through `M` again.

`[lidd1-;sr;s<R1+dsila>S]sS` One pass through the array. We load the increment counter `i`, duplicate it twice, and decrement the top version of it by one. Essentially `i` is always high, so we compare `i` and `i-1`. Load the two values from array `s`, compare them, and if they're going the wrong way we run our swapping macro, `R`. Then we keep on incrementing `i`, comparing it to `a`, and running `S` until that comparison tells us we've hit the end of our array.

`[1scddd;sr1-;sli:sr1-:s]sR` An individual instance of swappery in array `a`. First we set our check register `c` to 1 so that `M` knows we made changes to the array. `i` should still be on the stack from earlier, so we duplicate it three times. We retrieve `i` indexed item from `a`, swap our top-of-stack so that `i` is present again, subtract one from it, and then retrieve that item from `a`. Here we run into a stack manipulation limitation, so we have to load `i` again and we store our previous `i-1` value into that index in `a`. Now we just have our old `i`-indexed `a` value on the stack and `i` itself, so we swap these, subtract 1 from `i`, and replace the value in `a`.

Eventually `M` will stop running when it sees no changes have been made, and now that things are sorted we can do the actual median operation.

`la2/dd1%-;sr.5-;s+2/p` Since `a` already has the length of array `s`, we load it and divide by two. Testing for evenness would be costly, so we rely on the fact that dc uses the floor of a non-whole value for its index. We divide `a` by two and duplicate the value. We then get from `s` the values indexed by (`a`/2-.5) and (`a`/2-((`a`/2)mod 1)). This gives us the middle value twice for an odd number of values, or the middle two values for an even number. `+2/p` averages them and prints the result.

# Answer
> 2 votes
# Java 8, 71 bytes

Parity is fun! Here's a lambda from `double[]` to `Double`.

```
l->{java.util.Arrays.sort(l);int s=l.length;return(l[s/2]+l[--s/2])/2;}

```

Nothing too complex going on here. The array gets sorted, and then I take the mean of two numbers from the array. There are two cases:

* If the length is even, then the first number is taken from just ahead of the middle of the array, and the second number is taken from the position before that by integer division. The mean of these numbers is the median of the input.
* If the length is odd, `s` and `s-1` both divide to the index of the middle element. The number is added to itself and the result divided by two, yielding the original value.

Try It Online

# Answer
> 2 votes
# Jelly, 2 bytes

```
Æṁ

```

Try it online!

# Answer
> 2 votes
# SmileBASIC, 45 bytes

```
DEF M A
L=LEN(A)/2SORT A?(A[L-.5]+A[L])/2
END

```

Gets the average of the elements at floor(length/2) and floor(length/2-0.5) Very simple, but I was able to save 1 byte by moving things around:

```
DEF M A
SORT A    <- extra line break
L=LEN(A)/2?(A[L-.5]+A[L])/2
END

```

# Answer
> 2 votes
# GolfScript, ~~27~~ ~~25~~ ~~20~~ 17 bytes

```
~..+$\,(>2<~+"/2"

```

Takes input as an array of integers on stdin. Outputs as an unreduced fraction. Try it online!

### Explanation

The median of the array, as BMO's Husk answer explains, is equal to the median of an array twice as long where each element is repeated twice. So we concatenate the array to itself, sort, and take the mean of the middle two elements. If the length of the original array is \\$l\\$, the middle two elements of the doubled array are at indices \\$l-1\\$ and \\$l\\$.

```
~                  Evaluate input (converting string -> array)
 ..                Duplicate twice
   +               Concatenate two of the copies
    $              Sort the doubled array
     \,            Swap with the non-doubled array and get its length: l
       (           Decrement: l-1
        >          Array slice: all elements at index (l-1) and greater
         2<        Array slice: first two elements (originally at indices l-1 and l)
           ~       Dump array elements to stack
            +      Add
             "/2"  Push that string
                   Output all items on stack without separator

```

The output will be something like `10/2`.

# Answer
> 2 votes
# *without* using the `median` builtin, 51 bytes

```
function(x,n=sum(x|1)+1)mean(sort(x)[n/2+0:1*n%%2])

```

Try it online!

# Answer
> 2 votes
# Python 3, 59 bytes

```
f=lambda l:l.sort()or(len(l)<3)*(l[0]+l[-1])/2or f(l[1:-1])

```

Try it online!

This is a recursive version:

* the list is sorted
* if there are 1 or 2 elements left, we output the median since 0 and -1 are both first and last with a single or atwo element list
* if not, we remove first and last elements and call f.

# Answer
> 2 votes
# Vyxal, 6 bytes

```
s∆ṁwfṁ

```

Try it Online!

`s`ort the input, get the `∆ṁ`iddle item(s), `w`rap in a list, `f`latten and get the ean of that. (`wf` is needed to handle cases where the list is of odd length)

Or, without a trivial built-in

## Vyxal, 11 bytes

```
L‹½₍⌈⌊$s$İṁ

```

Try it Online!

## Explained

```
L‹½₍⌈⌊$s$İṁ
L‹         # Length of the input - 1 (this accounts for 0 indexing)
  ½        # halved
   ₍⌈⌊      # a list of the ceiling and floor of that number
     $s    # the input list sorted
       $İ  # indexed at the positions in the ceil,floor list
         ṁ # take the average of that

```

# Answer
> 1 votes
## Racket 113 bytes

```
(let*((L(sort L >))(n(length L))(r list-ref))(if(odd? n)(r L(floor(/ n 2)))(/(+(r L(-(/ n 2)1))(r L(/ n 2)))2)))

```

Ungolfed:

```
(define (median L)
  (let* ((L (sort L >))
         (n (length L))
         (lr list-ref))
    (if (odd? n)
        (lr L (floor (/ n 2)))
        (/(+ (lr L (sub1(/ n 2)))
             (lr L (/ n 2)))
          2))))

```

Testing:

```
(median '(1 2 3))
(median '(1 2 3 4))

```

Output:

```
2
2 1/2

```

# Answer
> 1 votes
# T-SQL, ~~101~~ 67

```
DECLARE @ table(i real)
INSERT @ values(1),(3),(20),(4)

SELECT top 1PERCENTILE_CONT(.5)WITHIN GROUP(ORDER BY i)OVER()FROM @

```

**Try it out**

# Answer
> 1 votes
## Clojure, 65 bytes

```
#(/(apply +(take 2(drop(-(count %)1)(sort(for[c % i[0 1]]c)))))2)

```

An other approach I tried:

```
#(apply +(map *(for[i(range)](get{-2 0.5 -1 1 0 0.5}(-(* i 2)(count %))0))(sort %)))

```

# Answer
> 1 votes
## CJAM - 21

```
q~]$__,2/=\_,(2/=+2d/

```
* `q~]` reads input to array
* `$__` sorts it and makes 2 copies
* `,` gets length of array
* `2/` divides that by 2 rounded down
* `=` finds the number at that index
* `/_` puts original array at top of stack and copies it
* `,(` gets length of array - 1
* `2/` divides that by 2 rounded down
* `=` finds the number at that index
* `+` adds the two array elements extracted `2d/` divides them by 2 as a double (so no rounding)

If the number of array elements N is odd, floor(N/2) = floor((N-1)/2). If N is even the two center elements are selected and the mean is found.

Longer but working alternative strategies:

```
q~]$__,2/)<_,@W%<&_:+\,d/
q~]$:A,2/_(A,2%$A=@A=+2d/\;
q~]$_Vf*_,2/.5t_W%.+.*:+

```

# Answer
> 1 votes
# Haxe, 104 bytes

Not amazing, what with the `function` keywords and a mandatory sorting function …

```
function f(l,?a)return(l[(a={l[0]+=.0;l.sort(function(x,y)return x>y?1:-1);l.length;})>>1]+l[a-1>>1])/2;

```

With some whitespace:

```
function f(l, ?a)
  return (
      l[(a = {
          l[0] += .0;
          l.sort(
               function(x, y) return x > y ? 1 : -1
             );
          l.length;
        }) >> 1]
      + l[a - 1 >> 1]
    ) / 2;

```

I used `l[0]+=.0;` to let Haxe know the type of `l`. The alternative would be `l:Array<Float>` in the arguments. Then `l` is sorted, its length is stored in `a`, and then we basically do `(l[a / 2] + l[(a - 1) / 2]) / 2`.

# Answer
> 1 votes
# Swift, 93 bytes

```
let m:([Double])->Double={{c,s in c%2==0 ?(s[c/2-1]+s[c/2])/2:s[c/2]}($0.count,$0.sorted())}

```

This takes about 10 seconds to compile on my machine but it works. It declares the constant `m` of type `[Double] -> Double`.

# Answer
> 1 votes
# 8th, ~~108~~ ~~105~~ 93 bytes

```
: m ' n:cmp a:sort a:len 2 n:/mod swap not if n:1- 2 a:slice a:open n:+ 2 n:/ else a:@ then ;

```

**SED** (Stack Effect Diagram) is `a -- a n`

**Test**

```
[1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] m .

```

**Output**

```
1.50000

```

**Ungolfed version** (with comments)

```
\ Median
: m \ a -- a n
    ' n:cmp a:sort \ Sort array
    a:len          \ Get array length
    2 n:/mod       \ Remainder and quotient
    swap           \ Remainder on TOS
    not if
        \ Array contains an even number of items
        \ Get arithmetic mean of the two values closest to the center of the sorted list
        n:1- 2 a:slice a:open n:+ 2 n:/
    else
        \ Array contains an odd number of items
        \ Get the central value
        a:@
    then ;

```

# Answer
> 1 votes
# C#, 75 bytes

```
a=>{Array.Sort(a);int m=a.Length;return m%2>0?a[m/2]:(a[m/2-1]+a[m/2])/2;};

```

An anonymous function which computes the median.

Full program with ungolfed method and test cases:

```
using System;

public class Program
{
    public static void Main()
    {
        Func<double[],double> f =
        a =>
        {
            Array.Sort(a);  // built-in sort function for arrays
            int m = a.Length;   // stores the number of elements from the array
            return m % 2 > 0 ? a[m/2] : ( a[m/2-1] + a[m/2] ) / 2;
            // if the array has an odd number of elements, the central number will be returned
            // otherwise, the average of the two central elements
        };

        // test cases:
        Console.WriteLine(f(new double[]{1,2,3,4,5,6,7,8,9}));  // 5
        Console.WriteLine(f(new double[]{1,4,3,2}));    // 2.5
        Console.WriteLine(f(new double[]{1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4}));  // 1.5
    }
}

```

# Answer
> 1 votes
# PHP, ~~70~~ 77 bytes

Not exactly optimal but works.

Requires that the values are passed over GET.

```
<?sort($_GET);die(($C=count($G=$_GET))&1?$G[~-$C/2]:($G[$C/2]+$G[$C/2-1])/2);

```

The result will be displayed in the browser and as the return code.

---

Thanks to Titus for fixing it, at the cost of 7 bytes.

# Answer
> 1 votes
Ruby 50 48 Bytes

*-2 bytes thanks to @Conor O'Brien*

```
->(l){l.sort!;e=l.length;(l[~-e/2]+l[e/2])/2.0}

```

# Answer
> 1 votes
# Racket, 95 bytes

Using the trusty old `match` syntax. The pattern `(list _ m ... _)` matches the middle of a list (that is, it omits the first and last element).

```
(λ(l)(let f([l(sort l <)])(match l[(list x)x][(list x y)(/(+ x y)2)][(list _ m ... _)(f m)])))

```

## Ungolfed

```
(λ (l)
  (let f ([l (sort l <)])
    (match l
      [(list x) x]
      [(list x y) (/ (+ x y) 2)]
      [(list _ m ... _) (f m)])))

```

# Answer
> 1 votes
# Perl 5, 58 + 2 (-ap) = 60 bytes

```
$_=(@F=sort{$a<=>$b}@F)%2?@F[@F/2]:@F[@F/2]/2+@F[@F/2-1]/2

```

Try it online!

Input is split into the @F array by the '-a' flag. @F gets sorted. Then, its length is checked to see if it is odd or even. If odd, result is the middle element. If even, result is half of the element to the left of middle plus half of the element to the right of the middle.

# Answer
> 1 votes
## Julia 0.6.0 (9 bytes) (6 bytes)

`median(a)`

`median`

where `a` is an array. It's not a very exciting answer but it's cool that Julia has a built in function for the median.

edit: I didn't know I could just write median!

# Answer
> 1 votes
# APL, 26 bytes

```
{3>≢⍵:(+/÷≢)⍵⋄∇1↓¯1↓⍵[⍋⍵]}

```

Try it online!

### How?

* `3>≢⍵:(+/÷≢)⍵` \- if the length of the array is less then 3, return the average
* \- otherwise
* `∇1↓¯1↓⍵[⍋⍵]` \- return the sorted array with the first and last elements removed.

# Answer
> 1 votes
# GolfScript, 44 bytes

```
~$.,:l;~l 2%{l 2/$}{{l 2/$}2*+'/2'+}if{\;}l*

```

Try it online!

Explanation

```
~$.,:l;~l 2%{l.2/-}{{l 2/$}2*+'/2'+}if{\;}l*   |
~                                              Create array from input string
 $                                             Sort array
  .                                            Duplicate array
   ,                                           Pop and count the top array
    :l                                         Assign variable l
      ;                                        Pop
       ~                                       Convert array into individual integers
        l                                      Push variable l onto stack
          2%                                   Push 2 and perform mod
            {l 2/$}                            If block
            {l 2/                              push variable l and divide by 2
                 $}                            Copy/push value at index (push(stack[pop()]))
                   {{l 2/$}2*+'/2'+}           Else block
                    {l 2/                      Push l/2
                         $}                    Copy
                           2*                  Perform block {} twice
                             +                 Add top two of stack (result of copies)
                              '/2'+}if         Push and add '/2'. End if
                                      {\;}     New block. Swap top two elements then pop
                                          l*   Perform previous block l times

```

# Answer
> 1 votes
# k, 23 bytes

Basically a slightly golfed version of `q`'s canonical `med` in k.

```
{avg x(<x)@_.5*-1 0+#x}

```

# Answer
> 1 votes
# Haskell 1.2 (Gofer), 44 bytes

```
f[x]=x
f[x,y]=(x+y)/2.0
f(x:y)=f.init$sort y

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
Åm

```

Try it online or verify all test cases.

No need for an explanation, since `Åm` is a builtin which will:

> Median. Sorts the list, then returns either the middle element or the average of the middle elements depending on the parity of the length of the list.

# Answer
> 1 votes
# Lua, ~~64~~ 63 bytes

```
function f(t)table.sort(t)h=#t//2return(t[h+1]+t[h+#t%2])/2 end

```

Try it online!

Sort table, get the position halfway through the table by integer-dividing table length by two, return average of element at half position plus one and element at half position if table length is even, else at half position plus one.

This solution is only valid in Lua 5.3 and onwards where there is integer division, `//` (and where integers can be squished right next to the keyword `return`). In Lua 5.1, the equivalent is `math.floor(a/b)`, which would add several bytes.

# Answer
> 1 votes
# Tcl, 100 bytes

```
proc M L {expr ([lindex [set S [lsort -r $L]] [set h [expr [llength $L]/2]]]+[lindex $S end-$h])/2.}

```

Try it online!

---

~~Tcl, 97 bytes
```
proc M L {expr ([lindex [set S [lsort $L]] [set h [expr [llength $L]/2]]]+[lindex $S end-$h])/2.}

```
Try it online!
~~

##

~~Tcl, 123 bytes
```
proc M L {set I [lindex [set S [lsort $L]] [expr [set n [llength $L]]/2]]
expr {$n%2?$I:($I+[lindex $S [expr $n/2-1]])/2.}}

```
Try it online!
~~

##

~~Tcl, 124 bytes
```
proc M L {set n [llength [set S [lsort $L]]]
set I [lindex $S [expr $n/2]]
expr {$n%2?$I:($I+[lindex $S [expr $n/2-1]])/2.}}

```
Try it online!
~~

##

~~Tcl, 133 bytes
```
proc M L {proc G L\ i {lindex $L [expr $i]}
expr {[set n [llength [set S [lsort $L]]]]%2?[G $S $n/2]:([G $S $n/2]+[G $S $n/2-1])/2.}}

```
Try it online!
~~

##

~~Tcl, 135 bytes
```
proc M L {expr {[set n [llength [set S [lsort $L]]]]%2?[lindex $S [expr $n/2]]:([lindex $S [expr $n/2]]+[lindex $S [expr $n/2-1]])/2.}}

```
Try it online!
~~

~~Still very ungolfed, my first minimum viable product!~~

# Answer
> 1 votes
# Arn, ~~13~~ 12 bytes

Version: **1.1.5**

```
Iõå)n├┼U■¨Mõ

```

# Explained

Unpacked: `z&:}+\$.:<:_&:-`

```
z&               Zip array with itself, bind to the following
  :_             Flatten
    :<           Sort ascending
      $.         Split in half
        :}+\     Fold with `:}+`.
            &:-  Bind the half symbol to the expression

```

How `:}+\` works: Takes the last element of the first array and adds to the second array, which is casted to the first element of that array automatically (finally, that feature actually is useful!).

Where a symbol needs to take a value but none is provided, `_` is inserted, the implied variable. Ungolfed this looks like

```
( _ z _ ) & ( :}+\ ( $. ( :< ( _ :_ ) ) ) ) & ( :- _ )

```

# Arn, the boring way, 3 bytes

```
med

```

Built in function, can't be compressed.

# Answer
> 1 votes
# Pip, 16 bytes

```
SN:g(CHg+Rgoi)/2

```

Try It Online!

### Explanation

```
SN:g(CHg+Rgoi)/2
   g              List of command-line arguments
SN:               Sort it (using numeric comparison) in-place
       g          Take that sorted list
        +         Add it (element-wise) with
         Rg       Its reverse
     CH           Chop into two halves (if odd length, second half is longer)
    (      oi)    Select the item at index 0 of the sublist at index 1 (o=1, i=0)
              /2  Divide it by 2

```

# Answer
> 1 votes
# Thunno 2, 1 byte

Attempt This Online!

Built-in.

## Thunno 2, 11 bytes

```
l⁻½çṃN$Ṡsim

```

Attempt This Online!

Non built-in.

#### Explanation

```
l⁻½çṃN$Ṡsim  # Implicit input
l⁻           # Length of input, decremented
  ½          # Halve this number
   ç         # Parallelly apply:
    ṃ        #  Ceiling
     N       #  Floor
      $Ṡ     # Input list sorted
        si   # Index into this list
          m  # Mean of this list
             # Implicit output

```

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

-5 Inspired by Luis Mendos Octave answer.

```
lambda x:sum(sorted(x+x)[(n:=~len(x)):-n])/2

```

Try it online!

# Answer
> 0 votes
# APL(NARS), 31 chars, 62 bytes

```
{2÷⍨x[⌊k]+(⌈k←2÷⍨1+≢⍵)⌷x←⍵[⍋⍵]}

```

test

```
  t←{2÷⍨x[⌊k]+(⌈k←2÷⍨1+≢⍵)⌷x←⍵[⍋⍵]}
  t 5 4 3 2 1
3
  t 4 3 2 1
2.5
  t 5 40 30 2 1
5
  t 5 40 30 2
17.5
  35÷2
17.5
   t ,80
80
  t 9 3 4 8 7 6
6.5

```

# Answer
> 0 votes
# BQN, 20 bytes

```
{2÷˜(≠)⊑»+˝˘2↕2/∧}

```

Try it!

# Answer
> 0 votes
# Factor, 6 bytes

```
median

```

Try it online!

# Answer
> 0 votes
# Pyt, 1 byte

Try it online!

Gotta love built-ins

# Answer
> 0 votes
# Thunno, \\$ 2 \log\_{256}(96) \approx \\$ 1.65 bytes

```
Aa

```

Attempt This Online!

Built-ins FTW!

# Answer
> 0 votes
# JavaScript, 63 bytes

```
a=>(l=a.sort((k,v)=>k-v).length/2,l*2%2?a[l|0]:(a[l]+a[l-1])/2)

```

Try it online!

# Answer
> 0 votes
# Nekomata, 8 bytes

```
,o;↔ᶻÐlµ

```

Attempt This Online!

A port of @ბიმო's Husk answer.

```
,           Join two copies of the input
 o          Sort
  ;         Split into two parts
   ↔        Reverse the second part
    ᶻÐ      Zip the two parts into a list of pairs
      l     Take the last pair
       µ    Take the mean

```

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


title: Cover up zeroes in a list

text:
# Question
Title: Cover up zeroes in a list
Inspired by this SO question

As input you will be given a non-empty list of integers, where the first value is guaranteed to be non-zero. To construct the output, walk from the start of the list, outputting each non-zero value along the way. When you encounter a zero, instead repeat the value you most recently added to the output.

You may write a program or function, and have input/output take any convenient format which does not encode extra information, as long as is still an ordered sequence of integers. If outputting from a program, you may print a trailing newline. Except for this trailing newline, your output should be an acceptable input for your submission.

The shortest code in bytes wins.

## Test Cases

```
[1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9] -> [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9]
[1, 0, 0, 0, 0, 0] -> [1, 1, 1, 1, 1, 1]
[-1, 0, 5, 0, 0, -7] -> [-1, -1, 5, 5, 5, -7]
[23, 0, 0, -42, 0, 0, 0] -> [23, 23, 23, -42, -42, -42, -42]
[1, 2, 3, 4] -> [1, 2, 3, 4]
[-1234] -> [-1234]

```

# Answer
> 19 votes
# Pyth, 6 bytes

```
mJ|dJQ

```

Demonstration

`m ... Q` means this maps a function over the input. The function being mapped is `J|dJ`. That means `J = d or J` in Python, since `J` is implicity assigned to the following value on first use. Unlike Python, assignment expressions return the value assigned in Pyth, so the map returns each successive value of `J`, as desired.

# Answer
> 25 votes
# Jelly, 3 bytes

```
o@\

```

Try it online!

### How it works

```
o      Take the logical OR of its arguments.
 @     Reverse the argument order of the link to the left.
  \    Do a cumulative reduce, using the link to the left.

```

# Answer
> 19 votes
## Ruby, 25 bytes

```
->a{a.map{|x|x==0?a:a=x}}

```

This is actually really evil.

Specifically, the snippet `x==0 ? a : (a=x)`.

If I had used any other variable name for `a` (the previous nonzero value)—let's say `y`—I would have to declare it outside the `map` (because `y=x` would only have a scope of inside that single `map` iteration). That would use four chars more (`y=0;`).

But if I use the variable name `a`... yep, you guessed it. I'm actually reassigning to *the argument that we got as input* (the original array).

`map` doesn't care because it only cares about the *original* value of the thing its being called on, so this actually works.

# Answer
> 18 votes
## Haskell, 21 bytes

```
a%0=a
a%b=b
scanl1(%)

```

The (anonymous) function we make is in the last line. The first two lines define a helper function.

```
scanl1(%) [1,0,2,0,7,7,7,0,5,0,0,0,9]
[1,1,2,2,7,7,7,7,5,5,5,5,9]

```

The binary function `%` outputs the second argument, unless it's `0`, in which case it outputs the first argument instead. `scanl1` iterates this function over the input list, outputting the result at each step.

# Answer
> 13 votes
## J, 8 bytes

```
{:@-.&0\

```

This is a unary function, invoked as follows.

```
   f =: {:@-.&0\
   f 2 0 0 4 0 _1 0
2 2 2 4 4 _1 _1

```

## Explanation

```
{:@-.&0\
       \  Map over non-empty prefixes:
   -.      remove all occurrences
     &0    of the number 0 and
{:@        take the last element.

```

# Answer
> 13 votes
# Sed, 8

```
/^0$/g
h

```
* `/^0$/` matches a zero on a line - if so `g` copies the hold space to the pattern space
* `h` copies the pattern space to the hold space

Integers are newline separated. e.g:

```
$ printf -- "-1\n0\n5\n0\n0\n7\n" | sed -f zerocover.sed
-1
-1
5
5
5
7
$

```

# Answer
> 11 votes
# Javascript ES6, 19 bytes

```
s=>s.map(i=>p=i||p)

```

Straightforward solution, loop through input, assign `p` to current element `i` or to `p` if `i` is `0` and output it.

Example run (assigning anonymous function to `f`):

```
>> f([1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9])
<< Array [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9]

```

# Answer
> 9 votes
## Dyalog APL, ~~12~~ ~~10~~ 9 bytes

```
(⊃0~⍨,⍨)\

```

Inspired by @Zgarb's J answer.

```
(⊃0~⍨,⍨)\      Monadic function:
        \      Cumulative reduce by
(⊃0~⍨,⍨)       the dyadic function:
     ,⍨           Arguments concatenated in reverse order
  0~⍨             With zeroes removed
 ⊃                Take the first element

```

Try it here.

# Answer
> 7 votes
## Retina, 15 bytes

```
+`(\S+) 0
$1 $1

```

Try it online.

Repeatedly replaces a number followed by a zero with twice that number until the string stops changing.

# Answer
> 7 votes
## Java, 78

```
int[]f(int[]a){for(int i=-1,b=i;++i<a.length;a[i]=b=a[i]==0?b:a[i]);return a;}

```

Here we just keep track of the last non-zero and shove it in where appropriate. Seems like the obvious way to do it.

# Answer
> 6 votes
## Python 2, 29 bytes

```
while 1:x=input()or x;print x

```

Takes input as numbers given one per line, and outputs in the same format. Terminates with error after finishing.

Using the short-circuiting nature of `or`, the variable `x` is updated to the input, unless that input is 0 (which is Falsey), in which case it remains its current value. Then, `x` is printed. Note that since the first list value is nonzero, `x` is not evaluated in the right hand side before it is assigned.

# Answer
> 6 votes
## Pyth, 8 bytes

```
t.u|YNQ0

```

Uses `.u` (cumulative reduce) by `|` (Python's `or`), with base case 0.

# Answer
> 6 votes
# Prolog (SWI), 54 bytes

```
[X,0|T]+[X,X|Y]:-[X|T]+[X|Y].
[X|T]+[X|Y]:-T+Y.
[]+[].

```

Try it online!

## Explanation

I'm really happy with this answer.

First we say that the empty list is the solution of the empty list:

```
[]+[].

```

Then we say that `[X,X|Y]` is the solution of `[X,0|T]`, if by removing the second entry of each of the remaining solutions.

```
[X,0|T]+[X,X|Y]:-[X|T]+[X|Y].

```

Lastly we say that any thing left over is valid if they start with the same value and the rest of the the two lists match each other.

If that explanation isn't working for you here is the code translated into Haskell:

```
g(a:0:x)=a:g(a:x)
g(a:x)=a:g x
g x=x

```

Try it online!

# Answer
> 5 votes
# Japt, ~~8~~ 7 bytes

```
N£U=XªU

```

Pretty simple. Takes input separated by commas. Try it online!

### Ungolfed and explanation

```
N£    U=Xª U
NmXYZ{U=X||U

        // Implicit: N = input, U = first item
NmXYZ{  // Map each item X to:
U=Z||U  //  Set U to (X || U) and return.
        //  If X is non-zero, this sets U to X.
        //  Otherwise, this leaves U as the last non-zero we've encountered.
        // Implicit: output last expression

```

**4-byte** version:

```
Nå!ª

```

Explanation:

```
Nå!ª
Nå!||
NåXY{Y||X}

        // Implicit: N = input, U = first item
NåXY{   // Cumulatively reduce N; take each item Y and prev value X,
Y||X}   //  and return Y if it is non-zero; return X otherwise.
        // Implicit: output last expression

```

Try it online!

# Answer
> 5 votes
# Mathematica 38 bytes

Pattern matching repeatedly replaces `...a,0,...` with `...a,a...`

```
#//.{b___,a_/;a!=0,0,e___}:>{b,a,a,e}&

```

# Answer
> 5 votes
# Matlab, 41 ~~46~~ bytes

This is inspired in my original answer, with the following differences:

1. Use logical indexing instead of `nonzeros`.
2. Double logical negation instead of comparing with `0`.
3. The transpose can be removed, as the output format is flexible
4. Removing an intermediate variable.

Thanks to Tom Carpenter for item 4, and for his suggestion to use a program instead of a function; together these allowed a reduction of 5 bytes.

```
x=input('');u=x(~~x);disp(u(cumsum(~~x)))

```

Example:

```
>> x=input('');u=x(~~x);disp(u(cumsum(~~x)))
[4 0 3 2 0 5 6 0]
     4     4     3     2     2     5     6     6

```

# Answer
> 5 votes
# Gol\>\<\>, 8 bytes

```
IE;:Z~:N

```

Input and output are newline separated numbers.

Explanation:

```
I         push next integer to stack
 E;       halt if EOF
   :Z~    remove top stack element if 0
      :N  print top stack element while also keeping it on the stack
          wrap around code implicitly

```

Try it online here.

# Answer
> 4 votes
# GolfScript, 10 bytes

```
~{1$or}*]`

```

This program takes input from stdin, in the form of a GolfScript array literal (e.g. `[1 0 2 0]`), and writes its output to stdout in the same format (e.g. `[1 1 2 2]`).

Try it online.

A function (taking and returning a GolfScript array) would be three bytes longer, due to the need to wrap it in a block and assign it to a symbol:

```
{[{1$or}*]}:f

```

Of course, if only the function *body* (i.e. `[{1$or}*]`) is counted, then I can actually save one byte compared to the stand-alone program.

# Answer
> 4 votes
## Minkolang 0.14, ~~12~~ 10 bytes

```
$I?.nd?xdN

```

Try it here. Input can be given as in the question, but **without brackets**.

### Explanation

```
$I      Push the length of the input on the stack.
  ?.    If this is 0, stop. Otherwise, continue.

nd        Take number from input and duplicate it.
  ?x      If this number is 0, dump the top of stack.
    dN    Duplicate the top of stack and output as number

```

Minkolang is toroidal, so this loops around to the beginning and keeps going until it hits the `.` and stops.

# Answer
> 4 votes
# R, ~~39~~ ~~37~~ 33 bytes

```
function(x)zoo::na.locf(x*(x|NA))

```

This is an unnamed function that accepts a vector and returns a vector. It requires the `zoo` package to be installed. Note that it doesn't require `zoo` to be attached to the namespace since we're referencing it directly.

The name for this operation in the world of statistics is LOCF imputation, where LOCF stands for Last Observation Carried Forward. To accomplish this in R, we can use `na.locf` from the `zoo` package, which replaces `NA` values with the last known non-`NA` value. We just have to replace the zeros in the input with `NA`s first.

To do that, we use `x|NA`, which will be `TRUE` when `x != 0` and `NA` otherwise. If we multiply this by `x`, the `TRUE` elements are replaced by the corresponding elements of `x` and the `NA`s stay `NA`, thereby replacing all zeros. This is then passed to `zoo::na.locf` which gives us exactly what we want.

Saved 4 bytes thanks to flodel!

# Answer
> 4 votes
# , 31 bytes

```
[[I',T%T/]{n#}d]{n.{:V}{;V}?}d]

```

This takes an input separated by `,` and outputs the same list in `[]`.

```
7,0,3,0,0,2,-50,0,0 => [7,7,3,3,3,2,-50,-50,-50]

```

Explanation:

```
[                             ] Put result into array
 [I',T%T/]{n#}d]                Format input into array of numbers
                {n.{:V}{;V}?}d  Fill in zeros (see below for how this works)

```

# 17 bytes

```
I~]{n.{:V}{;V}?}d

```

Takes input as a list of numbers separated by spaces using postfix notation and can only handle single digit hexadecimal numbers. Negatives are postfixed with `_`.

```
5 4 0 0 1 0 0 => 5 4 4 4 1 1 1
A 3 0 0 1 B 0 => 10 3 3 3 1 11 11
67* 0 0 78* 0 => 42 42 42 56 56
67*_ 4 3_ 0 0 => -42 4 -3 -3 -3

```

Explanation:

```
I~]               Puts input into integer array
   {           }d For each number in the input
    n.{;V}{:V}?   If the number is 0, push V
                  If not, set V to the number

```

# Answer
> 4 votes
# , 7 chars / 12 bytes

```
ïⓜa=$⋎a

```

`Try it here (Firefox only).`

## Explanation

```
        // implicit: ï = input array
ïⓜ     // map over input
  a=    // set a to:
    $   // (if element is truthy (not 0)) element itself
     ⋎a // else whatever a was set to before
        // implicit output

```

# Answer
> 4 votes
## R, 36 bytes

```
function(x)x[cummax(seq(a=x)*(!!x))]

```

Let's see how this works using `x=`

```
c(1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9)

```

as an example. Here, `!!x` will be the logical (True/False) vector:

```
c(T, F, T, F, T, T, T, F, T, F, F, F, T)

```

Also, `seq(a=x)` gives a vector of indices as long as `x`:

```
c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

```

We multiply both, giving:

```
c(1, 0, 3, 0, 5, 6, 7, 0, 9, 0, 0, 0, 13)

```

We take the cumulative maximum:

```
c(1, 1, 3, 3, 5, 6, 7, 7, 9, 9, 9, 9, 13)

```

Finally, we use that last vector as the indices to extract from `x`:

```
c(1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9)

```

# Answer
> 4 votes
# Rust, 100 bytes

```
fn f(i:&[i64])->Vec<i64>{let(mut o,mut l)=(i.to_vec(),0);
for x in&mut o{if *x==0{*x=l}else{l=*x}};o}

```

Stumbled across this challenge, thought I'd try it in my favorite language. Tried using `[T]::windows_mut()` at first, before finding out that it doesn't exist. And it might've actually been longer than this. Anyway, it turns out that golfed Rust is very ugly and very not-competitive (especially with all those goshdarned esoterics!)1

The newline isn't included in the bytecount; it's only there so you don't have to scroll sideways. It doesn't change the meaning of the code.

Ungolfed:

```
fn cover_zeroes(input: &[i64]) -> Vec<i64> {
    let mut output = input.to_vec();
    let mut last_nonzero = 0;
    for item in &mut output {
        if *item == 0 {
            *item = last_nonzero;
        }
        else {
            last_nonzero = *item;
        }
    }
    output
}

```

\[1\] At least it's not as bad as Java.

# Answer
> 4 votes
# Husk, 2 bytes

```
G|

```

Try it online!

scan from left with or.

# Answer
> 3 votes
# CJam, 11 bytes

```
q~{1$e|}*]p

```

Try it online.

### How it works

```
q~             Read and evaluate all input.
  {    }*      Fold; for each element but the first:
   1$e|          Copy the previous element and take their logical OR.
         ]p   Wrap all results in an array and print it.

```

# Answer
> 3 votes
## Powershell, 32 bytes

```
param($x)$x|%{($t=($_,$t)[!$_])}

```

`$x|%{...}` does the script block for each element in `$x`. `($_,$t)` is an array of current element and `$t`, and `[!$_]` means that we use `!$_` to index into the array. The index will be `0` (false) for non-zero elements and `1` (true) when current element is zero, so `$t` will be either current element or `$t`. The parentheses surround the assignment expression so its value is emitted. Without parantheses it would be just a "quiet" assignment to `$t`.

# Answer
> 3 votes
# Milky Way 1.2.1, 33 bytes

```
:y;=<:&{~<?{0b_^;:3≤_;}1-}^<Ω!

```

This assumes that the list of integers is solely on the stack.

---

### Explanation

```
:    : :           :              # duplicate the TOS
 y                                # push the length of the TOS
  ;               ;    ;          # swap the TOS and STOS
   =                              # dump a list to the stack
    < <    <                 <    # rotate the stack leftward
        &{~                }      # while loop
            ?{  _     _ }         # if-else statements
              0     3    1        # push an integer
               b                  # == on the TOS and STOS
                 ^          ^     # pop the TOS without output
                     ≤            # rotate the top N stack elements leftward
                          -       # subtract the TOS from the STOS
                              Ω   # push a list made of the top N stack elements
                               !  # output the TOS

```

# Answer
> 3 votes
# Julia, 33 bytes

```
g(x,a=0)=[(i!=0&&(a=i);a)for i=x]

```

This is a function `g` that accepts an array and returns an array. We start a temporary variable `a` at 0. For each element `i` of the input, if `i` isn't 0 then we assign `a` to `i`. If `i` is 0, `a` doesn't change at that iteration. We use `a` as the value in that position in the output array.

# Answer
> 3 votes
## Perl 6, 21 bytes

```
*.map: {$_=($^a||$_)}

```

usage:

```
# store the Whatever lambda as a subroutine
# just so that we don't have to repeat it
my &code = *.map: {$_=($^a||$_)}

say code [1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9];
# (1 1 2 2 7 7 7 7 5 5 5 5 9)

say [-1, 0, 5, 0, 0, -7].&code;
# (-1 -1 5 5 5 -7)

say ([1, 0, 0, 0, 0, 0],[-1, 0, 5, 0, 0, -7]).map: &code;
# ((1 1 1 1 1 1) (-1 -1 5 5 5 -7))

```

# Answer
> 3 votes
# Japt, 3 bytes

```
å!ª

```

Try it

```
å!ª     :Implicit input of array
å       :Cumulatively reduce
 !      :Flip the arguments
  ª     :Logical OR

```

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
εĀiyU}X

```

Try it online!

My first try, using 05AB1E

```
ε       for each y in input
  Āi    if > 0
    yU  save current value in X
  }
  X     push X
        implicitly close for-loop and print list

```

# Answer
> 3 votes
# Perl 6, 16 bytes

```
*.map($ [R||]=*)

```

Try it online!

Maps each element to the reverse logical OR with the previous calculated element. I wish I could do something like `{[\R||] $_}` but the `R` operator doesn't quite work that way.

# Answer
> 3 votes
# Zsh, 21 bytes

```
for i;echo $[n=i?i:n]

```

Try it online!

We use `echo` instead of `<<<` because we need to set `n`. Using `<<<$[n=i?i:n]` expands `$[n=i?i:n]` in a subshell, which will prevent `n` from ever being set.

# Answer
> 3 votes
# k4, 15 bytes

```
{^\?[0=x;0N;x]}

```

---

```
   ?[        ]  / vector conditional ?[cond;true;false]; eg ?[010b;2 2 2;3 3 3] -> 3 2 3
 ^\             / fills nulls (0N) with preceding value

```

# Answer
> 3 votes
# Prolog (SWI), 44 bytes

```
f(0,B,B).
f(A,_,A).
X*O:-scanl(f,X,0,[_|O]).

```

Try it online!

# Answer
> 3 votes
# Arturo, ~~32~~ 29 bytes

```
$=>[0map&'x->(0=x)?[<=]-><=x]

```

Try it

```
$=>[          ; a function where input is assigned to &
    0         ; push 0 to stack
    map&'x->  ; map over input, assign current elt to x
    (0=x)?    ; is the current element zero?
    [<=]      ; then duplicate top of stack
    ->        ; otherwise,
        <=x   ; push x and duplicate it
]             ; end function

```

# Answer
> 3 votes
# Thunno 2, 3 bytes

```
Ʋs|

```

Attempt This Online!

#### Explanation

```
Ʋs|  # Implicit input
Ʋ    # Cumulative reduce by:
 s|  #  Swapped logical OR
     # Implicit output

```

# Answer
> 3 votes
# Nekomata, 4 bytes

```
pZ‼l

```

Attempt This Online!

Find the last nonzero element in each prefix of the input array.

```
pZ‼l
p       For each prefix:
 Z‼     Remove zeros
   l    Last element

```

# Answer
> 2 votes
# Arcyóu, 44 bytes

```
(F(L)(f x(_(_ L))(L((F(i)(?(L i)i($([ i))))x

```

This is an anonymous function taking one argument.

Explanation:

```
(F(L)               ; Anonymous function F(L)
  (f x (_ (_ L))    ; For x in range(len(L))
    (L              ; Implicit indexing
      (F(i)         ; Anonymous function F(i)
        (? (L i)    ; If L[i] is not 0:
          i         ; Return i; otherwise:
          ($ ([ i)) ; Recurse ($) with i decremented
        )           ; Then, we call this new function on x
      )             ; And use the return value as the index from line 3
      x             ; No final close-parens

```

# Answer
> 2 votes
## Labyrinth, 21 bytes

The top half seems a bit wasteful, but I'm not sure what to do about it...

```
""?"
" #"
;  ;
,\!:
@

```

I/O via linefeed-delimited lists.

Try it online.

The idea is to keep the last printed thing on the stack and discard zeroes whenever we find them.

# Answer
> 2 votes
# Mathematica, ~~28~~ ~~27~~ 25 bytes

Saved 2 bytes thanks to Martin Büttner.

```
If[#2==0,##]&~FoldList~#&

```

# Answer
> 2 votes
# C 45 Bytes

```
#define F(a,s) while(s--) *a=*a?*a++:*(a++-1)

```

## Here's my test program

Go easy as it's my first try at code golf.

```
#include <stdio.h>

#define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0]))
#define F(a,s) while(s--) *a=*a?*a++:*(a++-1)

void printSolutions(int * solutions, int size)
{
  do {
    printf("%d ", *solutions++);
  } while (--size > 0);
  printf("\n");
}

int main(int argc, char * argv[])
{
  static int testCase1[] = {1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9};
  static int testCase2[] = {1, 0, 0, 0, 0, 0};
  static int testCase3[] = {-1, 0, 5, 0, 0, -7};
  static int testCase4[] = {23, 0, 0, -42, 0, 0, 0};
  static int testCase5[] = {1, 2, 3, 4};
  static int testCase6[] = {-1234};
  int * p;
  int s;
  printSolutions(testCase1, ARRAYSIZE(testCase1));
  s = ARRAYSIZE(testCase1);
  p = testCase1;
  F(p, s);
  printSolutions(testCase1, ARRAYSIZE(testCase1));
  printSolutions(testCase2, ARRAYSIZE(testCase2));
  s = ARRAYSIZE(testCase2);
  p = testCase2;
  F(p, s);
  printSolutions(testCase2, ARRAYSIZE(testCase2));
  printSolutions(testCase3, ARRAYSIZE(testCase3));
  s = ARRAYSIZE(testCase3);
  p = testCase3;
  F(p, s);
  printSolutions(testCase3, ARRAYSIZE(testCase3));
  printSolutions(testCase4, ARRAYSIZE(testCase4));
  s = ARRAYSIZE(testCase4);
  p = testCase4;
  F(p, s);
  printSolutions(testCase4, ARRAYSIZE(testCase4));
  printSolutions(testCase5, ARRAYSIZE(testCase5));
  s = ARRAYSIZE(testCase5);
  p = testCase5;
  F(p, s);
  printSolutions(testCase5, ARRAYSIZE(testCase5));
  printSolutions(testCase6, ARRAYSIZE(testCase6));
  s = ARRAYSIZE(testCase6);
  p = testCase6;
  F(p, s);
  printSolutions(testCase6, ARRAYSIZE(testCase6));

  return 0;
}

```

# Answer
> 2 votes
# Factor, 36 bytes

```
[ 0 [ dup 0 = -rot ? ] accumulate* ]

```

(Only works locally in Factor 0.98 or later. TIO is missing `accumulate*`.) ¯\\\_(ツ)\_/¯

## Explanation

* `0` Push a zero to the data stack for `accumulate*` to use later. This is a 'starter' element so that a binary operation can be performed on something with the first element of the input sequence.
* `[ dup 0 = -rot ? ]` Push a quotation to the data stack for `accumulate*` to use later. This is a function that says *"Return the non-zero input if possible. Otherwise, return the second input."* Shorter but harder to read than `[ [ nip ] unless-zero ]`.
* `accumulate*` Like `reduce`, except the intermediate results are mapped into a sequence of the same size as the input sequence.

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

```
{y+x*~y}\

```

Try it online!

Take the cumulative sums of the input, resetting to 0 whenever a new non-zero value is encountered in the list.

If the 0's in the input are replaced with nulls (`0N`), `^\` (fill-scan) suffices for two bytes.

# Answer
> 2 votes
# Groovy, ~~34~~ 25 bytes

```
f={it.collect{it?n=it:n}}

```

Try it online!

A more readable solution:

```
f = { // define new closure
  it.collect { // taking advantage of implicit "it". collect applies the closure
               // on every element in order and returns the new, mapped array
    it ? // Groovy Boolean evaluation: 0 = false, 1+ = true
    n = it // assign value to holding variable (if not 0). assignments are expressions
    :
    n // in Groovy, if no return, last expression evaluated is returned
  } // same as above, returns the mapped array
} // end of closure

```

Groovy is supposed to be similar to Java (and it is), but the Java answer is more than two times longer. Just something to think about.

EDIT: reduced it by 9 bytes(!) by not declaring the `n` variable beforehand (saves 6 bytes), and using a ternary operator instead of an `if` (saves 3 bytes)

# Answer
> 2 votes
# Vyxal, 2 bytes

```
ɖ∨

```

Try it Online!

# Answer
> 1 votes
# rs, 14 bytes

```
+(\S+) 0/\1 \1

```

1 byte shorter than Retina!!

Live demo and test cases.

# Answer
> 1 votes
## Seriously, 12 bytes

```
0╗,`╜@;I;╗`M

```

Try it online

Explanation:

```
0╗,    initialize first register to 0 and get input
`...`M map the function over the input:
  ╜@;I    push the result of (a if a else <value in register 0>)
  ;╗      dupe result and push to register 0

```

# Answer
> 1 votes
# Gema, 21 characters

```
0=$p
<N>=@set{p;$0}$0

```

Sample run:

```
bash-4.3$ gema '0=$p;<N>=@set{p;$0}$0' <<< '23 0 0 -42 0 0 0'
23 23 23 -42 -42 -42 -42

```

# Answer
> 1 votes
# JavaScript, 20 Bytes

```
a=>a.map(b=>c=b?b:c)

```

Explanation:

```
a=>           // Define anonymous function which takes argument a
  a.map(      // Loop through input
    b=>       // Looping function
      c=b     // Assign c to the loop value (returns b)
      ?b:c    // Ternary Operator: If b (previous expression) is truthy (Non-zero integers are) return b else return c (last value)
)

```

# Answer
> 1 votes
# Perl 5 \+ `-pl`, 9 bytes

```
$;=$_||=$

```

Try it online!

## Explanation

This reads each number in as `$_` (`-p`), then sets `$;` to `$_`, after first setting `$_` to `$;` if `$_` is falsy (`0`) and is implicitly `print`ed (`-p`). Requires `-l` as otherwise `$_` would include `\n` which would mean `0` isn't falsy. The final `;` can be omitted as `-p` (well, specifically the `-n` part of `-p`) adds `while(<STDIN>){` ... `;}` around your code, resulting in `$;` at the end.

# Answer
> 1 votes
# QBasic, 54 bytes

```
INPUT n
FOR i=1TO n
INPUT x
IF x=0THEN x=p
?x
p=x
NEXT

```

Input is the length of the list, followed by the numbers in the list one at a time. (Compare this I/O default, which is the same basic idea even though it refers specifically to passing an array to a function.)

You can try it at Archive.org.

### Ungolfed

```
INPUT arrayLength
FOR i = 1 TO arrayLength
  INPUT number
  IF number = 0 THEN number = previous
  PRINT number
  previous = number
NEXT i

```

# Answer
> 1 votes
# Batch 147 bytes

```
@Set A=%* &@Setlocal EnableDelayedExpansion
@Set "L=%A: ="&If .!C!==. Set "C=%"
@Set "A=%A: ="&2>nul Set/AL/L&&Set/AC=L&<nul Set/p=!C! &Set "L=%"

```

Approach:
Update Value to output only when value is non zero

How:

Line one: Arg asssignment and environment prep. Defines the array from arg to the batch file IE: `4 1 0 2 4 3`

Line two: Uses a substring operation for each whitespace present in the string with an if condition to isolate the first substring preceding a space for assignment to `L`ast and `C`Current variables.

Line three: Uses Substring modification to iterate through the array from each space in the substring; divides the `L`ast value by itself and on command success (`&&`) transfers the `L`ast value to `C`urrent. (a 0 value results in divide by zero error, redirected to nul). `C`urrent value is output after each step of the substitution.

---

Example Input / output:

```
4 3 2 0 3
4 3 2 2 3

```

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

```
Prompt A
For(I,2,dim(ʟA
ʟA(I)+ʟA(I-1)not(ʟA(I→ʟA(I
End

```

Output is stored in `ʟA`.

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

```
g=lambda l,s=0:l and[a:=l[0]or s]+g(l[1:],a)

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
Å»‚0Kθ

```

Unfortunately 05AB1E lacks a logical-OR builtin, and a bitwise-OR isn't what we want here.

Try it online or verify all test cases.

**Explanation:**

```
Å»      # Cumulative left-reduce the (implicit) input-list by:
  ‚     #  Pair the current and previous integers together
   0K   #  Remove any potential 0
     θ  #  And pop and push the last item of this singleton-list/pair
        # (after which the result is output implicitly)

```

# Answer
> 1 votes
# MathGolf, 7 bytes

```
êæαç┤o╘

```

Prints all values on a separated line to STDOUT.

Try it online.

**Explanation:**

```
ê       # Push the input as integer-array
 æ      # Foreach over these integers, using four characters as inner code-block:
  α     #  Wrap the top two values on the stack into a list
        #  (the first iteration will pair with an implicit 0)
   ç    #  Remove all 0s (falsey filter)
    ┤   #  Push it's last item to the stack (unfortunately doesn't pop the list)
     o  #  Print it with trailing newline (without popping)
 ╘      # After the foreach: empty the stack (otherwise it would implicitly output the
        # entire stack; feel free to remove it in the TIO-link to see the difference)

```

# Answer
> 1 votes
# Ly, 19 bytes

```
&nry[p[s!]plu9`oy]p

```

Try it online!

This works by running through all the numbers on the list and remember the current number if it's non-zero. Then it unconditionally deleted the current character and what's printed is whatever number is in the backup cell.

```
&nr                  - read all the nunbers into the stack, reverse them
   y[p          y]   - loop while the stack length is >0
      [  ]           - if/then, true is current number !=0
       s             - save the number to the backup cell
        !            - flip to 0 to exit the loop
                  p  - delete loop boolean so it doesn't print
          p          - delete current number
           lu        - load backup cell and print
             9`o     - print a LF

```

# Answer
> 0 votes
## Clojure, 49 bytes

```
#(reduce(fn[c i](conj c(if(= i 0)(last c)i)))[]%)

```

Well this is very boring. TIO

# Answer
> 0 votes
# Desmos, 80 bytes

```
L=l[1...i-1]
A=L[LL>0]
f(l)=[\{l[i]=0:A[A.\length],l[i]\}\for i=[1...l.\length]]

```

Most likely golfable, though I don't see anything at the moment.

Try It On Desmos!

Try It On Desmos! - Prettified

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