Remove leading and trailing zeroes

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

• Are the numbers non-negative integers only? I suggest you clarify that or add test cases with other numbers – Luis Mendo Feb 12 '16 at 20:08
• Can we assume that there will be at least one leading and one trailing 0? – James Feb 12 '16 at 20:24
• What 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 Feb 13 '16 at 0:41
• Is 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 Feb 13 '16 at 17:57
• Can 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 Feb 24 '16 at 18:18

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!

Python 3, 48 bytes

lambda a:map(int,''.join(map(str,a)).strip('0'))
• While it works for the given test cases, it fails if the input array contains number 10 or higher. – Bubbler May 21 '20 at 6:08

Factor, 16 bytes

[ [ 0 = ] trim ]

Try it online!

Factor has a combinator for this. You just have to supply it with a quotation that returns t for the element(s) you want to trim.

Brachylog, 12 bytes

{↔a₁.h>0∧}ⁱ²

Try it online!

The predicate fails in the case of "nothing".

a₁.           Take the longest suffix of
↔              the input reversed
h          the first element of which
>0        is greater than 0
∧       (which is not the output).
{        }ⁱ²    Do it again.

If "nothing" has to be some actual value, like an empty list, it's only one more byte:

Brachylog, 13 bytes

{↔a₁.h>0∨Ė}ⁱ²

Try it online!

If the input can be assumed to contain only single digits, it's quite a bit shorter:

Brachylog, 6 bytes

c↔↔ℕ₁ẹ

Try it online!

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.

[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: 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]) ===> [] 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.

$./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 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',','); PHP, 61 bytes <?=preg_replace("^[^_]*_(0_)*(.*)(_0)*$","$2",join(_,$argv));

regexp using the underscore as delimiter.

• <?=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 Oct 5 '16 at 22:55 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]))."]"; • Invalid, consider input: 0 10, output [1] – aross Oct 5 '16 at 15:24 • @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 codegolf.stackexchange.com/questions/94832/… You are right if there could been an integer greater then 10 my answer is not valid – Jörg Hülsermann Oct 5 '16 at 15:57 • 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 Oct 5 '16 at 16:04 • Normally this would be considered optimizing for the specified test-cases which is a loophole. – aross Oct 5 '16 at 16:06 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?

Jellyfish, 22 bytes

p
\A2
~R
(#
~*
\
/
+
i

Try it online!

Explanation

p   print the result of:
\A2 repeat the following twice:
~R  compose reverse with the below
(#  filter the elements of the input by the following function:
~*  compose sign with:
\   map each prefix to:
/    fold by:
+    addition
i   evaluated input

MATLAB, 38 bytes

@(x)x((cummax(x))&cummax(x,'reverse'))

Anonymous function, saved to default output variable Ans.
Tried different ideas but the simplest stayed the shortest. Also I should note that instead of cummmax you can use cumsum as well.
Unfortunately, doesn't work with Octave, because its implementation of cummax and cumsum doesn't allow for reversing the direction. For Octave alternative solution below.

How does it work?

• cummax(x) takes cumulative maximal value, so everything besides leading zeros is greater than 0.
• cummax(x,'reverse') does the same but in reversed direction - everything besides trailing zeros is greater than 0.
• & is logical conjunction (AND) on arrays. Both numeric arrays (results of cummax functions) are transformed into logical arrays in a way that 0 is false and anything else is true.
• cummax(x))&cummax(x,'reverse') gives thus logical array with true for values we need to include and false for trailing/leading zeros.
• x(cummax(x))&cummax(x,'reverse')) performs logical indexing - only values where corresponding logical value is true are selected.

Octave, 40 bytes

@(x)x((cummax(x))&flip(cummax(flip(x))))

Try it online!
Basically the same as MATLAB solution, only cummax(x,'reverse') is replaced with flip(cummax(flip(x))) - the x is flipped, then cummax and then result is flipped.

AWK, 24 bytes

gsub(/^(0 )*|( *0)*$/,e) Try it online! Using a convenient input to awk's default field separator (space). No easy way to define an array here. This substitutes every match to the regex /^(0 )*|( *0)*$/ for a null string (variable e, not defined). Even if there are no trailing zeros, null matches are found before and after the input, so gsub() always returns a positive number, and the input (modified or not) is printed.

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
)

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)

Python 3, 485529 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 ')
• This chops off trailing 0s from numbers divisible with 10: python3 -c "print(input().strip('0 '))" <<< '0 2000 0'. – manatwork Oct 7 '16 at 7:46

JavaScript (V8), 54 bytes

s=>(g=a=>a.filter(e=>e^k?k=1:k,k=0).reverse(),g(g(s)))

Try it online!

JavaScript (V8), 52 bytes

f=(s,q=f(s,s))=>q.filter(e=>e^k?k=1:k,k=0).reverse()

Try it online!

05AB1E, 2 bytes

Built-in version. :)

Try it online!