Remove leading and trailing zeroes

31

2

Given a non-empty list/array containing only non-negative integers like this:

[0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0]

Output the list with trailing and leading zeroes removed.

The output for this would be:

[8, 1, 4, 3, 5, 6, 4, 1, 2]

Some other test cases:

[0, 4, 1, 2, 0, 1, 2, 4, 0] > [4, 1, 2, 0, 1, 2, 4]
[0, 0, 0, 0, 0, 0] > nothing
[3, 4, 5, 0, 0] > [3, 4, 5]
[6] > [6]

Shortest code wins

Lamaro

Posted 2016-02-12T18:27:51.363

Reputation: 781

Are the numbers non-negative integers only? I suggest you clarify that or add test cases with other numbers – Luis Mendo – 2016-02-12T20:08:31.643

1Can we assume that there will be at least one leading and one trailing 0? – James – 2016-02-12T20:24:12.000

@LuisMendo Yes, only non-negative integers. – Lamaro – 2016-02-12T22:56:50.657

@DJMcGoathem No, it is possible that there is no leading or trailing 0 – Lamaro – 2016-02-12T22:57:28.820

4What constitutes nothing? I can think of several different things that are variations on nothing in Perl 6. Nil ()/[] slip()/Empty Any {} some of them are undefined, some defined but singular, some that slip into other lists such that they don't increase the number of elements. ( There are as many different variations on Any as there are classes/types and roles ) – Brad Gilbert b2gills – 2016-02-13T00:41:42.130

7Is it a coincidence that there are no integers over 10 or can we assume that all the numbers are going to be single-digit? – A Simmons – 2016-02-13T17:57:06.580

Huh. I was thinking about posting this the other day, actually. +1 – Addison Crump – 2016-02-21T16:08:07.707

1Can we input/output the list as a delimited string? For example: "0,4,1,2,0,1,2,4,0" => "4,1,2,0,1,2,4" EDIT: Just noticed many languages do this already. – Mwr247 – 2016-02-24T18:18:07.910

Answers

25

Jelly, 2 bytes

Code:

t0

Explanation:

t   # Trim off...
 0  #  zero at both sides

Try it online!

Adnan

Posted 2016-02-12T18:27:51.363

Reputation: 41 965

10This works? Jeez. I thought the MATL answers were insane. – Skyl3r – 2016-02-12T18:55:28.930

4wut y no don do dis jelly – Addison Crump – 2016-02-21T16:09:10.693

Of course Jelly beats every other guy out there almost every time... – Erik the Outgolfer – 2016-10-05T14:35:33.160

Is Jelly used in actual businesses? – Chromozorz – 2016-10-05T23:49:52.283

Man, I hope not – Caleb Paul – 2017-05-20T16:11:21.860

10

JavaScript (ES6) 43

a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a))

Less golfed

a=>{
  f=a=>a.reverse().filter(x=>a|=x) // reverse and remove leading 0
  // leverage js cast rules: operator | cast operands to integer
  // an array casted to integer is 0 unless the array is made of
  // a single integer value (that is ok for me in this case)
  return f(f(a)) // apply 2 times
}

Test

F=a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a))

function test(){
  var l=(I.value.match(/\d+/g)||[]).map(x=>+x)
  O.textContent=F(l)
}

test()
#I { width:90%}
<input id=I oninput='test()' value='0 0 1 3 7 11 0 8 23 0 0 0'>
<pre id=O></pre>

edc65

Posted 2016-02-12T18:27:51.363

Reputation: 31 086

1Nice. f=(a,r=f(a,a))=>r.reverse().filter(x=>a|=x) is also 43 bytes. – Neil – 2016-02-13T18:58:35.133

6

CJam, 13 bytes

l~{_{}#>W%}2*

With the array inputted.

Longer version:

l~             Puts input on the stack and parse as array
  {       }    Code block
   _           Duplicate the first thing on the stack
    {}#        Finds the index of the first non-0 value in the array, puts it on the stack
       >       Slices the array from that index
        W%     Reverses the array
           2*  Does the code block twice in total

Angela Xu

Posted 2016-02-12T18:27:51.363

Reputation: 61

I wish I could use the fact that converting to and from a base would remove leading zeros, but it looks like it's too long. – Esolanging Fruit – 2017-05-20T00:19:04.230

5

Pyth, 4 bytes

.sQ0

Demo:

llama@llama:~$ pyth -c .sQ0
[0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 5, 0, 0, 0, 0]
[1, 2, 0, 3, 4, 0, 0, 5]

From Pyth's rev-doc.txt:

.s <seq> <any>
    Strip from A maximal prefix and suffix of A consisting of copies of B.

Doorknob

Posted 2016-02-12T18:27:51.363

Reputation: 68 138

5

05AB1E, 4 bytes

Code:

0Û0Ü

Try it online!

Explanation:

0Û    # Trim off leading zeroes
  0Ü  # Trim off trailing zeroes

Uses CP-1252 encoding.

Adnan

Posted 2016-02-12T18:27:51.363

Reputation: 41 965

5

Retina, 12 bytes

^0 ?

)` 0$

The trailing linefeed is significant.

Thanks to @Martin Büttner and @FryAmTheEggman for saving a few bytes.

Try it online

andlrc

Posted 2016-02-12T18:27:51.363

Reputation: 1 613

5

R, 43 bytes

function(x)x[cummax(x)&rev(cummax(rev(x)))]

or as read/write STDIN/STDOUT

x=scan();cat(x[cummax(x)&rev(cummax(rev(x)))])

This finds the cumulative maximum from the beginning and the end (reversed) string. The & operator converts these two vectors to logical one of the same size as x, (zeroes will always converted to FALSE and everything else to TRUE), this way it makes it possible to subset from x according to the met conditions.

David Arenburg

Posted 2016-02-12T18:27:51.363

Reputation: 531

5

Haskell, 29 bytes

t=f.f;f=reverse.dropWhile(<1)

Itai Bar-Natan

Posted 2016-02-12T18:27:51.363

Reputation: 246

4

Mathematica 34 27 bytes

#//.{0,a___}|{a___,0}:>{a}&

This repeatedly applies replacement rules until such action fails to provide a new output. 7 bytes saved thanks to Alephalpha.

The first rule deletes a zero at the beginning; the second rule deletes a zero at the end of the array.

DavidC

Posted 2016-02-12T18:27:51.363

Reputation: 24 524

3#//.{0,a___}|{a___,0}:>{a}& – alephalpha – 2016-02-13T17:46:51.360

4

05AB1E, 4 bytes

0Û0Ü

Basically trimming leading then trailing zeroes of the input, given as an array.

Try it online !

Paul Picard

Posted 2016-02-12T18:27:51.363

Reputation: 863

3

Perl, 19 + 1 = 20 bytes

s/^(0 ?)+|( 0)+$//g

Requires -p flag:

$ perl -pE's/^(0 )+|( 0)+$//g' <<< '0 0 0 1 2 3 4 5 6 0 0 0'
1 2 3 4 5 6

andlrc

Posted 2016-02-12T18:27:51.363

Reputation: 1 613

@MartinBüttner I though about the same just after hitting [Add Comment], now I just need to figure out now to let markdown save my newline in a code block – andlrc – 2016-02-12T19:03:39.860

Via evil HTML hacks. ;) – Martin Ender – 2016-02-12T19:04:21.347

117+1 bytes: s/^0 | 0$//&&redo – Kenney – 2016-02-21T19:14:22.827

@Kenney That is beautiful :-) You should post that as an answer! – andlrc – 2016-02-23T11:56:05.940

Thanks! My original was also 19+1 bytes but then I saw your answer which gave me an idea to shave off 2 more, so it's yours if you want it. Btw, your answer is actually 18+1 if you drop the ? as in the example - but that won't reduce "0".. – Kenney – 2016-02-23T12:10:19.667

3

Jelly, 10 bytes

Uo\U,o\PTị

This doesn't use the builtin.

Uo\U            Backward running logical OR
    ,           paired with
     o\         Forward running logical OR
       P        Product
        T       All indices of truthy elements
         ị      Index the input at those values.

Try it here.

lirtosiast

Posted 2016-02-12T18:27:51.363

Reputation: 20 331

3

MATL, 9 bytes

2:"PtYsg)

Try it online!

Explanation

2:"     % For loop (do the following twice)
  P     %   Flip array. Implicitly asks for input the first time
  t     %   Duplicate
  Ys    %   Cumulative sum
  g     %   Convert to logical index
  )     %   Apply index
        % Implicitly end for
        % Implicitly display stack contents

Luis Mendo

Posted 2016-02-12T18:27:51.363

Reputation: 87 464

3

Perl, 38 bytes

$\.=$_}{$\=~s/^(0\n)*|(0\n)*\n$//gs

Run with perl -p, (3 bytes added for -p).

Accepts numbers on STDIN, one per line; emits numbers on STDOUT, one per line, as a well-behaved unix utility should.

Only treats numbers represented exactly by '0' as zeroes; it would be possible to support other representations with a few more bytes in the regex.

Longer version, still to be run with -p:

    # append entire line to output record separator
    $\.=$_
}{
    # replace leading and trailng zeroes in output record separator
    $\ =~ s/^(0\n)*|(0\n)*\n$//gs
    # output record separator will be implicitly printed

Expanded version, showing interactions with -p flag:

# implicit while loop added by -p
while (<>) {
    # append line to output record separator
    $\.=$_
}{ # escape the implicit while loop
    # replace leading and traling 
    $\=~s/^(0\n)*|(0\n)*\n$//gs
    # print by default prints $_ followed by
    # the output record separator $\ which contains our answer
    ;print # implicit print added by -p
} # implicit closing brace added by -p

David Morris

Posted 2016-02-12T18:27:51.363

Reputation: 241

Assuming you're running with perl -E, the -p flag usually is only counted as one byte, since there's only one extra byte different between that and perl -pE. – Chris – 2017-05-20T00:19:41.870

3

Elixir, 77 bytes

import Enum
z=fn x->x==0 end
reverse(drop_while(reverse(drop_while(l,z)),z))

l is the array.

Edit:wah! copy/pasta fail. of course one has to import Enum, which raises the byte count by 12 (or use Enum.function_name, which will make it even longer).

srecnig

Posted 2016-02-12T18:27:51.363

Reputation: 171

3

Vitsy, 13 bytes

Vitsy is slowly getting better... (I'm coming for you Jelly. ಠ_ಠ)

1mr1m
D)[X1m]

This exits with the array on the stack. For readability, the TryItOnline! link that I have provided below the explanation will output a formatted list.

Explanation:

1mr1m
1m      Do the second line of code.
  r     Reverse the stack.
   1m   I'ma let you figure this one out. ;)

D)[X1m]
D       Duplicate the top item of the stack.
 )[   ] If the top item of the stack is zero, do the stuff in brackets.
   X    Remove the top item of the stack.
    1m  Execute the second line of code.

Note that this will throw a StackOverflowException for unreasonably large inputs.

TryItOnline!

Addison Crump

Posted 2016-02-12T18:27:51.363

Reputation: 10 763

2Vitsy will get Jelly some day. – Conor O'Brien – 2016-02-21T17:40:01.127

Add auto-bracket matching on EOL/EOF – Cyoce – 2016-04-12T21:54:44.930

3

R, 39 bytes

function(x)x[min(i<-which(x>0)):max(i)]

Four bytes shorter than David Arenburg's R answer. This implementation finds the first and last index in the array which is greater than zero, and returns everything in the array between those two indices.

rturnbull

Posted 2016-02-12T18:27:51.363

Reputation: 3 689

2

Ruby, 49 44 bytes

->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2}

Thanks to manatwork for chopping off 5 bytes with a completely different method!

This just drops the first element of the array while it's 0, reverses the array, repeats, and finally reverses the array to return it to the proper order.

Doorknob

Posted 2016-02-12T18:27:51.363

Reputation: 68 138

Ouch. Now even a .drop_while() based solution would be shorter (if using 2 functions): f=->a{a.drop_while{|i|i<1}.reverse};->a{f[f[a]]} – manatwork – 2016-02-12T19:31:50.877

Doh. No need for 2 functions, just some eval ugliness: ->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2}. – manatwork – 2016-02-12T19:38:07.497

@manatwork Not sure why I didn't think of <1, anyway. Thanks! – Doorknob – 2016-02-12T20:00:41.300

2

Dyalog APL, 15 bytes

{⌽⍵↓⍨+/0=+\⍵}⍣2

               ⍣2     Apply this function twice:
{             }       Monadic function:
           +\⍵        Calculate the running sum.
       +/0=           Compare to zero and sum. Number of leading zeroes.
   ⍵↓⍨               Drop the first that many elements from the array.
 ⌽                   Reverse the result.

Try it here.

lirtosiast

Posted 2016-02-12T18:27:51.363

Reputation: 20 331

How about {⌽⍵/⍨×+\⍵}⍣2? – lstefano – 2016-06-27T13:04:28.890

2

Vim 16 Keystrokes

i<input><esc>?[1-9]<enter>lD0d/<up><enter>

The input is to be typed by the user between i and esc, and does not count as a keystroke. This assumes that there will be at least one leading and one trailing zero. If that is not a valid assumption, we can use this slightly longer version: (18 Keystrokes)

i <input> <esc>?[1-9]<enter>lD0d/<up><enter>

James

Posted 2016-02-12T18:27:51.363

Reputation: 54 537

1I don't think you need to include code to allow the user to input the numbers (i and <esc>). In vim golf the golfer starts with the input already in a file loaded the buffer and the cursor in the top left corner, but the user also has to save and exit (ZZ is usually the fastest way). Then you could do something like d[1-9]<enter>$NlDZZ (13 keystrokes). Note N/n instead of /<up><enter> – daniero – 2016-02-12T22:45:43.897

2

ES6, 51 bytes

f=a=>a.map(x=>x?t=++i:f<i++||++f,f=i=0)&&a.slice(f,t)

t is set to the index after the last non-zero value, while f is incremented as long as only zeros have been seen so far.

Neil

Posted 2016-02-12T18:27:51.363

Reputation: 95 035

2

Perl 6, 23 bytes

{.[.grep(?*):k.minmax]}
{.[minmax .grep(?*):k]}

Usage:

# replace the built-in trim subroutine
# with this one in the current lexical scope
my &trim = {.[.grep(?*):k.minmax]}

say trim [0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0];
# (8 1 4 3 5 6 4 1 2)
say trim [0, 4, 1, 2, 0, 1, 2, 4, 0];
# (4 1 2 0 1 2 4)
say trim [0, 0, 0, 0, 0, 0];
# ()
say trim [3, 4, 5, 0, 0];
# (3 4 5)
say trim [6];
# (6)

Brad Gilbert b2gills

Posted 2016-02-12T18:27:51.363

Reputation: 12 713

2

JavaScript (ES6), 47 bytes

a=>a.join(a="").replace(/(^0+|0+$)/g,a).split(a)

Where a is the array.

user2428118

Posted 2016-02-12T18:27:51.363

Reputation: 2 000

4I think you need to make an anonymous function to take input: a=>a.join(a="").... – andlrc – 2016-02-13T17:11:28.157

2This only handles integers properly when they're a single digit – aross – 2016-02-13T23:30:40.337

@dev-null Done. – user2428118 – 2016-02-14T16:37:02.793

Still returning wrong for multi-digit integers. [14] will return [1, 4]. – Mwr247 – 2016-02-23T19:16:45.830

Actually, I was (and am) still awaiting a reply to this comment. Anyway, I unfortunately don't see a way to do handle multi-digit integers using the same technique I've used for my answer and I don't think I'll be able to beat this answer anyway. I may try when I have the time, though.

– user2428118 – 2016-02-23T19:43:10.670

2

Retina, 11 bytes

+`^0 ?| 0$
<empty>

Quite simple. Recursively replaces zeroes at beginning and end of line.

Try it online!

Mama Fun Roll

Posted 2016-02-12T18:27:51.363

Reputation: 7 234

2

PHP, 56 54 52 bytes

Uses Windows-1252 encoding

String based solution

<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));

Run like this:

echo '<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo

If your terminal is set to UTF-8, this is the same:

echo '<?=preg_replace("#-( 0)+|( 0)+$#","",join($argv," "));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo

Tweaks

  • Saved 2 bytes by negating strings and dropping string delimiters
  • Saved 2 bytes by using short print tag

aross

Posted 2016-02-12T18:27:51.363

Reputation: 1 583

1Can you please provide an ASCII solution. Nobody can read this! – Titus – 2016-10-05T13:34:00.220

1@Titus Sure. However, plenty of unreadable esolangs out there.... it's not like my answer doesn't feel right at home. – aross – 2016-10-05T14:09:51.030

An array as first parameter of join? – Jörg Hülsermann – 2016-10-05T14:30:45.887

1@JörgHülsermann Yup. It's documented the other way around but it accepts both. – aross – 2016-10-05T14:32:25.637

You are right I have not realize it – Jörg Hülsermann – 2016-10-05T14:50:13.260

Wanted to point you at this: http://codegolf.stackexchange.com/questions/15715/goodbye-world-complete-obfuscation. Can you create a score 0 answer in PHP?

– Titus – 2016-10-06T08:49:47.363

@Titus I have a solution, but can't post it... I voted to reopen – aross – 2016-10-06T09:15:25.223

@Titus: it probably won't be re-opened. Here you go (Windows 1252 encoding): echo '<?="Äììçáúæ£Ôìñïç¢"^"ƒƒƒƒƒƒƒƒƒƒƒƒƒƒ";' | php;echo – aross – 2016-10-07T08:44:47.093

2

Python, 84 characters

def t(A):
 if set(A)<={0}:return[]
 for i in(0,-1):
  while A[i]==0:del A[i]
 return A

pafcjo

Posted 2016-02-12T18:27:51.363

Reputation: 31

You can do for i in-1,0: – mbomb007 – 2016-10-04T14:50:50.730

I count 86 bytes. – Erik the Outgolfer – 2016-10-05T14:43:21.560

2

Python 2, 69 67 bytes

def f(a):
 for i in(0,-1):
  while a and a[i]==0:a.pop(i)
 return a

SumnerHayes

Posted 2016-02-12T18:27:51.363

Reputation: 77

You can remove the space before your tuple in the second line. – Zach Gates – 2016-02-21T19:16:25.447

You can do for i in-1,0: – mbomb007 – 2016-10-04T14:51:21.277

Also, you might want to recount your bytes. I count 67 as is. You can also replace [space][space]while with [tab]while. And ==0 can be <1. https://mothereff.in/byte-counter#def%20f%28a%29%3A%0A%20for%20i%20in-1%2C0%3A%0A%09while%20a%20and%20a%5Bi%5D%3C1%3Aa.pop%28i%29%0A%20return%20a

– mbomb007 – 2016-10-04T15:00:03.150

I count 67 bytes. – Erik the Outgolfer – 2016-10-05T14:44:28.287

2

JavaScript (ES6), 34 bytes

a=>a.replace(/^(0 ?)*|( 0)*$/g,'')

Input and output are in the form of a space-delimited list, such as "0 4 1 2 0 1 2 4 0".

Mwr247

Posted 2016-02-12T18:27:51.363

Reputation: 3 494

2

Javascript (ES6) 40 bytes

a=>/^(0,)*(.*?)(,0)*$/.exec(a.join())[2]

Shaun H

Posted 2016-02-12T18:27:51.363

Reputation: 732

1

PowerShell, 49 bytes

($args[0]-join',').trim(',0').trim('0,')-split','

Takes input $args[0] and -joins them together with commas to form a string. We then use the .Trim() function called twice to remove first the trailing and then the leading zeros and commas. We then -split the string on commas back into an array.


Alternate version, without using conversion
PowerShell, 81 bytes

function f{param($a)$a=$a|%{if($_-or$b){$b=1;$_}};$a[$a.Count..0]}
f(f($args[0]))

Since PowerShell doesn't have a function to trim arrays, we define a new function f that will do half of this for us. The function takes $a as input, then loops through each item with a foreach loop |%{...}. Each iteration, we check a conditional for $_ -or $b. Since non-zero integers are truthy, but $null is falsey (and $b, being not previously defined, starts as $null), this will only evaluate to $true once we hit our first non-zero element in the array. We then set $b=1 and add the current value $_ onto the pipeline. That will then continue through to the end of the input array, with zeros in the middle and the end getting added onto the output, since we've set $b truthy.

We encapsulate and store the results of the loop all back into $a. Then, we index $a in reverse order (i.e., reversing the array), which is left on the pipeline and thus is the function's return value.

We call the function twice on the $args[0] input to the program in order to "trim" from the front, then the front again (which is the back, since we reversed). The order is preserved since we're reversing twice.

This version plays a little loose with the rules for an input array of all zeros, but since ignoring STDERR is accepted practice, the program will spit out two (verbose) Cannot index into a null array errors to (PowerShell's equivalent of) STDERR and then output nothing.

AdmBorkBork

Posted 2016-02-12T18:27:51.363

Reputation: 41 581

1

Mathematica, 33 bytes

#/.{Longest[0...],x__,0...}->{x}&

A Simmons

Posted 2016-02-12T18:27:51.363

Reputation: 4 005

1

jq, 48 characters

. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]

Sample run:

(Command line option -c only used in this sample for readability to avoid pretty printing the result.)

bash-4.3$ jq -c '. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]' <<< '[0, 4, 1, 2, 0, 1, 2, 4, 0]'
[4,1,2,0,1,2,4]

bash-4.3$ jq -c '. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]' <<< '[0, 0, 0, 0, 0, 0]'
[]

On-line test:

manatwork

Posted 2016-02-12T18:27:51.363

Reputation: 17 865

1

Groovy, 43 characters

{x={it.dropWhile{it<1}.reverse()};x(x(it))}

Sample run:

groovy:000> ({x={it.dropWhile{it<1}.reverse()};x(x(it))})([0, 4, 1, 2, 0, 1, 2, 4, 0])
===> [4, 1, 2, 0, 1, 2, 4]

groovy:000> ({x={it.dropWhile{it<1}.reverse()};x(x(it))})([0, 0, 0, 0, 0, 0])
===> []

manatwork

Posted 2016-02-12T18:27:51.363

Reputation: 17 865

1

sed, 24 bytes

#!/bin/sed -f
:
s/ 0$//
s/^0\b \?//
t

Input as space-separated words on stdin.

It cost me five bytes (\b \?) to deal with the special case of all zeros.

Test results

$ ./71877.sed <<EOF
0 0 0 8 1 4 3 5 6 4 1 2 0 0 0 0
0 4 1 2 0 1 2 4 0
0 0 0 0 0 0
3 4 5 0 0
6
EOF
8 1 4 3 5 6 4 1 2
4 1 2 0 1 2 4

3 4 5
6

Toby Speight

Posted 2016-02-12T18:27:51.363

Reputation: 5 058

1

C#, 134 bytes

using System.Linq;n=>string.Join(" ",n).Trim('0',' ').Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries).Select(s=>int.Parse(s));

If I can return a comma separated string of the return values:

C#, 36 bytes

n=>string.Join(",",n).Trim('0',',');

TheLethalCoder

Posted 2016-02-12T18:27:51.363

Reputation: 6 930

1

PHP, 61 bytes

<?=preg_replace("^[^_]*_(0_)*(.*)(_0)*$","$2",join(_,$argv));

regexp using the underscore as delimiter.

Titus

Posted 2016-02-12T18:27:51.363

Reputation: 13 814

<?=preg_replace("#^[^_]*_(0_)*(.*?)(_0)*$#","$2",join(_,$argv)); works better for $argv=["t.php",0, 4, 1, 2, 0, 1, 2, 4, 0]; or you should take <?=preg_replace("^[^_]*_(0_)*(.*?)(_0)*$","$2",join(_,$argv)); instead – Jörg Hülsermann – 2016-10-05T22:55:43.213

1

PHP, 41 Bytes

<?="[".trim(join(",",$_GET[a]),",0")."]";

If the input as array could be write as ?a=0&b=0 and so on it can be reduce to 38 Bytes

<?="[".trim(join(",",$_GET),",0")."]";

The longer way working with Regex 65 Bytes

<?="[".preg_replace("#^(0,)*|(,0)*$#","",join(",",$_GET[a]))."]";

Jörg Hülsermann

Posted 2016-02-12T18:27:51.363

Reputation: 13 026

Invalid, consider input: 0 10, output [1] – aross – 2016-10-05T15:24:58.057

@aross in the question is to read non-negative integers like this: followed with no integer greater then 9. let me remenber you to your own opinion at http://codegolf.stackexchange.com/questions/94832/yes-of-course-im-an-adult/94842#94842 You are right if there could been an integer greater then 10 my answer is not valid

– Jörg Hülsermann – 2016-10-05T15:57:26.847

The other challenge explicitly specified a range of input. Though I only just realized that this challenge doesn't clarify that (someone asked about it on OP). Usually it's safe to assume that there's no limit if none is posted though... – aross – 2016-10-05T16:04:55.833

Normally this would be considered optimizing for the specified test-cases which is a loophole.

– aross – 2016-10-05T16:06:10.493

1

///, 20 bytes

/[0 /[// 0]/]//[0]//

Try it online!

Input as list of integers separated by spaces and surrounded by square brackets ([0 1 2 3 4 5 0]).

acrolith

Posted 2016-02-12T18:27:51.363

Reputation: 3 728

1

PHP, 30 bytes

<?=trim(join(' ',$argv),' 0');

Needs to be saved in a file called '0' (or any number of 0s). Works with all test cases (which are <10 at time of submission) but if a test case with a final non 0 integer of 10 (or any other integer with a 0 units digit) gets added then it will no longer be valid.

use like:

php 0 0 4 1 2 0 1 2 4 0

Where the first 0 is the file name and the rest is the input

A bunch of answers got added between me loading the challenge and submitting this. I'd delete it but I never finished the account sign up, would a mod do so please?

user59178

Posted 2016-02-12T18:27:51.363

Reputation: 1 007

0

Pari/GP, 27 bytes

p->Vecrev(polrecip(Pol(p)))

When a list is converted to a polynomial, the leading zeros are removed. Then we can take the reciprocal polynomial, and convert it back to a list, and the trailing zeros are removed.

Try it online!

alephalpha

Posted 2016-02-12T18:27:51.363

Reputation: 23 988

0

Racket 73 bytes

(λ(l)(define(g k)(if(= 0(car k))(g(cdr k))k))(reverse(g(reverse(g l)))))

Ungolfed:

(define f
  (λ(l)
    (define (g k)                     ; fn to remove leading zeros; 
        (if(= 0 (first k))
           (g (rest k))
           k))
    (reverse (g (reverse (g l))))))

Last line removes leading 0s in original and reversed list. List is re-reversed to get original order.

Testing with different combinations:

(f '(0 0   2 5 0 6 8 9   0 0))
(f '(0 0 0 2 5 0 6 8 9   0 0 0))

(f '(0 0 0 2 5 0 6 8 9   0 0))
(f '(0 0   2 5 0 6 8 9   0 0 0))

(f '(0 0   2 5 0 6 8 9))
(f '(0 0 0 2 5 0 6 8 9))

(f '(2 5 0 6 8 9   0 0))
(f '(2 5 0 6 8 9   0 0 0))

(f '(2 5 0 6 8 9))

Output:

'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)

rnso

Posted 2016-02-12T18:27:51.363

Reputation: 1 635

0

PHP, 144 126 chars

It's a bit longer than the other PHP answers because it's array-based.

function e($a){foreach($a as$i=>$v){if($v)break;unset($a[$i]);}return array_reverse($a);}print_r(e(e(explode(",",$argv[1]))));

Call like this: php remove0.php 0,4,2,1,0,1,2,4,0

Example return:

Array
(
    [0] => 4
    [1] => 2
    [2] => 1
    [3] => 0
    [4] => 1
    [5] => 2
    [6] => 4
)

timmyRS

Posted 2016-02-12T18:27:51.363

Reputation: 329

Rearranged it a bit to reduce it to 126 characters, without changing the logic: http://pastebin.com/HMSGfftE

– manatwork – 2016-10-06T17:20:23.750

@manatwork thanks, changed it. – timmyRS – 2016-10-06T17:31:17.277

According to discussion in Running PHP with -r instead of code tags and Is the PHP opening tag mandatory in byte count?, running code with php -r is acceptable, so no need the <?.

– manatwork – 2016-10-06T17:38:30.733

@manatwork Thanks, changed it ^^ – timmyRS – 2016-10-06T17:43:01.983

0

Python 3, 48 55 29 26 bytes

print(input().strip('0 '))

Input and output is taken as space-separated numbers, eg:

0 0 0 1 3 1 4 0 1 3 6 4 5 19 3 1 4 0

Alternatively, a 29-byte Python 2 solution:

print raw_input().strip('0 ')

Oliver Ni

Posted 2016-02-12T18:27:51.363

Reputation: 9 650

This chops off trailing 0s from numbers divisible with 10: python3 -c "print(input().strip('0 '))" <<< '0 2000 0'. – manatwork – 2016-10-07T07:46:36.913