36
\$\begingroup\$

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

\$\endgroup\$
8
  • \$\begingroup\$ Are the numbers non-negative integers only? I suggest you clarify that or add test cases with other numbers \$\endgroup\$ – Luis Mendo Feb 12 '16 at 20:08
  • 1
    \$\begingroup\$ Can we assume that there will be at least one leading and one trailing 0? \$\endgroup\$ – DJMcMayhem Feb 12 '16 at 20:24
  • 4
    \$\begingroup\$ 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 ) \$\endgroup\$ – Brad Gilbert b2gills Feb 13 '16 at 0:41
  • 10
    \$\begingroup\$ 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? \$\endgroup\$ – A Simmons Feb 13 '16 at 17:57
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Mwr247 Feb 24 '16 at 18:18

51 Answers 51

1
2
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 48 bytes

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

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.

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Mathematica, 33 bytes

#/.{Longest[0...],x__,0...}->{x}&
\$\endgroup\$
1
\$\begingroup\$

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:

\$\endgroup\$
1
\$\begingroup\$

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])
===> []
\$\endgroup\$
1
\$\begingroup\$

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

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',',');
\$\endgroup\$
1
\$\begingroup\$

PHP, 61 bytes

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

regexp using the underscore as delimiter.

\$\endgroup\$
1
  • \$\begingroup\$ <?=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 \$\endgroup\$ – Jörg Hülsermann Oct 5 '16 at 22:55
1
\$\begingroup\$

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]))."]";
\$\endgroup\$
4
  • \$\begingroup\$ Invalid, consider input: 0 10, output [1] \$\endgroup\$ – aross Oct 5 '16 at 15:24
  • \$\begingroup\$ @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 \$\endgroup\$ – Jörg Hülsermann Oct 5 '16 at 15:57
  • \$\begingroup\$ 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... \$\endgroup\$ – aross Oct 5 '16 at 16:04
  • \$\begingroup\$ Normally this would be considered optimizing for the specified test-cases which is a loophole. \$\endgroup\$ – aross Oct 5 '16 at 16:06
1
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

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

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.

\$\endgroup\$
1
\$\begingroup\$

MATLAB, 38 32 bytes

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

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.
  • 'reverse' can be replaced simply with 'r'

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.

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

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

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

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

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!

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

05AB1E, 2 bytes

Built-in version. :)

Try it online!

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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