| Bytes | Lang | Time | Link |
|---|---|---|---|
| 026 | Juby | 250512T152532Z | Jordan |
| 078 | Trilangle | 230901T212528Z | Bbrk24 |
| 058 | JavaScript Node.js | 230502T153218Z | Fhuvi |
| 069 | TypeScript's Type System | 230501T174132Z | Tristan |
| 021 | ReRegex | 230501T000924Z | ATaco |
| 078 | C gcc | 230427T160450Z | evanstar |
| 101 | Python 3 | 230428T192308Z | Larry Ba |
| 048 | Python 2/3 | 230427T004109Z | Hunaphu |
| 010 | BQN | 230427T215015Z | DLosc |
| 015 | Julia 1.0 | 230427T191610Z | Ashlin H |
| 006 | Japt h | 230427T091338Z | Shaggy |
| 002 | Vyxal | 221015T025245Z | emanresu |
| 032 | MATLAB | 210512T204634Z | elementi |
| 012 | Brachylog | 200521T063748Z | Unrelate |
| 016 | Factor | 210513T043959Z | chunes |
| 024 | AWK | 210513T010331Z | Pedro Ma |
| 022 | Jellyfish | 210512T165131Z | Razetime |
| 002 | 05AB1E | 200522T121252Z | user9206 |
| 054 | JavaScript V8 | 200522T082658Z | Yaroslav |
| 048 | Python 3 | 200521T053053Z | Adam Aba |
| 027 | Pari/GP | 170520T131815Z | alephalp |
| 009 | MATL | 160212T200647Z | Luis Men |
| 020 | /// | 161005T230420Z | acrolith |
| 030 | PHP | 161007T140607Z | user5917 |
| 026 | Python 3 | 161007T011539Z | Oliver N |
| 067 | Python 2 | 160221T174527Z | SumnerHa |
| 073 | Racket | 161006T130219Z | rnso |
| 126 | PHP | 161006T170339Z | Paper |
| 041 | PHP | 161005T144527Z | Jör |
| 061 | PHP | 161005T133812Z | Titus |
| 052 | PHP | 160213T232705Z | aross |
| 039 | R | 161005T124446Z | rturnbul |
| 134 | C# | 161005T121203Z | TheLetha |
| 004 | 05AB1E | 160411T091421Z | Sake |
| 040 | Javascript ES6 | 160224T194319Z | Shaun H |
| 034 | JavaScript ES6 | 160224T182912Z | Mwr247 |
| 024 | sed | 160223T183234Z | Toby Spe |
| 043 | Groovy | 160223T180106Z | manatwor |
| 029 | Haskell | 160221T173358Z | Itai Bar |
| 043 | R | 160221T151823Z | David Ar |
| 013 | Vitsy | 160221T161926Z | Addison |
| 084 | Python | 160221T132444Z | pafcjo |
| 047 | JavaScript ES6 | 160213T170853Z | user2428 |
| 077 | Elixir | 160213T202506Z | srecnig |
| 011 | Retina | 160213T193455Z | Mama Fun |
| 043 | JavaScript ES6 | 160213T180416Z | edc65 |
| 048 | jq | 160213T192533Z | manatwor |
| 027 | Mathematica | 160212T201937Z | DavidC |
| 033 | Mathematica | 160213T172745Z | A Simmon |
| 013 | CJam | 160213T181433Z | Angela X |
| 023 | Perl 6 | 160213T032956Z | Brad Gil |
| 051 | ES6 | 160213T002431Z | Neil |
| 038 | Perl | 160212T204538Z | David Mo |
| nan | 160212T203236Z | DJMcMayh | |
| 049 | PowerShell | 160212T200912Z | AdmBorkB |
| 044 | Ruby | 160212T184240Z | Doorknob |
| 010 | Jelly | 160212T193426Z | lirtosia |
| 012 | Retina | 160212T190110Z | Andreas |
| 015 | Dyalog APL | 160212T191704Z | lirtosia |
| nan | Perl | 160212T185543Z | Andreas |
| 004 | 05AB1E | 160212T184836Z | Adnan |
| 002 | Jelly | 160212T183743Z | Adnan |
| 004 | Pyth | 160212T183253Z | Doorknob |
J-uby, 26 bytes
Like Doorknob's Ruby solution but using J-uby's ** operator to apply the transformation twice instead of eval.
(:drop_while+(:>&1)|:~)**2
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.
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:[]
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 :(
TypeScript's Type System, 69 bytes
type T<R>=R extends[...infer K,0]?T<K>:R extends[0,...infer K]?T<K>:R
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")
ReRegex, 21 bytes
\[0,?/[/,?0]/]/#input
A very simple solution consisting of two regexes, each stripping 0's from the start and end respectively.
C (gcc), 80 78 bytes
-2 bytes thanks to ceilingcat by using strlen() and indexing into the string
p;f(char*s){for(;*s&&*s<49;s++);for(p=strlen(s);p&&s[p]<49;s[p--]=0);puts(s);}
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
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
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 ofcummaxfunctions) are transformed into logical arrays in a way that0isfalseand anything else istrue.cummax(x))&cummax(x,'reverse')gives thus logical array withtruefor values we need to include andfalsefor trailing/leading zeros.x(cummax(x))&cummax(x,'reverse'))performs logical indexing - only values where corresponding logical value istrueare 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.
Brachylog, 12 bytes
{↔a₁.h>0∧}ⁱ²
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∨Ė}ⁱ²
If the input can be assumed to contain only single digits, it's quite a bit shorter:
Brachylog, 6 bytes
c↔↔ℕ₁ẹ
Factor, 16 bytes
[ [ 0 = ] trim ]
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.
AWK, 24 bytes
gsub(/^(0 )*|( *0)*$/,e)
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.
Jellyfish, 22 bytes
p
\A2
~R
(#
~*
\
/
+
i
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
JavaScript (V8), 54 bytes
s=>(g=a=>a.filter(e=>e^k?k=1:k,k=0).reverse(),g(g(s)))
JavaScript (V8), 52 bytes
f=(s,q=f(s,s))=>q.filter(e=>e^k?k=1:k,k=0).reverse()
Python 3, 48 bytes
lambda a:map(int,''.join(map(str,a)).strip('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.
MATL, 9 bytes
2:"PtYsg)
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
///, 20 bytes
/[0 /[// 0]/]//[0]//
Input as list of integers separated by spaces and surrounded by square brackets ([0 1 2 3 4 5 0]).
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?
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 ')
Python 2, 69 67 bytes
def f(a):
for i in(0,-1):
while a and a[i]==0:a.pop(i)
return a
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)
PHP, 144 126 chars
- -18 chars thanks to @manatwork
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
)
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]))."]";
PHP, 61 bytes
<?=preg_replace("^[^_]*_(0_)*(.*)(_0)*$","$2",join(_,$argv));
regexp using the underscore as delimiter.
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
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.
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',',');
05AB1E, 4 bytes
0Û0Ü
Basically trimming leading then trailing zeroes of the input, given as an array.
Javascript (ES6) 40 bytes
a=>/^(0,)*(.*?)(,0)*$/.exec(a.join())[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".
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
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])
===> []
Haskell, 29 bytes
t=f.f;f=reverse.dropWhile(<1)
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.
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.
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
JavaScript (ES6), 47 bytes
a=>a.join(a="").replace(/(^0+|0+$)/g,a).split(a)
Where a is the array.
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).
Retina, 11 bytes
+`^0 ?| 0$
<empty>
Quite simple. Recursively replaces zeroes at beginning and end of line.
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>
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:
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.
Mathematica, 33 bytes
#/.{Longest[0...],x__,0...}->{x}&
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
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)
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.
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
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>
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.
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.
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.
Retina, 12 bytes
^0 ?
)` 0$
The trailing linefeed is significant.
Thanks to @Martin Büttner and @FryAmTheEggman for saving a few bytes.
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.
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
05AB1E, 4 bytes
Code:
0Û0Ü
Explanation:
0Û # Trim off leading zeroes
0Ü # Trim off trailing zeroes
Uses CP-1252 encoding.
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.
