Skip like a rabbit!

41

4

Given a list of non-negative integers in any reasonable format, iterate over it, skipping as many elements as every integer you step on says.


Here is a worked example:

[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | []
 ^ First element, always include it
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0]
    ^ Skip 0 elements
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1]
          ^ Skip 1 element
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1, 2]
                   ^ Skip 2 elements
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1, 2, 3]
Skip 3 elements; you're done

Another worked example, not so all-equal-deltas:

[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | []
 ^ First element, always include it
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4]
                ^ Skip 4 elements
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3]
                            ^ Skip 3 elements
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3, 3]
                                        ^ Skip 3 elements
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3, 3, 4]
Skip 4 elements; you're done

An out-of-bounds example:

[0, 2, 0, 2, 4, 1, 2] | []
^ First element, always include it
[0, 2, 0, 2, 4, 1, 2] | [0]
    ^ Skip 0 elements
[0, 2, 0, 2, 4, 1, 2] | [0, 2]
             ^ Skip 2 elements
[0, 2, 0, 2, 4, 1, 2] | [0, 2, 4]
Skip 4 elements; you're done (out of bounds)

Rules

  • You may not use any boring cheat among these ones, they make the challenge boring and uninteresting.
  • You should only return/print the final result. STDERR output is ignored.
  • You may not get the input as a string of digits in any base (e.g. "0102513162" for the first case).
  • You must use left-to-right order for input.
  • As in the worked examples, if you go out of bounds, execution terminates as if otherwise.
  • You should use 0 for skipping 0 elements.
  • Given the empty list ([]) as input, you should return [].

Test cases

[]                                                     => []
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                     => [0, 1, 3, 7]
[5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]                   => [5, 2, 1, 0]
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2]                         => [0, 1, 2, 3]
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] => [4, 3, 3, 4]
[0, 2, 0, 2, 4, 1, 2]                                  => [0, 2, 4]

This is , so shortest answer wins!

Erik the Outgolfer

Posted 2017-07-28T10:56:18.837

Reputation: 38 134

1Is it okay to have trailing zeros in my array? would save me ~18 bytes – Roman Gräf – 2017-07-28T11:15:04.130

@EriktheOutgolfer Could we output a string array and have trailing empty strings? – TheLethalCoder – 2017-07-28T11:17:10.623

1@TheLethalCoder Sorry I'd say no since that's not reasonable imo...can't you just remove trailing ""s? – Erik the Outgolfer – 2017-07-28T11:25:20.743

2@RomanGräf Sorry but no, that would be too ambiguous since there are cases you should have trailing 0s in the output. – Erik the Outgolfer – 2017-07-28T11:25:51.520

Answers

14

Python 2, 36 bytes

f=lambda x:x and x[:1]+f(x[x[0]+1:])

Try it online!

Rod

Posted 2017-07-28T10:56:18.837

Reputation: 17 588

I was expecting to get outgolfed, but not that badly :) – Mr. Xcoder – 2017-07-28T11:31:23.527

Can't you do x[0] instead of x[:1]? – Erik the Outgolfer – 2017-07-28T11:32:11.977

@EriktheOutgolfer yes, but it need to be a list, so it would be [x[0]] – Rod – 2017-07-28T11:32:51.463

@Rod You're not saving any bytes with x[:1] anyways...f=lambda x:x and[x[0]]+f(x[x[0]+1:]) – Erik the Outgolfer – 2017-07-28T11:33:50.713

13

Python 2, 49 44* 41 bytes

Crossed out 44 is still regular 44 :(

* -3 thanks to @ASCII-only.

l=input()
while l:print l[0];l=l[l[0]+1:]

Try it online!

Prints the results separated by a newline, as the OP allowed in chat. I don't think it can get any shorter as a non-recursive full program.


How does this work?

  • l=input() - Reads the list from the standard input.

  • while l: - Abuses the fact that empty lists are falsy in Python, loops until the list is empty.

  • print l[0]; - Prints the first element of the list.

  • l=l[l[0]+1:] - "Skips like a rabbit" - Trims the first l[0]+1 from the list.

Let's take an example

Given the list [5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0] as input, the code performs the following (according to the explanation above) - Prints the first item of the array: 5, trim the first 6: [2, 1, 2, 1, 0, 0]. We then print 2 and trim the first 3: [1,0,0]. Likewise, we output 1, crop the first 2, and we get [0]. Of course, 0 is printed and the program terminates.

Mr. Xcoder

Posted 2017-07-28T10:56:18.837

Reputation: 39 774

46 bytes – ASCII-only – 2017-07-28T11:20:03.813

11

Haskell, 29 27 26 bytes

j(x:y)=x:j(drop x y)
j x=x

Saved 1 byte thanks to Zgarb.

Try it online.

Cristian Lupascu

Posted 2017-07-28T10:56:18.837

Reputation: 8 369

f x=x on the second line saves a byte. – Zgarb – 2017-07-28T12:27:20.983

9

JavaScript (ES6), 42 39 35 bytes

a=>a.map((n,i)=>a.splice(i+1,n))&&a

let f = 
a=>a.map((n,i)=>a.splice(i+1,n))&&a

console.log(f([]))                                                     // => []
console.log(f([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))                     // => [0, 1, 3, 7]
console.log(f([5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]))                   // => [5, 2, 1, 0]
console.log(f([0, 1, 0, 2, 5, 1, 3, 1, 6, 2]))                         // => [0, 1, 2, 3]
console.log(f([4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2])) // => [4, 3, 3, 4]
console.log(f([0, 2, 0, 2, 4, 1, 2]))                                  // => [0, 2, 4]

Old Solution 39 Bytes

a=>a.map(n=>i--||r.push(i=n),r=i=[])&&r

-3 bytes thanks to @ThePirateBay

Johan Karlsson

Posted 2017-07-28T10:56:18.837

Reputation: 670

39 bytes a=>a.map(n=>i--||r.push(i=n),r=i=[])&&r – None – 2017-07-28T11:47:48.223

8

05AB1E, 10 9 bytes

[¬Dg>#=ƒ¦

Uses the 05AB1E encoding. Try it online!

Adnan

Posted 2017-07-28T10:56:18.837

Reputation: 41 965

Yeah, that is way better than what I was thinking. – Magic Octopus Urn – 2017-07-28T13:57:25.830

8

Mathematica, 46 44 bytes

SequenceCases[#,{x_,y___}/;Tr[1^{y}]<=x:>x]&

Alternatives:

SequenceCases[#,{x_,y___}/;x>=Length@!y:>x]&
SequenceCases[#,l:{x_,___}/;x>Tr[1^l]-2:>x]&

Martin Ender

Posted 2017-07-28T10:56:18.837

Reputation: 184 808

7

C#, 68 bytes

a=>{for(int i=0;i<a.Count;i+=a[i]+1)System.Console.Write(a[i]+" ");}

Try it online!

Full/Formatted version:

namespace System
{
    class P
    {
        static void Main()
        {
            Action<Collections.Generic.List<int>> f = a =>
            {
                for (int i = 0; i < a.Count; i += a[i] + 1)
                    System.Console.Write(a[i] + " ");
            };

            f(new Collections.Generic.List<int>() { });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 0, 1, 0, 2, 5, 1, 3, 1, 6, 2 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 0, 2, 0, 2, 4, 1, 2 });Console.WriteLine();

            Console.ReadLine();
        }
    }
}

Returning a list is longer at 107 bytes.

a=>{var l=new System.Collections.Generic.List<int>();for(int i=0;i<a.Count;i+=a[i]+1)l.Add(a[i]);return l;}

TheLethalCoder

Posted 2017-07-28T10:56:18.837

Reputation: 6 930

2Why has someone downvoted this? – TheLethalCoder – 2017-07-28T15:15:00.883

To round your score and make a perfect 5k? – Thomas Ayoub – 2017-07-31T10:13:59.357

@ThomasAyoub We can only assume it was someone with OCD yes. – TheLethalCoder – 2017-07-31T10:20:19.847

6

Husk, 8 6 bytes

←TU¡Γ↓

Try it online!

-2 bytes (and a completely new solution idea) thanks to Leo!

Explanation

I'm using the list pattern match function Γ. It takes a function f and a list with head x and tail xs, and applies f to x and xs. If the list is empty, Γ returns a default value consistent with its type, in this case an empty list. We take f to be , which drops x elements from xs. This function is then iterated and the resulting elements are collected in a list.

←TU¡Γ↓  Implicit input, e.g. [0,2,0,2,4,1,2]
    Γ↓  Pattern match using drop
   ¡    iterated infinitely: [[0,2,0,2,4,1,2],[2,0,2,4,1,2],[4,1,2],[],[],[],...
  U     Cut at first repeated value: [[0,2,0,2,4,1,2],[2,0,2,4,1,2],[4,1,2],[]]
 T      Transpose: [[0,2,4],[2,0,1],[0,2,2],[2,4],[4,1],[1,2],[2]]
←       First element: [0,2,4]

Zgarb

Posted 2017-07-28T10:56:18.837

Reputation: 39 083

You can drop the default value of ø, and everything will still magically work :) – Leo – 2017-07-28T13:36:27.497

Or, for even less bytes, https://tio.run/##yygtzv7//1HbhJDQQwvPTX7UNvn////RBjpGOiBsomOoYxQLAA

– Leo – 2017-07-28T15:34:51.827

@Leo Oh wow, that's clever! – Zgarb – 2017-07-28T17:32:32.420

Why did you CW this? – Erik the Outgolfer – 2017-07-28T17:36:16.187

@ErikTheOutgolfer That was a mistake (I'm on my phone and apparently pushed something by accident). I'm trying to undo it... – Zgarb – 2017-07-28T17:42:26.663

@Zgarb You must flag it for mod attention...flagged it too. – Erik the Outgolfer – 2017-07-28T17:43:12.040

5

Python 2, 59 55 bytes

l=input()
i=0
while l[i:]:i+=1;l[i:i+l[i-1]]=[]
print l

Try it online!

Arfie

Posted 2017-07-28T10:56:18.837

Reputation: 1 230

1You can use l[i:i+l[i-1]]=[] instead del l[i:i+l[i-1]] to save a byte – Rod – 2017-07-28T11:11:50.870

156 bytes – ASCII-only – 2017-07-28T11:18:58.993

5

Pyth, 22 Bytes

VQ aY.(Q0VeY .x.(Q0 ;Y

Removed a useless byte

Dave

Posted 2017-07-28T10:56:18.837

Reputation: 432

I see 23 bytes there. – Erik the Outgolfer – 2017-07-28T13:16:09.357

Typo :) sorry... – Dave – 2017-07-28T13:17:30.420

3I'm not sure why you have a down vote. There is a possibility that when you edited fixing your answer this triggered an "automatic down vote". The reasons for this automatic downvote are confusing and terrible but it happens if the system considers your answer to be "low quality" based on it heuristics. Its also possible that someone didn't like your answer, but I don't see anything wrong with it at the moment so I'm not sure why that would be the case. – Post Rock Garf Hunter – 2017-07-28T13:23:23.820

I'm glad you're using Pyth! – isaacg – 2017-07-31T03:01:05.670

4

Python 2, 60 42 41 bytes

-18 bytes thanks to Luis Mendo
-1 byte thanks to Jonathan Frech

x=input()
i=0
while 1:print x[i];i-=~x[i]

Try it online!

Rod

Posted 2017-07-28T10:56:18.837

Reputation: 17 588

i-=~x[i] is one byte shorter than i+=1+x[i]. – Jonathan Frech – 2017-10-04T17:15:23.917

3

Retina, 36 bytes

Byte count assumes ISO 8859-1 encoding.

.+
$*
((1)*¶)(?<-2>1*¶)*
$1
%M`.
0$

Input and output are linefeed-separated with a trailing linefeed.

Try it online! (Uses commas instead of linefeeds to allow for convenient test suites.)

Martin Ender

Posted 2017-07-28T10:56:18.837

Reputation: 184 808

3

Brain-Flak, 64 bytes

([]){{}(({})<>)<>{({}[()]<{}>)}{}([])}{}<>([]){{}({}<>)<>([])}<>

Try it online!

([]){{}                          ([])}{}                         # Until the stack is empty
       (({})<>)<>                                                # Copy TOS to off stack
                 {({}[()]<{}>)}{}                                # Pop TOS times
                                        <>([]){{}({}<>)<>([])}<> # Reverse off stack

Riley

Posted 2017-07-28T10:56:18.837

Reputation: 11 345

7Holy crap! I wrote up a solution, and then scrolled down to post it, but it turns out we wrote the exact same solution byte-for-byte! Even minor details like ({}[()]<{}>) vs ({}<{}>[()]) were the same! What a coincidence! – James – 2017-07-28T16:54:55.980

@DJMcMayhem stealing all the fame XD – Christopher – 2017-07-28T17:08:31.060

I also made a byte for byte identical solution, but I golfed it down 4 bytes. Just some delayed competition :)

– Post Rock Garf Hunter – 2017-10-05T04:21:09.313

2

Mathematica, 64 50 bytes

±x_List:=Prepend[±Drop[x,1+#&@@x],#&@@x]
±_=±{}={}

user202729

Posted 2017-07-28T10:56:18.837

Reputation: 14 620

I couldn't resist further golfing this neat code; my answer is below. – Mr.Wizard – 2017-07-28T18:29:23.363

2

Java (OpenJDK 8), 53 bytes

Thanks to @PunPun1000 and @TheLethalCoder

a->{for(int n=0;;n+=1+a[n])System.out.println(a[n]);}

Try it online!

Roman Gräf

Posted 2017-07-28T10:56:18.837

Reputation: 2 915

Would printing the results, like in my C# answer, save you anything? – TheLethalCoder – 2017-07-28T11:42:48.727

@TheLethalCoder Ill try – Roman Gräf – 2017-07-28T11:43:12.280

Can you save a byte by moving n into the loop? – TheLethalCoder – 2017-07-28T12:45:23.487

Plus this doesn't seem to work at the moment. – TheLethalCoder – 2017-07-28T12:46:00.167

You're missing a paren after the (a[n+=1+a[n]]. Function also throws an error after outputting the correct value, I don't know the concensus on whether this is allowed or not (the question does say anything to standard error is ignore). If that was the intention, then you can remove the n<a.length in the for loop. Finally the TIO code doesn't run as is, even with the paren. The function should be a Consumer<int[]> and use func.accept(test) – PunPun1000 – 2017-07-28T12:46:12.873

It looks like it's ok to error out, in that case I definitely recommend removing the n<a.length in the for loop: TIO (52 bytes)

– PunPun1000 – 2017-07-28T12:56:00.713

@PunPun1000 your solution skips the first element so i moved n+=... in the for header for an extra byte – Roman Gräf – 2017-07-28T13:00:13.397

You can use n-=~a[n] to save 1 byte. – Nevay – 2017-07-30T23:47:17.307

2

R, 58 bytes

f=function(x,p=1){cat(z<-x[p]);if(p+z<sum(x|1))f(x,p+z+1)}

Recursive function. Takes a vector x as argument and intiates a pointer p. This prints the corresponding entry of x, checks if p+x[p] would go out of bounds, and if not, calls the function for the new pointer.

f=function(x,p=1,s=x[1])`if`((z<-x[p]+p+1)>sum(x|1),s,f(x,z,c(s,x[z])))

This is a comparable solution that returns a proper vector instead of printing the digits.

JAD

Posted 2017-07-28T10:56:18.837

Reputation: 2 898

what about an input of numeric(0)? aka empty array. – Giuseppe – 2017-07-28T17:23:54.160

@Giuseppe I'll take a look at it when I'm behind my pc – JAD – 2017-07-28T17:35:25.793

55 bytes – Giuseppe – 2017-10-04T17:24:24.900

2

C# (.NET Core), 68 bytes

n=>{var t="";for(int i=0;i<n.Length;i+=n[i]+1)t+=n[i]+" ";return t;}

Try it online!

Takes input as an array of integers, returns a string containing the non-skipped values.

jkelm

Posted 2017-07-28T10:56:18.837

Reputation: 441

Nice way to do it and comes in at the same count as printing. – TheLethalCoder – 2017-07-28T11:49:54.447

I love the simple solutions. Still gotta learn LINQ though, as I have seen that shorten so many c# lambdas.. – jkelm – 2017-07-28T11:52:39.807

Shortens it because you can implicit return most of the time. Though it is a toss up between implicit return with using System.Linq; and a normal loop. – TheLethalCoder – 2017-07-28T11:54:03.857

2

Alice, 15 bytes

/$.. \h&
\I@nO/

Try it online!

Input and output a linefeed-separated lists of decimal integers.

Explanation

/   Switch to Ordinal mode.
I   Read a line.
.   Duplicate it.
n   Logical NOT (gives truthy if we're at EOF).
/   Switch to Cardinal.
    The IP wraps around to the left.
\   Switch to Ordinal.
$@  Terminate the program if we're at EOF.
.   Duplicate the input line again.
O   Print it.
\   Switch to Cardinal.
h   Increment the value.
&   Store the result in the iterator queue.
    The program wraps around to the beginning.

Storing an integer n in the iterator queue causes the next command to be executed n times. Mirrors like / are not commands, so the next command will be I. Therefore if we just read and printed a value x, we will read x+1 values on the next iteration, with the last of them ending up on top of the stack. This skips the required number list elements.

Martin Ender

Posted 2017-07-28T10:56:18.837

Reputation: 184 808

2

Mathematica, 37 (30?)

Further golfing of user202729's fine method.

±{a_,x___}={a}~Join~±{x}~Drop~a
±_={}

The rules don't seem to explicitly specify the output format, so maybe:

±{a_,x___}=a.±{x}~Drop~a
±_={}

Output for the second function looks like: 0.2.4.{} — notably {} is still returned for an empty set, conforming to the final rule.

Mr.Wizard

Posted 2017-07-28T10:56:18.837

Reputation: 2 481

1±Drop[{x},a] can be ±{x}~Drop~a because ± has a lower precedence than Infix. – JungHwan Min – 2017-07-28T19:08:58.120

@JungHwanMin I missed that; thanks! – Mr.Wizard – 2017-07-28T19:13:51.427

2

Common Lisp, 51 bytes

(do((x(read)(nthcdr(1+(print(car x)))x)))((not x)))

Try it online!

Renzo

Posted 2017-07-28T10:56:18.837

Reputation: 2 260

2

Brain-Flak, 64 60 bytes

4 bytes save based on an idea from 0 '

([]){{}(({})<>())<>{({}[()]<{}>)}{}([])}{}<>{({}[()]<>)<>}<>

Try it online!

Annotated

([]){{}            #{Until the stack is empty}
  (({})<>())<>     #{Put n+1 to the offstack}
  {({}[()]<{}>)}{} #{Remove n items from the top}
([])}{}            #{End until}
<>                 #{Swap stacks}
{({}[()]<>)<>}<>   #{Move everything back onto the left stack decrementing by 1}

Post Rock Garf Hunter

Posted 2017-07-28T10:56:18.837

Reputation: 55 382

1

Python 2.4, 85 bytes

No chance to win in python with it, but I love oneliners and this one might be interesting to others.
Turns out, there is a fancy magic trick to access building list inside comprehension, but it works only in 2.4 and with some edits in <= 2.3
locals()['_[1]'] it is. Python creates secret name _[1] for list, while it is created and store it in locals. Also names _[2], _[3]... are used for nested lists.

lambda n:[j for i,j in enumerate(n)if i==len(locals()['_[1]'])+sum(locals()['_[1]'])]

So it counts number of already added elements plus their sum. Result is the index of next desired element.
I think, that there should be a way to avoid enumerate. Like accessing input array directly by index: [ n[len(locals()['_[1]'])+sum(locals()['_[1]'])] for ... ]. But I can't figure out a compact way to protect it from index-out-of-range (while keeping it oneliner)

enter image description here

Dead Possum

Posted 2017-07-28T10:56:18.837

Reputation: 3 256

1

Ruby, 36 33 31

f=->l{a,*l=l;a&&f[l.drop(p a)]}

Try it online.

Cristian Lupascu

Posted 2017-07-28T10:56:18.837

Reputation: 8 369

You're allowed to subtract the f= as a header element. – canhascodez – 2017-07-30T02:39:12.550

@sethrin Even if I need to call it recursively? – Cristian Lupascu – 2017-07-30T05:42:07.033

Hmm, good question. I suppose not. I did very much like that about your solution, by the way. – canhascodez – 2017-07-30T12:01:58.843

1

Swift, 63 bytes

func a(d:[Int]){var i=0;while i<d.count{print(d[i]);i+=d[i]+1}}

This is my first entry, ever, so I'm not 100% sure on the rules, but hopefully this answer suffices. I'm a little unsure of rules on how to get the input into a system. I have a shorter answer if I was allowed to assume a function somewhere that can return the input.

AnonymousReality

Posted 2017-07-28T10:56:18.837

Reputation: 41

Welcome to PPCG! The default rules are that you can either have code that works as a full program, so input (usually) in STDIN and output (usually) to STDOUT, or a function, so input (usually) from function parameters and output (usually) from function return. – Stephen – 2017-07-28T12:53:24.717

@StepHen - thanks! I guess that makes my other version invalid then. Looking forward to contributing more! – AnonymousReality – 2017-07-28T14:28:32.503

1

Perl 5, 36 30 + 1 (-a) = 31 bytes

$i+=$F[$i]+say$F[$i]while$i<@F

Try it online!

Takes its input as a space separated list of numbers.

Xcali

Posted 2017-07-28T10:56:18.837

Reputation: 7 671

1

Perl 6, 31 bytes

{(@_,{.[1+.[0]..*]}...^0)[*;0]}

Test it

Expanded:

{  # bare block lambda with implicit parameter 「@_」
  (
    # generate a sequence

    @_,

    {
      .[ # index into previous value in the sequence
        1 + .[0]  # start by skipping one plus the first element
                  # of the previous value in the sequence
        ..  *     # use that to create a Range with no end
      ]
    }

    ...^  # keep doing that until: (and throw away last value)
    0     # it generates an empty list

  )[ *; 0 ]  # from every value in the sequence, get the first element
}

To help understand how the code works, without [*;0] this would generate a sequence like the following:

[0, 1, 0, 2, 5, 1, 3, 1, 6, 2],
   (1, 0, 2, 5, 1, 3, 1, 6, 2),
         (2, 5, 1, 3, 1, 6, 2),
                  (3, 1, 6, 2)

Brad Gilbert b2gills

Posted 2017-07-28T10:56:18.837

Reputation: 12 713

1

C++ (gcc), 172 bytes

(for 144 bytes see @ceilingcat comment)

#include<iostream>
int main(){std::istream& i=std::cin;char c;int a,b;while(i>>c&&i>>a){std::cout<<c<<(c/91?"":" ")<<a;while(a--&&i>>c&&i>>b);}std::cout<<c<<(c/93?"":"]");}

Try it online

The awful (c/91?"":" ") is for correct spacing in output. Without it (-15 bytes) output is in form: [0,2,4], when I change it to simple " " (-9 bytes) output is like [ 0, 2, 4] (additional space at the beginning).

<<(c/93?"":"]") on the end is only to handle [] empty input corner case

Prints no trailing endline.

Przemysław Czechowski

Posted 2017-07-28T10:56:18.837

Reputation: 121

You can also print the numbers separated by a no-digit separator, no need for [] and you can have empty output for that edge-case, and no need for (c/91?"":" "). You don't have to match the format of the examples in the challenge. – Erik the Outgolfer – 2017-07-30T07:52:17.783

144 bytes – ceilingcat – 2019-08-09T01:15:35.157

@ceilingcat so when I looked at my answer after this two years, changing std:istream to auto was the first thing I thought about. Thanks! – Przemysław Czechowski – 2019-08-09T07:54:37.040

1

Jelly, 8 bytes

ḢṄ‘ṫ@µL¿

A full program printing the results each followed by a newline (empty list produces no output).

Try it online!

How?

ḢṄ‘ṫ@µL¿ - Main link: list of non-negative integers  e.g. [2,5,4,0,1,2,0]
       ¿ - while:           Iteration:  1                  2             3          4        5
      L  -   length (0 is falsey)       7                  4             3          1        0
     µ   - ...do:                                                                            stop
Ḣ        -   head (pop & modify)        2 ([5,4,0,1,2,0])  0 ([1,2,0])   1 ([2,0])  0 ([0])
 Ṅ       -   print it (and yield it)   "2\n"              "0\n"         "1\n"      "0\n"
  ‘      -   increment                  3                  1             2          1
   ṫ@    -   tail from index            [0,1,2,0]          [1,2,0]      [0]         []
         -
         -                       i.e. a resulting in the printing of: '''2
                                                                         0
                                                                         1
                                                                         0
                                                                         '''

Jonathan Allan

Posted 2017-07-28T10:56:18.837

Reputation: 67 804

Finally a Jelly answer! BTW I can do it in 7 bytes. – Erik the Outgolfer – 2017-07-30T07:30:42.373

And I also have a list-returning function in 18 bytes. – Erik the Outgolfer – 2017-07-30T07:49:14.320

1

Python 3, 35 bytes

f=lambda h=0,*t:t and[h,*f(*t[h:])]

Try it online!

Run it with f(*l) where l is your input. Arguably stretching the rules for input, but I just love advanced unpacking.

Evpok

Posted 2017-07-28T10:56:18.837

Reputation: 558

1

APL (Dyalog Unicode), 20 bytesSBCS

{⍵≡⍬:⍬⋄(⊃,∘∇1↓⊃↓⊢)⍵}

Try it online!

ngn

Posted 2017-07-28T10:56:18.837

Reputation: 11 449

The way you use that tacit function inside the dfn is creative. – Erik the Outgolfer – 2018-02-03T20:29:06.230

1

PowerShell, 25 bytes

$args|?{!$s--}|%{($s=$_)}

Try it online!

mazzy

Posted 2017-07-28T10:56:18.837

Reputation: 4 832

0

Mathematica, 65 bytes

(s=#;t=1;w={};While[t<=Length@s,AppendTo[w,k=s[[t]]];t=t+k+1];w)&

Try it online!

J42161217

Posted 2017-07-28T10:56:18.837

Reputation: 15 931

0

Clojure, 67 bytes

#(nth(reduce(fn[[z k]b](if(= z 0)[b(conj k b)][(- z 1)k]))[0[]]%)1)

Starts with the initial parameters [0 []], where 0 is the counter and [] is the result. If the first element in this list is 0 appends item n from the argument to the result and passes further this list [n [... n]] otherwise decrements the first element. (this explanation feels horrible to me)

See it online

cliffroot

Posted 2017-07-28T10:56:18.837

Reputation: 1 080

0

Batch, 69 bytes

:l
@if not "%1"=="" echo %1&(for /l %%i in (0,1,%1)do @shift)&goto l

(I need the ()s around the for otherwise the goto happens inside the loop.)

Neil

Posted 2017-07-28T10:56:18.837

Reputation: 95 035

0

C (gcc), 100 96 93 90 65 61 58 bytes

s;main(d){while(scanf("%d",&d)>0)s--||printf("%d\n",s=d);}

Try it online!

  • recursive main() saves a few bytes, yay!
  • indexing into string saves another 3 bytes
  • relaxing the output format saves a whole lot of bytes (25 to be exact), see here the shortest version with nice list-style output (90 bytes):

    s;d;main(p){scanf("%*c %d",&d)>0?s--||printf(p?"[%d":", %d",s=d),main(0):printf("[]"+!p);}
    
  • a different input format (1 number per line) saves another 4 bytes

  • Now it's shorter without recursion

Felix Palmen

Posted 2017-07-28T10:56:18.837

Reputation: 3 866

Suggest ~scanf("%d",&d) instead of scanf("%d",&d)>0 – ceilingcat – 2019-08-09T02:00:46.953

0

Perl 6, 33 bytes

my&f={$_&&(.[0],|f .[.[0]+1..*])}

Try it online!

Sean

Posted 2017-07-28T10:56:18.837

Reputation: 4 136

0

Cubix, 24 bytes

U.;@I)!/(O?vL!(.;I<.oWSL

Try it online!

Takes input as a comma- (or whitespace-) separated list with a -1 at the end to signify end of input.

I expect there's some golfing to do here.

Expands to the following cube:

    U .
    ; @
I ) ! / ( O ? v
L ! ( . ; I < .
    o W
    S L

Algorithm is in two parts:

  • I) : read in an input, increment it.
  • !/ : If zero (i.e., input is -1), turn left to @ and end program, otherwise proceed
  • (O : decrement and output as a number
  • ? : if zero, go straight, if positive, turn right.

Positive case:

  • <I : go right and read in input
  • ;( : pop TOS and decrement TOS
  • !L : skip L (turn left) if TOS is nonzero
  • wrap around to <I again
  • otherwise we hit SLWo(!;U which is the same as the zero case.

Zero case:

  • vS : go down, push 32 (space character)
  • o( : output as a character, decrement
  • !; : (no ops)
  • U : re-enter main loop, I)!/ etc.

Giuseppe

Posted 2017-07-28T10:56:18.837

Reputation: 21 077

0

Jelly, 7 bytes

ḊḢṄ$¡¹¿

Try it online!

Since nobody has discovered this yet (I challenged Jonathan Allan a long time ago), I am posting it.

Jelly, 12 bytes

Ḋ1ị$‘$¡ÐĿṖḢ€

Try it online!

I had 18 bytes back then (can't remember the exact code), but now I managed to make a list-returning version in 12 bytes.

Erik the Outgolfer

Posted 2017-07-28T10:56:18.837

Reputation: 38 134

0

PHP, 74 bytes

function s($l){$k=0;while(isset($l[$k]))$k+=($r[]=$l[$k])+1;return$r?:[];}

Try it online!

Jo.

Posted 2017-07-28T10:56:18.837

Reputation: 974

0

PowerShell, 57 50 bytes

-7 bytes thanks to mazzy

param($l)for(;$i-lt$l.count){($z=$l[$i++]);$i+=$z}

Try it online!

Simple for-loop approach that does alright.

Veskah

Posted 2017-07-28T10:56:18.837

Reputation: 3 580

150 bytes? – mazzy – 2019-07-15T13:42:59.747

0

Japt, 5 bytes

Modifies the input array in place.

£jYÄX

Try it - Footer outputs the original array

Shaggy

Posted 2017-07-28T10:56:18.837

Reputation: 24 623

0

Javascript 2019, 43 42 chars

a=>a.flatMap(x=>i^q++?[]:(i+=x+1,x),i=q=0)

Test:

f=a=>a.flatMap(x=>i^q++?[]:(i+=x+1,x),i=q=0)

console.log(
`[]                                                    => []
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                     => [0, 1, 3, 7]
[5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]                   => [5, 2, 1, 0]
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2]                         => [0, 1, 2, 3]
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] => [4, 3, 3, 4]
[0, 2, 0, 2, 4, 1, 2]                                  => [0, 2, 4]`
.split`
`.map(s=>s.split`=>`)
.map(([s,key])=>f(eval(s))==""+eval(key))
)

Qwertiy

Posted 2017-07-28T10:56:18.837

Reputation: 2 697

0

Runic Enchantments, 25 bytes

>Ri:$' $\
~/i~1-!;R:0)2*?

Try it online!

But input and output are space-separated integer lists. There is a trailing space because the logic to check to see if any input was actually read is a pain (and about 7 bytes) and not strictly needed for processing of this sort.

Draco18s no longer trusts SE

Posted 2017-07-28T10:56:18.837

Reputation: 3 053

0

Stax, 5 bytes

√⌡╜9{

Run and debug it

recursive

Posted 2017-07-28T10:56:18.837

Reputation: 8 616

0

PHP, 66 bytes

function($a){for(;$x<count($a);$x+=$o[]=$a[$x++|0]);return$o?:[];}

Try it online!

Output:

[]                                       => []
[0,1,2,3,4,5,6,7,8,9,10]                 => [0,1,3,7]
[5,1,2,3,4,5,2,1,2,1,0,0]                => [5,2,1,0]
[0,1,0,2,5,1,3,1,6,2]                    => [0,1,2,3]
[4,5,1,3,8,3,0,1,1,3,1,2,7,4,0,0,1,2]    => [4,3,3,4]
[0,2,0,2,4,1,2]                          => [0,2,4]

640KB

Posted 2017-07-28T10:56:18.837

Reputation: 7 149