42
\$\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, 2016 at 20:08
  • 1
    \$\begingroup\$ Can we assume that there will be at least one leading and one trailing 0? \$\endgroup\$
    – DJMcMayhem
    Feb 12, 2016 at 20:24
  • 5
    \$\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\$ Feb 13, 2016 at 0:41
  • 13
    \$\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, 2016 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, 2016 at 18:18

62 Answers 62

2
\$\begingroup\$

Python 2, 69 67 bytes

def f(a):
 for i in(0,-1):
  while a and a[i]==0:a.pop(i)
 return a
\$\endgroup\$
4
  • \$\begingroup\$ You can remove the space before your tuple in the second line. \$\endgroup\$
    – Zach Gates
    Feb 21, 2016 at 19:16
  • \$\begingroup\$ You can do for i in-1,0: \$\endgroup\$
    – mbomb007
    Oct 4, 2016 at 14:51
  • \$\begingroup\$ 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. mothereff.in/… \$\endgroup\$
    – mbomb007
    Oct 4, 2016 at 15:00
  • \$\begingroup\$ I count 67 bytes. \$\endgroup\$ Oct 5, 2016 at 14:44
2
\$\begingroup\$

///, 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]).

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

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\$

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\$
2
\$\begingroup\$

Trilangle, 78 bytes

<>?@.#<...#)!j.(,2#_|...><.L/(,\@^_\L\.\.#\S.?S>S(.<)).7),..\._v..._|..._>#('0

Try it on the online interpreter! Output is separated by newlines.

This is some of the control flow of all time.

           <
          > ?
         @ . #
        < . . .
       # ) ! j .
      ( , 2 # _ |
     . . . > < . L
    / ( , \ @ ^ _ \
   L \ . \ . # \ S .
  ? S > S ( . < ) ) .
 7 ) , . . \ . _ v . .
. _ | . . . _ > # ( ' 0

This is definitely the most colors I've had to use in this size of grid. Let's break this down:

The first loop -- red, blue, and yellow -- ignores input until it sees something other than 0. If it reaches EOF before finding a positive value, the green path terminates the program with no output.

The next loop -- orange and yellow-green -- counts how much input there is after the first positive number.

The third loop -- cyan and brown -- removes zeroes from the end of the array and decreases the counter as it goes.

The final loop -- gray and red-violet -- prints out what's left. The purple branch terminates the program once it's exhausted the list.

\$\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\$ Oct 5, 2016 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, 2016 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\$ Oct 5, 2016 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, 2016 at 16:04
  • \$\begingroup\$ Normally this would be considered optimizing for the specified test-cases which is a loophole. \$\endgroup\$
    – aross
    Oct 5, 2016 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\$

05AB1E, 2 bytes

Built-in version. :)

Try it online!

\$\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\$

Japt -h, 6 bytes

ã fÎfÌ

Try it

2Æ=Ôf|

Try it

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

Python 2/3, 48 bytes

lambda x:map(int,''.join(map(str,x)).strip('0'))

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Realized after posting that Adam Abahot posted an identical answer (excluding the name) \$\endgroup\$
    – Hunaphu
    Apr 27, 2023 at 1:40
1
\$\begingroup\$

TypeScript's Type System, 69 bytes

type T<R>=R extends[...infer K,0]?T<K>:R extends[0,...infer K]?T<K>:R

TypeScript Playground

Explanation

By using infer, we can take out portions of the array that don't start or end in 0 recursively:

type T<R> = 
    R extends [...infer K, 0] ? T<K> : // take out trailing zeros
    R extends [0, ...infer K] ? T<K> : // and leading zeros
    R; // if none are left, return the final array.

Since we use extends, we don't need to bind the input parameters to a type (e.g. using T<"input"> simply returns "input")

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

JavaScript (Node.js), 58 bytes

Not the best JS answer, but a different approach not using regexp, replace, nor filter.
(Like other answers, we assume that the array input can only contain integers <= 9)

t=>(r=(g=a=>[...""+a.reverse().join``*1])(g(t)))[0]*1?r:[]

Try it online!


Converts the array into a number to get rid of the leading zeros.

Then we do this a second time on the reversed array to get rid of the leading (previously trailing) zeros, and reverse back again to get the answer array in the correct order.

The case were the array contains only zeros had to be specifically handled (or else it would have resulted in a [0] output), and this part has a cost of 14 bytes :(

\$\endgroup\$
0
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
  • 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, 2016 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\$

Vyxal, 2 bytes

0P

Try it Online!

What it says on the box. StriPs 0s.

\$\endgroup\$
1
  • \$\begingroup\$ AKA "cyclops sticking its tongue out" \$\endgroup\$
    – DLosc
    Apr 27, 2023 at 17:09
0
\$\begingroup\$

Julia 1.0, 15 bytes

~x=strip(x,'0')

Try it online!

Accepts a String input.

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

BQN, 10 bytes

⌈`∘×⊸/∘⌽⍟2

Anonymous tacit function; takes a list, returns a list. Try it at BQN online!

Explanation

⌈`∘×⊸/∘⌽⍟2
      ∘⌽    Reverse the list; then,
    ⊸/      select the elements matching the 1s in the following list:
   ×         Get the sign of each number in the list (0 or 1)
⌈`∘          Scan by maximum: preserves leading 0s, but turns all others into 1s
            All but the leading run of zeros is therefore kept
        ⍟2  Do this twice
\$\endgroup\$
0
\$\begingroup\$

Python 3, 101 bytes

def f(l,n,a=0):
 while l[a]==0:
  del l[a];a+=1;n-=1
 a=n-1
 while l[a]==0:
  del l[a];a-=1
 return l

Try it online!

\$\endgroup\$

Your Answer

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

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