50
\$\begingroup\$

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]
\$\endgroup\$
8
  • 23
    \$\begingroup\$ A bit of trivia: The name for this operation in the world of statistics is LOCF (last observation carried forward) imputation. \$\endgroup\$
    – Alex A.
    Dec 5, 2015 at 0:12
  • \$\begingroup\$ What happens if the input was [0,0]? \$\endgroup\$
    – user41805
    Dec 5, 2015 at 6:56
  • 5
    \$\begingroup\$ @KριτικσιΛίθος "...where the first value is guaranteed to be non-zero" \$\endgroup\$
    – Sp3000
    Dec 5, 2015 at 7:49
  • \$\begingroup\$ What if the input is [1,01]? Using, issac's Pyth answer, compare this and this. \$\endgroup\$
    – Arcturus
    Dec 6, 2015 at 0:47
  • 1
    \$\begingroup\$ @Eridan 01 is not a valid integer in Pyth input, so isaac doesn't have to account for that. Other answers can accept input like that if they want, just so long as they are consistent (like how isaac's answer will never produce that list as output) \$\endgroup\$ Dec 6, 2015 at 0:52

61 Answers 61

25
\$\begingroup\$

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.
\$\endgroup\$
2
  • 7
    \$\begingroup\$ My brain cannot comprehend... Dennis has finally found a way to permanently out golf us. Like he hadn't already. ಠ_ಠ \$\endgroup\$ Dec 5, 2015 at 0:52
  • 2
    \$\begingroup\$ The explanation no longer aligns with the program \$\endgroup\$
    – quintopia
    Dec 27, 2015 at 8:23
19
\$\begingroup\$

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.

\$\endgroup\$
0
19
\$\begingroup\$

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.

\$\endgroup\$
0
18
\$\begingroup\$

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.

\$\endgroup\$
0
13
\$\begingroup\$

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.
\$\endgroup\$
2
  • \$\begingroup\$ Can you replicate by absolute value instead of removing 0s? \$\endgroup\$
    – lirtosiast
    Dec 4, 2015 at 22:20
  • \$\begingroup\$ @ThomasKwa That was my first attempt. It's {:@(#~|)\, so one byte longer. \$\endgroup\$
    – Zgarb
    Dec 4, 2015 at 22:25
13
\$\begingroup\$

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
$ 
\$\endgroup\$
11
\$\begingroup\$

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]
\$\endgroup\$
5
  • \$\begingroup\$ Whenever I run this I get an error saying "can't find variable p" \$\endgroup\$
    – Downgoat
    Dec 6, 2015 at 17:23
  • \$\begingroup\$ @Downgoat That's because the interpreter is a Strict Mode only interpreter. If you don't run that code in strict mode, it should work. \$\endgroup\$
    – wizzwizz4
    Dec 6, 2015 at 18:16
  • \$\begingroup\$ @wizzwizz4 ohh,r okay \$\endgroup\$
    – Downgoat
    Dec 6, 2015 at 19:41
  • 2
    \$\begingroup\$ @wizzwizz4 Strict mode is silly. \$\endgroup\$ Dec 8, 2015 at 14:49
  • 2
    \$\begingroup\$ @SuperJedi224 It's not silly. It's very useful; it makes sure your code is not ambiguous, and will work even with a major update, and doesn't use undefined behaviour, etc. But what's silly is enabling it by default, since Strict mode doesn't specify a way to turn itself off, and if you don't put the strict mode string at the beginning, you don't want it and/or are code-golfing. \$\endgroup\$
    – wizzwizz4
    Dec 8, 2015 at 18:08
9
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 76, took off a couple: int[]f(int[]a){for(int i=0;++i<a.length;a[i]=a[i]==0?a[i-1]:a[i]);return a;} Try it online! \$\endgroup\$ Mar 31, 2021 at 19:53
6
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ This is 6 bytes in Pyth, and suppresses the error: #\nJ|EJ \$\endgroup\$
    – isaacg
    Dec 4, 2015 at 22:08
6
\$\begingroup\$

Pyth, 8 bytes

t.u|YNQ0

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

\$\endgroup\$
2
  • \$\begingroup\$ @isaacg It seems like .u is longer even if J and K are tied up. Is it ever optimal? \$\endgroup\$
    – lirtosiast
    Dec 4, 2015 at 22:24
  • \$\begingroup\$ It was (at least afaik) here. It usually helps when you would want all the results for some reason. \$\endgroup\$ Dec 4, 2015 at 22:30
6
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ Very concise! I like how some functional and logic programming languages allow you to do such a literal translation of the rules. It's such a natural way to write it! \$\endgroup\$ Sep 27, 2019 at 20:31
  • \$\begingroup\$ 46 bytes \$\endgroup\$
    – ovs
    Oct 19, 2021 at 16:13
5
\$\begingroup\$

Mathematica 38 bytes

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

#//.{b___,a_/;a!=0,0,e___}:>{b,a,a,e}&
\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ You can save one byte by converting it to a program - use x=input('') instead of the function declaration, and disp(u(t) instead of the y= bit. Also, you can save four more bytes by getting rid of the t variable, yielding x=input('');u=x(~~x);disp(u(cumsum(~~x))) for 41. \$\endgroup\$ Dec 5, 2015 at 1:31
  • \$\begingroup\$ @TomCarpenter Thanks a lot! Edited \$\endgroup\$
    – Luis Mendo
    Dec 5, 2015 at 2:43
  • \$\begingroup\$ I don't have Matlab, but @(x)x(~~x)(cumsum(~~x)) works in Octave. \$\endgroup\$
    – alephalpha
    Dec 5, 2015 at 6:13
  • \$\begingroup\$ @alephalpha Matlab doesn't allow iterated indexing. \$\endgroup\$
    – AlexR
    Dec 5, 2015 at 12:26
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ Wait, ª is OR, rather than º? Is º AND by any chance? \$\endgroup\$ Dec 25, 2017 at 22:38
  • \$\begingroup\$ @cairdcoinheringaahing Nope, º is ((. They were assigned by Unicode value as I found the need for them :P ªnd and ºr is genius though, I might use that for Japt 2.0... \$\endgroup\$ Dec 26, 2017 at 3:04
4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Perhaps not surprisingly, the new, shorter version turned out very similar to Dennis's CJam entry. It wins by one byte because GolfScript reads the input automatically, and thus doesn't need an extra command for that. \$\endgroup\$ Dec 4, 2015 at 22:41
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 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
\$\endgroup\$
0
4
\$\begingroup\$

O, 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
\$\endgroup\$
3
  • \$\begingroup\$ You can save two bytes with I~]{n.{:V}{;V}?}d. I wonder if d should just put the value on the stack instead of n... \$\endgroup\$ Dec 5, 2015 at 17:10
  • \$\begingroup\$ Are you sure O can handle this? I can't find the way to pass it -42 satisfying the “your output should be an acceptable input for your submission” requirement. \$\endgroup\$
    – manatwork
    Dec 5, 2015 at 17:16
  • \$\begingroup\$ @manatwork I've got a better version now that works for -42, but it adds brackets around the output. \$\endgroup\$
    – jado
    Dec 5, 2015 at 19:59
4
\$\begingroup\$

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)
\$\endgroup\$
1
  • \$\begingroup\$ I believe x[cummax(seq(!x)*!!x] is 3 bytes shorter and equivalent. \$\endgroup\$
    – Giuseppe
    Mar 31, 2021 at 15:05
4
\$\begingroup\$

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 NAs 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 NAs 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!

\$\endgroup\$
0
4
\$\begingroup\$

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.

\$\endgroup\$
2
  • 7
    \$\begingroup\$ "At least it's not as bad as Java"? Ahem... ;) \$\endgroup\$
    – Geobits
    Dec 8, 2015 at 14:25
  • 1
    \$\begingroup\$ @Geobits Oh, right. I was counting on you needing that public static void main boilerplate… \$\endgroup\$ Dec 8, 2015 at 22:03
4
\$\begingroup\$

Husk, 2 bytes

G|

Try it online!

scan from left with or.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ I'm pretty sure that TOS and STOS mean Top of Stack and Second-to-Top of Stack, is this right? \$\endgroup\$ Dec 5, 2015 at 0:35
  • \$\begingroup\$ Yep @FlagAsSpam \$\endgroup\$
    – Zach Gates
    Dec 5, 2015 at 1:40
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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))
\$\endgroup\$
3
\$\begingroup\$

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.
\$\endgroup\$
0
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ @TimmyD, you are right, of course. I've added param($x) which turns this into a program. The output is a collection of integers which you can submit as a parameter to the program, e.g. $a = .\program.ps1 1,2,3,4,0,0,5 and then .\program.ps1 $a works as expected. \$\endgroup\$ Dec 9, 2015 at 15:41
  • \$\begingroup\$ $args|%{($p=($_,$p)[!$_])} - 26 bytes using $args. \$\endgroup\$ Dec 16, 2015 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.