Cover up zeroes in a list

41

2

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]

FryAmTheEggman

Posted 2015-12-04T21:48:42.157

Reputation: 16 206

21A bit of trivia: The name for this operation in the world of statistics is LOCF (last observation carried forward) imputation. – Alex A. – 2015-12-05T00:12:19.457

What happens if the input was [0,0]? – user41805 – 2015-12-05T06:56:03.657

4@KριτικσιΛίθος "...where the first value is guaranteed to be non-zero" – Sp3000 – 2015-12-05T07:49:14.560

What if the input is [1,01]? Using, issac's Pyth answer, compare this and this.

– Arcturus – 2015-12-06T00:47:17.900

@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) – FryAmTheEggman – 2015-12-06T00:52:58.470

@FryAmTheEggman I don't know the mechanics of Pyth, so I appreciate the explanation, thanks. – Arcturus – 2015-12-06T01:14:43.143

Can we error out when finished? – FantaC – 2017-12-24T22:55:50.770

@tfbninja As long as the error doesn't affect your output, you can do whatever you would like. This is a site-wide default, so feel free to assume it is alright in the future!

– FryAmTheEggman – 2017-12-25T19:56:10.633

Answers

19

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.

isaacg

Posted 2015-12-04T21:48:42.157

Reputation: 39 268

23

Jelly, non-competing

3 bytes This answer is non-competing, since it uses features that postdate the challenge.

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.

Dennis

Posted 2015-12-04T21:48:42.157

Reputation: 196 637

6My brain cannot comprehend... Dennis has finally found a way to permanently out golf us. Like he hadn't already. ಠ_ಠ – Addison Crump – 2015-12-05T00:52:02.047

1The explanation no longer aligns with the program – quintopia – 2015-12-27T08:23:30.203

18

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.

Doorknob

Posted 2015-12-04T21:48:42.157

Reputation: 68 138

17

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.

xnor

Posted 2015-12-04T21:48:42.157

Reputation: 115 687

13

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.

Zgarb

Posted 2015-12-04T21:48:42.157

Reputation: 39 083

Can you replicate by absolute value instead of removing 0s? – lirtosiast – 2015-12-04T22:20:42.793

@ThomasKwa That was my first attempt. It's {:@(#~|)\, so one byte longer. – Zgarb – 2015-12-04T22:25:08.973

13

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
$ 

Digital Trauma

Posted 2015-12-04T21:48:42.157

Reputation: 64 644

11

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]

Dendrobium

Posted 2015-12-04T21:48:42.157

Reputation: 2 412

Whenever I run this I get an error saying "can't find variable p"

– Downgoat – 2015-12-06T17:23:48.617

@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. – wizzwizz4 – 2015-12-06T18:16:48.837

@wizzwizz4 ohh,r okay – Downgoat – 2015-12-06T19:41:07.660

1@wizzwizz4 Strict mode is silly. – SuperJedi224 – 2015-12-08T14:49:18.310

1@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. – wizzwizz4 – 2015-12-08T18:08:36.980

7

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.

lirtosiast

Posted 2015-12-04T21:48:42.157

Reputation: 20 331

7

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.

Martin Ender

Posted 2015-12-04T21:48:42.157

Reputation: 184 808

6

Pyth, 8 bytes

t.u|YNQ0

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

lirtosiast

Posted 2015-12-04T21:48:42.157

Reputation: 20 331

@isaacg It seems like .u is longer even if J and K are tied up. Is it ever optimal? – lirtosiast – 2015-12-04T22:24:09.640

It was (at least afaik) here. It usually helps when you would want all the results for some reason.

– FryAmTheEggman – 2015-12-04T22:30:07.450

5

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!

Post Rock Garf Hunter

Posted 2015-12-04T21:48:42.157

Reputation: 55 382

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! – ThePlasmaRailgun – 2019-09-27T20:31:04.730

5

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.

xnor

Posted 2015-12-04T21:48:42.157

Reputation: 115 687

This is 6 bytes in Pyth, and suppresses the error: #\nJ|EJ – isaacg – 2015-12-04T22:08:03.390

5

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

Non-competing 4-byte version: (å command and !-auto-function added after challenge)

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!

ETHproductions

Posted 2015-12-04T21:48:42.157

Reputation: 47 880

Wait, ª is OR, rather than º? Is º AND by any chance? – caird coinheringaahing – 2017-12-25T22:38:47.270

@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... – ETHproductions – 2017-12-26T03:04:50.083

5

Mathematica 38 bytes

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

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

DavidC

Posted 2015-12-04T21:48:42.157

Reputation: 24 524

5

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

Luis Mendo

Posted 2015-12-04T21:48:42.157

Reputation: 87 464

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. – Tom Carpenter – 2015-12-05T01:31:00.437

@TomCarpenter Thanks a lot! Edited – Luis Mendo – 2015-12-05T02:43:26.860

I don't have Matlab, but @(x)x(~~x)(cumsum(~~x)) works in Octave. – alephalpha – 2015-12-05T06:13:56.127

@alephalpha Matlab doesn't allow iterated indexing. – AlexR – 2015-12-05T12:26:25.540

5

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.

randomra

Posted 2015-12-04T21:48:42.157

Reputation: 19 909

5

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.

Geobits

Posted 2015-12-04T21:48:42.157

Reputation: 19 061

4

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.

Ilmari Karonen

Posted 2015-12-04T21:48:42.157

Reputation: 19 513

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.

– Ilmari Karonen – 2015-12-04T22:41:04.800

4

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.

El'endia Starman

Posted 2015-12-04T21:48:42.157

Reputation: 14 504

4

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!

Alex A.

Posted 2015-12-04T21:48:42.157

Reputation: 23 761

4

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

phase

Posted 2015-12-04T21:48:42.157

Reputation: 2 540

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... – kirbyfan64sos – 2015-12-05T17:10:03.223

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. – manatwork – 2015-12-05T17:16:02.330

@manatwork I've got a better version now that works for -42, but it adds brackets around the output. – phase – 2015-12-05T19:59:23.653

4

, 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

Mama Fun Roll

Posted 2015-12-04T21:48:42.157

Reputation: 7 234

4

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.

Blacklight Shining

Posted 2015-12-04T21:48:42.157

Reputation: 170

7

"At least it's not as bad as Java"? Ahem... ;)

– Geobits – 2015-12-08T14:25:35.313

1@Geobits Oh, right. I was counting on you needing that public static void main boilerplate… – Blacklight Shining – 2015-12-08T22:03:58.963

3

Japt, 3 bytes

å!ª

Try it

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

Shaggy

Posted 2015-12-04T21:48:42.157

Reputation: 24 623

3

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.

Jo King

Posted 2015-12-04T21:48:42.157

Reputation: 38 234

3

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

scrawl

Posted 2015-12-04T21:48:42.157

Reputation: 1 079

3

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.

Dennis

Posted 2015-12-04T21:48:42.157

Reputation: 196 637

3

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.

Danko Durbić

Posted 2015-12-04T21:48:42.157

Reputation: 10 241

@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. – Danko Durbić – 2015-12-09T15:41:34.123

$args|%{($p=($_,$p)[!$_])} - 26 bytes using $args. – TessellatingHeckler – 2015-12-16T00:01:10.817

3

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

Zach Gates

Posted 2015-12-04T21:48:42.157

Reputation: 6 152

I'm pretty sure that TOS and STOS mean Top of Stack and Second-to-Top of Stack, is this right? – Addison Crump – 2015-12-05T00:35:08.303

Yep @FlagAsSpam – Zach Gates – 2015-12-05T01:40:48.713

3

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.

Alex A.

Posted 2015-12-04T21:48:42.157

Reputation: 23 761

3

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))

Brad Gilbert b2gills

Posted 2015-12-04T21:48:42.157

Reputation: 12 713

3

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)

flodel

Posted 2015-12-04T21:48:42.157

Reputation: 2 345

2

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

Dorian

Posted 2015-12-04T21:48:42.157

Reputation: 1 521

2

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.

GammaFunction

Posted 2015-12-04T21:48:42.157

Reputation: 2 838

2

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

jqblz

Posted 2015-12-04T21:48:42.157

Reputation: 2 062

2

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.

Martin Ender

Posted 2015-12-04T21:48:42.157

Reputation: 184 808

2

Mathematica, 28 27 25 bytes

Saved 2 bytes thanks to Martin Büttner.

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

alephalpha

Posted 2015-12-04T21:48:42.157

Reputation: 23 988

1If[#2==0,##]&~FoldList~#&? – Martin Ender – 2015-12-22T17:17:44.263

2

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;
}

cleblanc

Posted 2015-12-04T21:48:42.157

Reputation: 3 360

Running your test program on Ideone.com doesn't seem to work - it just duplicates the first number.

– AdmBorkBork – 2015-12-09T19:36:19.390

That's strange. I don't see where I'm relying on undefined behavior. Maybe some compiler optimization gone wrong? – cleblanc – 2015-12-09T20:33:50.857

Yeah, I'm not sure, either (I'm not super-well-versed in C). Both CodingGrounds and codepad have the same behavior.

– AdmBorkBork – 2015-12-09T20:45:48.860

Also, welcome to Programming Puzzles & Code Golf! – AdmBorkBork – 2015-12-09T20:51:32.097

Thanks, slow day in work and I usually just read through these... – cleblanc – 2015-12-09T21:09:05.847

1

rs, 14 bytes

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

1 byte shorter than Retina!!

Live demo and test cases.

kirbyfan64sos

Posted 2015-12-04T21:48:42.157

Reputation: 8 730

1

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

Mego

Posted 2015-12-04T21:48:42.157

Reputation: 32 998

1I was thinking this challenge had no seriously answer...and rather than check, I sat down and wrote this exact solution byte-for-byte. – quintopia – 2015-12-27T08:25:13.303

@quintopia Hush, people are going to think you're my sock :P – Mego – 2015-12-27T18:05:24.357

1

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

manatwork

Posted 2015-12-04T21:48:42.157

Reputation: 17 865

1

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)          
)

MayorMonty

Posted 2015-12-04T21:48:42.157

Reputation: 778

b||c saves one byte over b?b:c. – Neil – 2015-12-06T19:18:48.103

Although then you just end up with @Dendrobium's answer. – Neil – 2015-12-06T19:24:38.433

His is surperior, I don't want to impersonate him – MayorMonty – 2015-12-06T21:48:49.987

(I hadn't seen his answer when I wrote my first comment.) – Neil – 2015-12-07T10:43:01.450

You're fine, but if his is better, than is better so be it. – MayorMonty – 2015-12-08T21:42:50.270