Usuń zera początkowe i końcowe


Biorąc pod uwagę niepustą listę / tablicę zawierającą tylko nieujemne liczby całkowite takie jak to:

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

Wypisuje listę z usuniętymi końcowymi i wiodącymi zerami.

Dane wyjściowe dla tego będą:

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

Niektóre inne przypadki testowe:

[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]

Najkrótszy kod wygrywa

Czy liczby są tylko liczbami całkowitymi nieujemnymi? Sugeruję wyjaśnienie tego lub dodanie przypadków testowych z innymi liczbami
Luis Mendo,

Czy możemy założyć, że będzie co najmniej jedno wiodące i jedno końcowe 0?

Co nie stanowi niczego? Mogę wymyślić kilka różnych rzeczy, które są odmianami niczego w Perlu 6. Nil ()/ [] slip()/ Empty Any {}niektóre z nich są niezdefiniowane, niektóre zdefiniowane, ale osobliwe, niektóre, które wpadają na inne listy, tak że nie zwiększają liczby elementów. (Istnieje tyle różnych odmian, Anyile klas / typów i ról)
Brad Gilbert b2gills

Czy to przypadek, że nie ma liczb całkowitych powyżej 10, czy możemy założyć, że wszystkie liczby będą jednocyfrowe?
A Simmons,

Czy możemy wprowadzić / wyprowadzić listę jako ciąg rozdzielany? Na przykład: "0,4,1,2,0,1,2,4,0" => "4,1,2,0,1,2,4"EDYCJA: Zauważyłem, że wiele języków już to robi.



JavaScript (ES6) 43


Mniej golfa

  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



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

#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>

Miły. f=(a,r=f(a,a))=>r.reverse().filter(x=>a|=x)ma również 43 bajty.


CJam, 13 bajtów


Po wprowadzeniu tablicy.

Dłuższa wersja:

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

Chciałbym móc wykorzystać fakt, że konwersja do i z bazy usunęłaby początkowe zera, ale wygląda na to, że jest za długa.
Esolanging Fruit


Pyth, 4 bajty



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]

Od Pytharev-doc.txt :

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


R, 43 bytes


or as read/write STDIN/STDOUT


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.


Mathematica 34 27 bytes


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.



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

@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

Via evil HTML hacks. ;)
Martin Ender

17+1 bytes: s/^0 | 0$//&&redo

@Kenney That is beautiful :-) You should post that as an answer!

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"..


Jelly, 10 bytes


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.


Perl, 38 bytes


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 
    # 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

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.


Elixir, 77 bytes

import Enum
z=fn x->x==0 end

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).


Vitsy, 13 bytes

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


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.


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

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.


Vitsy will get Jelly some day.
Conor O'Brien

Add auto-bracket matching on EOL/EOF


R, 39 bytes


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.


MATL, 9 bytes


Try it online!


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


Dyalog APL, 15 bytes


               ⍣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.

How about {⌽⍵/⍨×+\⍵}⍣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.

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]]}

Doh. No need for 2 functions, just some eval ugliness: ->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2}.

@manatwork Not sure why I didn't think of <1, anyway. Thanks!


Vim 16 Keystrokes


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>

I 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>


ES6, 51 bytes


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 6, 23 bytes

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


# 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)


JavaScript (ES6), 47 bytes


Where a is the array.

I think you need to make an anonymous function to take input: a=>a.join(a="")....

This only handles integers properly when they're a single digit

@dev-null Done.

Still returning wrong for multi-digit integers. [14] will return [1, 4].

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.


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".


Javascript (ES6) 40 bytes



PHP, 56 54 52 bytes

Uses Windows-1252 encoding

String based solution


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


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

Can you please provide an ASCII solution. Nobody can read this!

@Titus Sure. However, plenty of unreadable esolangs out there.... it's not like my answer doesn't feel right at home.

An array as first parameter of join?
Jörg Hülsermann

@JörgHülsermann Yup. It's documented the other way around but it accepts both.

You are right I have not realize it
Jörg Hülsermann


PowerShell, 49 bytes


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]}

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.

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.