title: Implementing a stack

text:
# Question
Title: Implementing a stack
I can't believe we don't have this already.. It's one of the most important data-structures in programming, yet still simple enough to implement it in a :

## Challenge

Your task is to implement a stack that allows pushing and popping numbers, to test your implementation and keep I/O simple we'll use the following setup:

* Input will be a list of non-negative integers

Every positive integer \\$n\\$ indicates a \\$\texttt{push(}n\texttt{)}\\$ and every \\$0\\$ indicates a \\$\texttt{pop()}\\$ - discarding the top element.

* Output will be the resulting stack

## Example

For example if we're given \\$\[12,3,0,101,11,1,0,0,14,0,28\]\\$:

$$ \begin{aligned} & 12 & \[12\] \\ & 3 & \[3,12\] \\ & 0 & \[12\] \\ & 101 & \[101,12\] \\ & 11 & \[11,101,12\] \\ & 1 & \[1,11,101,12\] \\ & 0 & \[11,101,12\] \\ & 0 & \[101,12\] \\ & 14 & \[14,101,12\] \\ & 0 & \[101,12\] \\ & 28 & \[28,101,12\] \end{aligned} $$

Output will be: \\$\[28,101,12\]\\$

## Rules

* Input will be a list of non-negative integers in any default I/O format
    + you may use a negative integer to signify the end of a stream of integers
* Output will be a list/matrix/.. of the resulting stack
    + your choice where the top element will be (at the beginning or end), the output just has to be consistent
    + output is flexible (eg. integers separated by new-lines would be fine), the only thing that matters is the order
    + you may use a negative integer to signify the bottom of the stack
* You're guaranteed that there will never be a \\$0\\$ when the stack is empty

## Examples

```
[] -> []
[1] -> [1]
[1,0,2] -> [2]
[4,0,1,12] -> [12,1]
[8,3,1,2,3] -> [3,2,1,3,8]
[1,3,7,0,0,0] -> []
[13,0,13,10,1,0,1005,5,0,0,0] -> [13]
[12,3,0,101,11,1,0,0,14,0,28] -> [28,101,12]

```

# Answer
> 19 votes
# MATL, 6 bytes

```
"@?@}x

```

Input is a row vector of numbers.

The final stack is shown upside down, with the most recent element below.

Try it online! Or verify all test cases.

### Explanation

```
"         % For each element in the input (implicit)
  @       %   Push current element
  ?       %   If non-zero (this consumes the current element)
    @     %     Push current element again
  }       %   Else
    x     %     Delete most recent element
          %   End (implicit)
          % End (implicit)
          % Display (implicit)

```

# Answer
> 13 votes
# Java (JDK 10), 42 bytes

Since "\[the\] output is flexible \[...\], the only thing that matters is the order", this changes the input array into a `0`-terminated array. Example : `[1,0,2]` will return `[2,0,2]` which is to be interpreted as `[2`~~`,0,2`~~`]` = `[2]`.

```
a->{int s=0;for(int v:a)a[v>0?s++:--s]=v;}

```

Try it online!

# Previous versions:

## Java (JDK 10), 60 bytes

```
l->{for(int i;(i=l.indexOf(0))>0;l.remove(i))l.remove(--i);}

```

Try it online!

**Credits:**

## If I can end the program with errors: 55 bytes

(though everything is properly modified)

```
l->{for(int i;;l.remove(--i))l.remove(i=l.indexOf(0));}

```

Try it online!

# Answer
> 12 votes
# PowerShell, ~~46~~ ~~41~~ 40 bytes

```
$args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a

```

Try it online!

Takes input via splatting, e.g., `$z=@(12,3,0,101,11,1,0,0,14,0,28); .\implement-stack.ps1 @z`, which on TIO manifests as separate arguments.

```
$args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a    # Full program
$args                                       # Take input via splatting
     |%{                            };      # Loop through each item
              &(              )[!$_]        # Pseudo-ternary, if input is 0 this is 1
        $x,$a=            {$a}              # ... which will pop the first item into $x
           $a=  { ,$_+$a}                   # Else, we append the first item
        $x   =   1                          # ... and drop a dummy value into $x
                                      $a    # Leave $a on pipeline; implicit output

```

*-5 bytes thanks to mazzy.*
*-1 byte swapping `$_` to `1`*

# Answer
> 12 votes
# Sed, 17 Bytes

`:;s/[0-9]\+,0//;t`

-3 bytes thanks to @OMᗺ, -1 thanks to @eggyal

Because you're guaranteed to never pop an empty list, you don't need anything more than an iterated finite state machine. Regular expressions are a tool for building finite state machines, and `sed` can iterate. It's a match made in heaven.

Takes input from stdin, like so:

`echo '[12,3,0,101,11,1,0,0,14,0,28]' | sed ':;s/[0-9]\+,0,//;t'`

Outputs the stack in reverse:

`[12,101,28]`

Could be smaller by two bytes if my local `sed` inherently understood character classes like `\d`, but it doesn't for some reason.

# Answer
> 11 votes
# C (gcc), ~~62~~ ~~60~~ ~~56~~ 55 bytes

~~-2~~ -6 bytes thanks to l4m2

-1 byte thanks to ceilingcat.

Uses the permitted notion of -1 terminated arrays. `f()` calls itself recursively, until fully wound, and then backtracks through the list. `r` keeps track of how many numbers to discard before printing something. Increases if current item is 0, decreases otherwise. If 0, we need not discard, and can print the number.

```
r;f(int*l){~*l?f(l+1),*l?r?r--:printf("%d ",*l):r++:0;}

```

Try it online!

# Answer
> 10 votes
# , 45 bytes

```
o={};for(e in scan())o="if"(e,c(e,o),o[-1]);o

```

Try it online!

* -4 byte thanks to @Giuseppe

# Answer
> 10 votes
## Haskell, 28 bytes

```
foldl(#)[]
(_:s)#0=s
s#n=n:s

```

Try it online!

# Answer
> 10 votes
# Jelly, 6 bytes

```
ṣ0Ṗ;¥/

```

Try it online!

### How it works

```
ṣ0Ṗ;¥/  Main link. Argument: A (array)

ṣ0      Split A at zeroes.
    ¥/  Left-reduce the resulting 2D array by this dyadic chain:
  Ṗ       Pop; discard the last element of the left argument.
   ;      Concatenate the result with the right argument.

```

# Answer
> 9 votes
# Brain-Flak, ~~40~~ 36 bytes

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

```

Try it online!

Thanks to @Nitrodon for -4 bytes.

Since Brain-Flak already uses stacks, this is a good puzzle for Brain-Flak.

```
([]){   while items on stack
    {}      pop stack count
    {       if top element is non-zero
        ({}<>)<> push it on the other stack
    }
    if we're here the stack is either empty or there's a 0 on the stack

    ([])    so, count the stack again
    {{}<>{}<>} if there are items left on the stack, pop the stack count and the last item of the other stack
    {} pop the zero or the stack count
    ([]) count the stack again for next round
}
<>  go to the output stack

```

# Answer
> 9 votes
# Python 2, ~~59~~ ~~57~~ 51 bytes

```
s=[]
for x in input():s=(s+[x],s[:-1])[x<1]
print s

```

Try it online!

# Answer
> 9 votes
# Wolfram Language (Mathematica), 28 bytes

```
#//.{a___,b_,0,c___}:>{a,c}&

```

Try it online!

# Answer
> 9 votes
# Python 2, 48 bytes

```
s=[]
for x in input():s=([x]+s)[2*0**x:]
print s

```

Try it online!

# Answer
> 7 votes
# Python 2, ~~60~~ ~~59~~ ~~57~~ 56 bytes

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

```

Try it online!

---

Saved:

* -1 byte, thanks to pushkin

# Answer
> 7 votes
# Whitespace, 89 bytes

```
[N
S S N
_Create_Label_LOOP_1][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input][N
T   T   S
_If_neg_Jump_to_Label_EXIT][S N
S _Duplicate_input][N
T   S T N
_If_0_Jump_to_Label_DROP][N
S N
N
_Jump_to_Label_LOOP_1][N
S S S N
_Create_Label_EXIT][S N
N
_Discard_top][N
S S S S N
_Create_Label_LOOP_2][T N
S T _Print_as_integer][S S S T  S T S N
_Push_10_newline][T N
S S _Print_as_character][N
S T S S N
_Jump_to_Label_LOOP_2][N
S S T   N
_Create_Label_DROP][S N
N
_Discard_top][S N
N
_Discard_top][N
S N
N
_Jump_to_Label_LOOP_1]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Takes the input-list new-line separated with `-1` to indicate we're done with the inputs.

Try it online.

**Explanation in pseudo-code:**

```
Start LOOP_1:
  Integer i = STDIN as integer
  If(i is negative):
    Call function EXIT
  If(i is 0):
    Call function DROP
  Go to next iteration of LOOP_1

function EXIT:
  Start LOOP_2:
    Pop and print top as integer
    Print newline
    Go to next iteration of LOOP_2

function DROP:
  Drop the top of the stack
  Go to next iteration of LOOP_1

```

# Answer
> 7 votes
# brainfuck, ~~214~~ 150 bytes

```
>>,[>++++++[-<-------->]+<[>+++++[-<++++++++>]]>[-<<<[[-]<],[-]>>>>-<<]>>+[<<+<,----------[++++++++++>-]>[->>-<]>[->+<]>]<<<,]<<[[<]++++++++++<]>>[.>]

```

Reads input as numbers separated by newlines. This must include a single trailing newline. Also expects no leading zeros on each number. Output as a similar newline separated list

Try it online!

# Explanation ~~that isn't really an explanation but is actually just the version I was working on with the comments and stuff which may or may not actually be useful to anyone~~

```
Stack format:
0 (0 \d*)*

>>,[
    Setup digit == '0' conditional
    >++++++
    [-<-------->]
    +
    <[
        Read digit != '0'
        Restore the char code
        cond1 is already 1 at this stage
        >+++++
        [-<++++++++>]
    ]>[
        Read digit == '0'
        -
        Pop previous value
        <<<[
            [-]<
        ]
        Skip next input (assumed to be newline)
        ,[-]
        Skip following loop by unsetting loop flag
        >>>>-
        <<
    ]

    Move to next stack frame
    >
    Set loop flag
    >+[
        Set bit used for conditional
        <<+
        Read next character
        <,
        Compare with '\n'
        ----------[
            Not '\n': restore the char code
            ++++++++++

            >-
        ]>[
            -
            == '\n': Leave as 0
            Unset loop flag
            >>-
            <
        ]

        Copy loop flag along
        >
        [- > + <]

        Move to loop flag of next stack frame
        >
    ]

    <<<
,]

Fill in with newlines
<<[
    Skip to the cell before this value
    [<]
    Put a newline in there
    ++++++++++
    Move to next value
    <
]

Now the tape has the exact values we need to output
>>[.>]

```

# Answer
> 6 votes
# JavaScript, 40 bytes

Outputs in reverse order.

```
a=>a.map(x=>x?o.push(x):o.pop(),o=[])&&o

```

Try it online

1 byte saved thanks to Herman L.

# Answer
> 6 votes
# 05AB1E, 9 bytes

```
vy>i¨ëy)˜

```

Try it online or verify all test cases.

**Explanation:**

```
v        # For-each of the items in the input-list:
 y>i     #  If the current item is 0:
  ¨      #   Pop the top item of the list
 ë       #  Else:
  y      #   Push the current item to the stack
   )     #   Wrap the entire stack into a list
         #    i.e. 12 → [12]
         #    i.e. [12] and 3 → [[12], 3]
    ˜    #   Flatten the stack
         #    i.e. [[12], 3] → [12, 3]
         # (and output the list implicitly after the loop)

```

---

**9 bytes alternative:**

```
vy_i\ëy])

```

Try it online of verify all test cases.

**Explanation:**

```
v        # For-each of the items in the input-list:
 y_i     #  If the current item is 0:
  \      #   Discard top item of the stack
 ë       #  Else:
  y      #   Push the current item to the stack
]        # Close both the if-else and for-each (short for `}}`)
 )       # Wrap the entire stack into a list (and output implicitly)

```

PS: If the output should have been reversed to match the test cases in the challenge description, we can add a trailing `R` to the second version (so **10 bytes**), which reverses the list. Try it online or verify all test cases.

# Answer
> 6 votes
# Brain-Flak, 32 bytes

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

```

Try it online!

Uses `-1` to signify the end of the array (but any number will do really).

# Answer
> 6 votes
# Brachylog, 21 bytes

```
~c₃Ckt[İ,0]≠∧C⟨hct⟩↰|

```

Try it online!

-1 byte, and more importantly this feels like a much less clunky way of doing this.

```
~c₃                     % Partition the input into 3 subarrays
   C                    % Call that array-of-arrays C
    kt[İ,0]             % Its second element should be of the form [Integer, 0]
           ≠            % And its elements shouldn't be equal (i.e.
                        %   the Integer shouldn't be 0)
            ∧C⟨hct⟩     % Then, remove that [İ, 0] element from C
                   ↰    % And call this predicate recursively
                    |   % When the above fails (when it can't find a partition with
                        %  [İ, 0] in it), then just output the input

```

Alternate 21 byter: `∋0∧ℕ₁;0;P↺c;Qc?∧P,Q↰|` Try it online!

---

Older code:

**22 bytes**

```
∋0&b,1;?z{=|¬∋0&}ˢtᵐ↰|

```

Try it online!

```
∋0           If input contains a 0,
&b           Remove input's first element, getting list of "next" elements
,1           Append 1 to that to handle last element
;?z          Zip that with input
{      }ˢ    Select only zipped pairs where
 =|          both elements are equal (to keep 0s followed by 0s)
   ¬∋0&      or the pair doesn't contain a 0
             this removes both the (pairs containing the) value
              that is followed by a 0, and the 0 itself
tᵐ           Recover back the (filtered) input array elements from the zip
↰            Call this predicate recursively
|            If input contains no 0s, input is the output

```

# Answer
> 6 votes
# , 10 bytes

```
ò/ 0⏎b2dw0

```

Try it online!

### Explanation

```
ò           " run the following, until an error occurs
 / 0⏎       " | goto next zero with space in front (errors if none)
     b      " | jump one word back (to the beginning of element to pop)
      2     " | twice (element & zero itself)
       dw   " | | delete word
         0  " | goto beginning of line

```

---

## Equivalent in Vim, 16 bytes

```
qq/ 0⏎b2dw0@qq@q

```

Try it online!

### Explanation

Pretty much the same, except recording a macro `q` and recursively call it:

```
qq                " record macro q
  / 0⏎b2dw0       " same as in V
           @q     " recursively call q (aborts on error)
             q    " quit recording
              @q  " execute the macro q

```

# Answer
> 5 votes
# Retina 0.8.2, 18 bytes

```
^
,
+1`,\d+,0

^,

```

Try it online! Link includes test cases. Explanation:

```
^
,

```

Prefix an extra `,`.

```
+1`,\d+,0

```

Process all pop operations.

```
^,

```

Remove the `,` if it's still there.

Reversing the numbers would cost an extra 8 bytes:

```
O^$`\d+

```

# Answer
> 5 votes
# Java 10, ~~75~~ 72 bytes

```
n->{var s="";for(int i:n)s=(s+","+i).replaceAll(",\\d+,0","");return s;}

```

Outputs separated by a comma. Top of the stack is last. Try it online here.

Thanks to Olivier Grégoire for golfing 2 bytes.

Please check out Kevin Cruijssen's and Olivier Grégoire's Java answers as well. They take a list-based approach instead, with the latter beating mine by a tidy margin.

Ungolfed:

```
n -> { // lambda taking an integer array as argument and returning a String
    var s = ""; // we'll be using a String to implement and output the stack
    for(int i : n) // loop through the array
        s = (s + "," + i) // append the next number
               .replaceAll(",\\d+,0", ""); // remove any number followed by a zero
    return s; // output the resulting stack
}

```

# Answer
> 5 votes
# Ruby, 36 bytes

```
->a{b=[];a.map{|x|x>0?b<<x:b.pop};b}

```

Try it online!

Anonymous lambda. Outputs in reverse order.

# Answer
> 5 votes
# Brain-Flak, 36 bytes

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

```

Try it online!

```
#Let's call the two stacks in and out

([]){{}                      ([])}    # while not in.empty()
       {        (  )}{}               # if in.peek() != 0
        (({}<>)) <>                   # a = in.pop; out.push(a); out.push(a)
                       <>{}<>         # out.pop()
                                  <>  # switch to out to be printed

```

# Answer
> 5 votes
# Perl 5 `-p`, 17 bytes

*Thanks @sundar and @DomHastings*

```
s/\d+ 0 ?//&&redo

```

Try it online!

# Answer
> 5 votes
# GolfScript, ~~14~~ 12 bytes

```
~{.{;}if}/]`

```

Try it online!

```
~{.{;}if}/]` Full program, implicit input
~            Eval input
 {      }/   Foreach:
      if       If the value is truthy (!= 0):
  .              Push itself
   {;}         Else: pop the top value
          ]` Push as array representation
             Implicit output

```

# Answer
> 5 votes
# \>\<\>, 25 bytes

```
i:?\~~
(0:/:^?
!?l:!<oan;

```

Try it online! (input must be written in ascii. otherwise use this one)

### How it works

`i:?\~~` checks for 0, continues to `~~` to delete previous entry. otherwise go down to:

`(0:/:^?` which checks for -1 (no more input), then wrap up to delete -1 and loop:

`!?l:!<oan;` which outputs each number with a newline, then ends when stack emptied

# Answer
> 5 votes
# Husk, 6 bytes

Since there's no Husk answer already and it's my favourite golfing-lang:

```
F`?:tø

```

Try it online!

### Explanation

```
F`?:tø  --
F    ø  -- foldl (reduce) with [] as the initial accumulator
 `      -- | flip arguments of
  ?:    -- | | if truthy: apply cons (prepend) to it
    t   -- | | else: return tail
        -- | : returns a function, either prepending the element or dropping 1 element

```

### Alternative solution, 6 bytes

Instead of flipping, we can also just reverse the list and then use a right-fold: `Ḟ?:tø↔`

# Answer
> 5 votes
***Warning:*** Lots of lines ensue. You have been warned.

---

# CJam, 17 bytes

**Most dangerous code**
(Assumes the stack elements can be separated by only spaces in the output and that the input array can be whatever form we wish)

```
q~{X0={;}X?}fX]S*

```

Try it online!

*Explanation*

```
q                                    Reads input string
 ~                                   Instantly convert to array since the string is in the CJam format
  {        }fX                       For loop
   X0=                               If X (the array element currently being checked) is equal to 0
      {;}                            Pop the top element from the stack
         X                           Else push X onto the top of the stack
          ?                          If-Else flag
              ]                      Collate all stack elements into an array
               S*                    Put a space between each array element

```

---

**Alternate Code #1, 27 bytes**
(Assumes stack elements have to be output in the format shown in the question and that the input array can be whatever form we wish)

```
q~{X0={;}X?}fX]',S+*'[\+']+

```

Try it online!

*Explanation*

```
q                                    Reads input string
 ~                                   Instantly convert to array since the string is in the CJam format
  {        }fX                       For loop
   X0=                               If X (the array element currently being checked) is equal to 0
      {;}                            Pop the top element from the stack
         X                           Else push X onto the top of the stack
          ?                          If-Else flag
              ]                      Collate stack items into an array
               ',S+                  Add together a comma and a space to create a delimiter
                   *                 Apply the delimiter to the stack
                    '[\+             Append left bracket to the left of the stack text
                        ']+          Append right bracket to the right of the stack text

```

---

**Alternate Code #2, 24 bytes**
(Assumes the stack elements can be collated in the output and that the input array has to be in the exact format shown in the question)

```
q',/~]S*~{X0={;}X?}fX]S*

```

Try it online!

*Explanation*

```
q                        Read input string
 ',/                     Separate by commas (since commas are an invalid array delimiter in CJam)
    ~                    Turn string into an array of substrings that make up the array
     ]S*                 Add spaces in between input numbers to prevent collation in the array
        ~                Turn the string into a valid array representative of the original
         {        }fX    For loop
          X0=            If X (the array element currently being checked) is equal to 0
             {;}         Pop the top element from the stack
                X        Else push X onto the top of the stack
                 ?       If-Else flag
                     ]   Collate all stack elements into an array
                      S* Add a space between each element

```

---

**Safest code for this, 34 bytes**
(Assumes stack elements have to be output in the format shown in the question and that the input array has to be in the exact format shown in the question)

```
q',/~]S*~{X0={;}X?}fX]',S+*'[\+']+

```

Try it online!

*Explanation*

```
q                                      Read input string
 ',/                                   Separate by commas (since commas are an invalid array delimiter in CJam)
    ~                                  Turn string into an array of substrings that make up the array
     ]S*                               Add spaces in between input numbers to prevent collation in the array
        ~                              Turn the string into a valid array representative of the original
         {        }fX                  For loop
          X0=                          If X (the array element currently being checked) is equal to 0
             {;}                       Pop the top element from the stack
                X                      Else push X onto the top of the stack
                 ?                     If-Else flag
                     ]                 Collate stack items into an array
                      ',S+             Add together a comma and a space to create a delimiter
                          *            Apply the delimiter to the stack
                           '[\+        Append left bracket to the left of the stack text
                               ']+     Append right bracket to the right of the stack text

```

---

Thanks to @Jo King for pointing out that the ones with the collated output are invalid since things like `[12]` and `[1,2]` would be indistinguishable.

Thanks also to @Jo King providing a very suitable alternative for the collated outputs and cutting off 9 bytes!

# Answer
> 4 votes
# Red, 64 bytes

```
func[b][a: copy[]foreach n b[either n > 0[insert a n][take a]]a]

```

Try it online!

# Answer
> 4 votes
# Java 10, ~~83~~ ~~76~~ ~~75~~ 74 bytes

```
a->{for(int i=0;i<a.size();)if(a.get(i++)<1){a.remove(i-=2);a.remove(i);}}

```

-7 bytes thanks to *@O.O.Balance*.
-1 byte thanks to *@OlivierGrégoire*.

Modifies the input-List instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
a->{                        // Method with List parameter and no return-type
  for(int i=0;i<a.size();)  //  Loop `i` in the range [0, size)
    if(a.get(i++)<1){       //   If the current item is 0:
      a.remove(i-=2);       //    Remove the previous item
      a.remove(i);}}        //    As well as the current 0

```

# Answer
> 4 votes
# Attache, 35 bytes

```
{y.=[]_:>{If[_>0,Push&_!y,Pop!y]}y}

```

Try it online!

Actually implements a stack! For the most part.

54 bytes for a "stackless" approach: `Fixpoint!{Flat!{#_=1or _@1>0}\Chop[_,1+Rotate[_=0,1]]}`. Didn't spend much time golfing it tho.

## Explanation

`y.=[]` defines an array and `_:>{...}` iterates over the input array. For each element, we either push it if its `> 0` or pop the last element. We return `y` at the end.

# Answer
> 4 votes
# Lua, ~~141~~ 124 bytes

```
loadstring'p=loadstring("return "..(...))()r={}t=table for i=1,#p do (0<p[i]and t.insert or t.remove)(r,1,p[i])end return r'

```

Try it online!

---

### Explanation

```
p=loadstring("return "..(...))() -- deserializes the input ('{1, 2, 3}' becomes a table with 3 elements)
r={} -- initializes the result table
t=table -- just to decrease the number of bytes used
for i=1,#p do -- for each element on the input list (table)
  (0<p[i] and t.insert or t.remove)(r, 1, p[i])
   0<p[i] and t.insert   -- if the element (p[i]) is greater than 0 then 'y' is going to be the function table.insert
                       or t.remove -- else it's going to be the remove function
  (                               ) -- this defines which function will be called (insert or remove)

                                   (          ) -- these are the arguments
                                    r, 1, p[i] -- 'r' is the table, 1 is the position, p[i] is the element
                                    -- the insert function receives 3 arguments, the table which to insert, the position and the value
                                    -- the remove function only receives 2, the table and the position
                                    -- There's no problem with that because the third argument will be ignored
end
return r -- returns the 'r' table

```

This is an anonymous function.

I hope I did a decent job of explaining how it works hahah

# Answer
> 4 votes
# Japt, 14 bytes

```
;NË¥0?Ao:ApDÃA

```

Try it online!

Actual TIO doesn't work for some reason (it exits with an error, see here) so I've given a page to the ETHproductions' online Japt interpreter.

# Answer
> 4 votes
# MarioLANG, 51 47 bytes

```
> ;+[!>(
"====#"
 (![-<:[
 =#=="!<
!)<   #=
#="

```

Try it online!

Uses `-1` as mark for EOF. Explanation follows:

```
> ;+[!>     Mario walks to the left, reads an integer, adds 1 and checks if it's 0.
"====#"     If the value is not 0 Mario takes the elevator and starts walking to the left.
 (![-<      Mario takes 1 from the value and checks again if it's 0.
 =#=="      If so Mario skips the elevator and moves the pointer to the left, otherwise he
!)<         takes the elevator down and moves the pointer to the right. Either case
#="         Mario ends up taking the elevator to the start of the level.

>(    This is a loop to print what's left in the data values. Mario walks
"     to the right and falls, moving the pointer to the left and checking
:[    if the value pointed is 0. If it is, Mario skips the command to walk to the left and
!<    falls to end the level. Otherwise he walks to the left and takes the elevator,
#=    printing the value pointed as integer and continuing the loop.

```

# Answer
> 3 votes
# C, 138 bytes

```
int main(int _,char**v){int n=0,*s=0,i;for(;*++v;){i=atoi(*v);if(i){s=realloc(s,n*4+4);s[n++]=i;}else n--;}while(n--)printf("%i ",s[n]);}

```

Taking advantage of implicit definitions for printf, atoi, etc, and saving an 'int' by declaring i with the other variables.

# ~~202 bytes~~

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int _,char**v){int n=0,*s=NULL;for(;*++v;){int i=atoi(*v);if(i){s=realloc(s,n*4+4);s[n++]=i;}else n--;}while(n--)printf("%i ",s[n]);}

```

Takes input as command line args, outputs to stdout.

# Answer
> 3 votes
# TIS, 75 bytes

Code:

```
@0
MOV UP ACC
JGZ U
JLZ Q
ADD ANY
JRO -4
Q:MOV ANY DOWN
JMP Q
U:MOV ACC ANY

```

Layout:

```
1 2 CS
I0 NUMERIC -
O0 NUMERIC - 32

```

Try it online!

This implementation requires negative numbers for termination, and all values to be delimited by whitespace. Output is delimited by whitespace as well.

### Explanation:

I have one regular computation node. Numeric input comes from above, and numeric output is sent below. To the right, there is a stack node.

Here's the code, with more verbose (and additional) labels:

```
@0
START: MOV UP ACC     # Get input
       JGZ PUSH       # If input is positive, jump to PUSH
       JLZ STOP       # If input is negative, jump to STOP
                      # Else input is zero, continue at POP
POP:   ADD ANY        # Consume one value from the stack, by adding it to the accumulator
       JRO -4         # Jump back up to the top (new input will overwrite the accumulator)
STOP:  MOV ANY DOWN   # Move one value from the stack to output
       JMP STOP       # Just loop this bit forever
PUSH:  MOV ACC ANY    # Push the value we just read onto the stack
                      # Implicitly jump back to the top

```

You may have noticed that we use `ANY` to access the stack instead of `RIGHT`. We can depend on this to go to the correct place because of a quirk in the implementation of both the original game, and this emulator. Replacing all the `ANY`s by explicit `RIGHT`s will give the same solution.

I go into more detail about this behavior in note 2 of this other answer.

### Limitations:

TIS has some inherent limitations, which limit the abilities of this implementation quite directly.

First, the numeric datatype only accepts values from -999 to 999. Any values outside this range will be clamped to either -999 or 999.

Additionally, TIS stack nodes only allow a maximum depth of 15 items. Some implementations may deadlock when hitting that limit. Others, like this one, will behave in perhaps-unexpected ways. This specific implementation will just dump any overflow values to the output. (Changing the last line to `U:MOV ACC RIGHT` will make it do the deadlock thing instead).

# Answer
> 3 votes
# Kotlin, 90 bytes

```
{l:List<Int>->var c=0
l.reversed().filter{if(it<1){c++
0>1}else if(c>0){c--
0>1}else 1>0}}

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~51~~ 43 bytes

run `s` function Try it online

```
(#)[]
(_:r)#(0:s)=r#s
r#(x:s)=(x:r)#s
r#_=r

```

# Answer
> 2 votes
## C, 86 Bytes

```
c;f(a,n)int*a;{if(!n)c=0;else{f(a+1, n-1);!c&&*a&&printf("%d ",*a)||(c+=2*!*a-1,0);};}

```

Solution based on recursion. Simply load whole array on a system stack and count number of zeroes from the end and either skip current number (if count is positive) or print it. The resulting stack is printed from left to right, ie. head is on the beggining of the line.

Ungolfed version:

```
int counter;
void goo(int * a, int n){
        if (!n) {     // end of the array
            counter = 0;
            return;
        }
        goo(a+1, n-1); // try next number
        if (!*a) { cnt++; return;} //increase number of zeroes;
        if (cnt) { cnt--; return;} //skip current number
        printf("%d ", *a); //print it otherwise
    }

```

Try it on Ideone!

# Answer
> 2 votes
# Rust, 66 bytes

Takes a vector and returns a vector. The head of the stack comes last in the output.

```
|l|{let mut r=vec!();for&e in&l{if e>0{r.push(e)}else{r.pop();}}r}

```

Try It Online

# Answer
> 2 votes
# Stax, 8 bytes

```
âΦε∙GφN²

```

Run and debug it

# Answer
> 2 votes
# Befunge-93, 37 bytes

```
v<
 |   :<
 $
 $
>>&:1+|
>:v :$<
^._@

```

Try it online!

My first answer in Befunge!

Uses `-1` as EOF. As Befunge already uses a stack internally, I just need to do the push and pop operations given the values at the input.

# Answer
> 2 votes
# Ruby, 36 bytes

```
->a{b=[];a.map{|i|i>0?b<<i:b.pop};b}

```

Try it online!

# Answer
> 2 votes
# dc, 24 bytes

```
[*+]sP[?d0=Pd0<l]dslxsxf

```

Try it online!

Input is one number per line and terminate with a negative number but remember that negative numbers are input with a leading underscore not a dash. There's something punny about implementing this in a stack based language and using the operand stack as the data structure. I'm especially happy about the `*+` to "pop" the zero and the previous input.

# Answer
> 2 votes
# Scala, 50 bytes

```
(List[Int]()/:v)((x,i)=>if (i==0)x.tail else i::x)

```

Usage in the REPL

```
scala> val v = List(12,3,0,101,11,1,0,0,14,0,28)
v: List[Int] = List(12, 3, 0, 101, 11, 1, 0, 0, 14, 0, 28)

scala> (List[Int]()/:v)((x,i)=>if (i==0)x.tail else i::x)
res0: List[Int] = List(28, 101, 12)

scala>

```

# Answer
> 2 votes
# Chip `-o`, 53 bytes

```
)))))))}v9
ABCDEFGH`~8
0123456`v~S
)))))))~]T
abcdefg

```

Try it online!

For the TIO here, I use a Bash wrapper to allow "easier" number inputs. Numbers are given as values like `\x3f`, so that printf can do the conversion to the actual byte values for us. However, this is only a wrapper, or test harness, or whatever, and as such it is technically unnecessary.

This treats each byte of input as a 'signed byte', meaning that it will accept values `0 (0x00)` through `127 (0x7f)` as input, and anything else is a terminator (by virtue of being negative).

However, thanks to the `-o` flag, we don't need to provide an explicit terminator, since the interpreter will provide an infinite series of `-1 (0xff)` values upon exhaustion of STDIN.

### Explanation:

Chip is a 2D language, so the various elements seen generally interact with their four neighbors. Here's the highlights of the structure:

```
)))))))}v9      This chunk will, given a positive value, push it onto the stack,
ABCDEFGH`~8     and given zero, pop a value off the stack. Only the low 7 bits are
0123456         stored, since we never need to push/pop negatives.

```

The stack push control (`9`) is set from the result of ORing (`)`) the low 7 bits of the input together (`A` \- `G`), and XORing (`}`) the result with the high bit of the input (`H`). The stack pop control (`8`) is set by that same calculation, but inverted (`~`).

The end result is that `1` \- `127` cause a push, and `-128` \- `0` cause a pop.

The stack bits (`0`-`6`) push/pop based on what the control values resolve to. If pushing, they will read from the corresponding input bits (`A` \- `G`).

```
       H
0123456`v~S   This chunk will pop values to the output (or to the void if we
)))))))~]T    had a zero), and terminate the program if the stack is empty.
abcdefg

```

When the stack (`0` \- `6`) is popped, we want to send that data to the output bits (`a` \- `g`). Actually, we always send a value to the output, because in Chip you are either peeking or popping, and difference is only whether the value is kept for the future.

If the input was non-negative, due to the high bit (`H`) being unset, we want to suppress the output (`S`), preventing anything from being written to STDOUT.

On the way to the output, we also OR all the bits together again (`)`) to see if the stack has been emptied. If all bits are zero, it's empty, so we terminate (`T`). To prevent premature termination (since on the first cycle the stack is empty, and we always either peek or pop), we also use an AND (`]`) to ensure that we have a negative input value.

# Answer
> 2 votes
# Japt `-g`, 9 bytes

```
;®?AiZ:Av

```

Try it online!

# Answer
> 2 votes
# +pryr, 44 bytes

```
Reduce(pryr::f("if"(b,c(b,a),a[-1])),scan())

```

Try it online!

Heavily inspired by digEmAll's answer.

# Answer
> 2 votes
# ReRegex, 19 bytes

```
[^0,]\d*,0,//#input

```

Very simple solution, Looks for a non-zero number, followed by a zero, and removes both of them.

Takes input in the form of `,1,2,3,`

Try it online!

Test Battery

# Answer
> 2 votes
# MathGolf, 7 bytes

```
Æ_╜Å;;]

```

Try it online!

## Explanation

I wish I could do something clever to save a byte, it seems as if it should be possible.

```
Æ        For-each over the input with the next 5 operators
 _       Duplicate TOS
  ╜      Else without if, executes the next block if TOS is false
   Å;;   Discard two elements
      ]  Wrap everything in array

```

This answer has the opposite order compared to the examples in the challenge.

# Answer
> 2 votes
# Vyxal `W`, 6 bytes

```
0\_VṄĖ

```

Try it Online!

-2 thanks to Aaron Miller

# Answer
> 1 votes
# Charcoal, 12 bytes

```
ＦＡ¿ι⊞υι¬⊟υＩυ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＡ

```

Loop over the input list.

```
¿ι

```

Test for zero.

```
⊞υι

```

If non-zero, push to the predefined empty list.

```
¬⊟υ

```

Otherwise pop the value, and ignore it by taking the logical negation which is always zero and therefore prints an empty line.

```
Ｉυ

```

Print each element of the list on its own line.

# Answer
> 1 votes
# Small Basic, 218 bytes

A Script that takes input as a series of integers and outputs to the `TextWindow` object.

Note, terminal `"`s are not required for code to function and do not contribute to the bytecount.

```
n=" "
x=""
While n<>""
If n=0Then
k=Stack.PopValue(x)
Else
Stack.PushValue(x,n)
EndIf
n=TextWindow.Read()
EndWhile
o=Stack.PopValue(x)
k=Stack.GetCount(x)
For i=2To k
o=o+","+Stack.PopValue(x)
EndFor
TextWindow.Write(o)

```

Try it at SmallBasic.com! *Requires IE/Silverlight*

-8 bytes thanks to @OMᗺ for removing `[` and `]`

### Input / Output

# Answer
> 1 votes
# Ruby, 53 bytes

```
l=[];gets.split.map{|s|a=s.to_i;a>0?l<<a:l.pop};$><<l

```

The input needs to be separated by spaces. I'm working on a solution with `gsub`, but it does not re-run matching when it gets to the end. I would be happy if someone could help me fix this:

```
gets.gsub(/\d+ 0\s*/,'')

```

# Answer
> 1 votes
# Retina, 13 bytes

Takes the input list separated by newlines.

```
+0`\b\d+¶0¶?

```

Try it online!

Repeatedly remove the first occurrence of a number followed by a zero. Stack is returned upside-down.

Reversing the order of the lines is 4 more bytes (add to end of program). To avoid a possible leading newline, surround the input with newlines, similar to how the input in the examples uses brackets.

```

G^`

```

# Answer
> 1 votes
# Octave, 56 bytes

```
s=[];for i=input(''),if i,s=[i s];else s(1)=[];end,end,s

```

Try it online!

Implementation is simple. Create an empty stack / array `s`, then declare a list of values (i.e. `[12, 3, 0, 101, 11, 1, 0, 0, 14, 0, 28]`), iterate through each element and if the element is non-zero, simply place the element at the front. Otherwise, remove the first value inside the stack. Once we're done, show the result to the screen.

# Answer
> 1 votes
# PHP (\>=5.4), ~~68~~ 66 bytes

(-2 bytes by fixing a condition, thanks to Titus)

```
<?for(;null!=$n=$argv[++$i];)$n?$a[]=$n:array_pop($a);print_r($a);

```

To run it:

```
php -n <filename> <int_1> <int_2> ... <int_n>

```

Example:

```
php -n stack.php 12 3 0 101 11 1 0 0 14 0 28

```

Or Try it online!

Using `r` option per Titus's suggestion, this can be counted as **64 bytes**:

Example:

```
php -nr "for(;null!=$n=$argv[++$i];)$n?$a[]=$n:array_pop($a);print_r($a);" 12 3 0 101 11 1 0 0 14 0 28

```

# Answer
> 1 votes
# Bash, 81 , 50 bytes

```
for i;{ ((i))&&o+=($i)||unset o[-1];};echo ${o[@]}

```

Try it online!

Packed in function because, tio doesn't show output without it for some reason.

# Answer
> 1 votes
# Java 8, 65 bytes

flexible output permitting... the output stack is stored in the input array, with zero or more terminating -1 values

```
a->{int x=0,y=0;for(int e:a){a[y++]=-1;a[e>0?x++:--x]=e>0?e:-1;}}

```

all the remaining numbers on the stack are placed at the front of the array. Reaching -1 in the array indicates the end of the stack.

# Answer
> 1 votes
# Clojure, 139 bytes

```
(defn t[q](loop[c(rest q)n(first q)s '()](if(not(nil? n))(if(= n 0)(recur(rest c)(first c)(rest s))(recur(rest c)(first c)(cons n s)))s)))

```

Try it online!

### Ungolfed

```
(defn stacktest [col]
  (loop [c  (rest col)
         n  (first col)
         s  '()]
    (if (not (nil? n))
      (if (= n 0) ; then
        (recur (rest c) (first c) (rest s))    ; then - pop
        (recur (rest c) (first c) (cons n s))) ; else - push
      s)))        ; else

```

# Answer
> 1 votes
# Scala, ~~61 bytes~~ 48 bytes

```
(Seq[Int]()/:z)((z,b)=>if(b!=0)b+:z else z.tail)

```

Usage in the REPL

```
val z = Seq(1,2,3,4,0,3,2,5,0,1)

(Seq[Int]()/:z)((z,b)=>if(b!=0)b+:z else z.tail)

res0: Seq[Int] = List(1, 2, 3, 3, 2, 1)

```

Uses shorthand `.foldLeft` notation`/:` and `.tail` for popping items.

# Answer
> 1 votes
## F#, 84 bytes

```
let t v=
 let mutable s=List.empty
 for i in v do s<-if i=0 then s.Tail else i::s
 s

```

Try it online!

Takes advantage of the fact that in F# a `List` is a single-linked-list. Popping from the stack just takes the tail of the list (that is, everything after the first element). Pushing to the stack makes the individual value `i` the head of the list (that is, pre-appends it to the list).

# Answer
> 1 votes
# Lua, 115 bytes

```
t,a,s=table,arg,{}for i=1,#a do v=0+a[i]if v>0 then t.insert(s,1,v)else t.remove(s,1)end end print(t.concat(s,","))

```

quite simple iterates the arguments pushes and pops them to a table

Try it online!

# Answer
> 1 votes
# Scheme, 115 bytes

Like all lisp variants, scheme is based around linked lists. Linked Lists are often used to implement stacks. So I thought scheme might be a competitive language for this challenge. However, I failed to find a way to leverage Scheme's easily accessible built-ins for stack building to overcome Scheme's sheer verbosity. I love scheme, but sometimes its just too long...

```
(define(g c)(define(f l s)(cond((null? l)s)((= 0(car l))(f(cdr l)(cdr s)))(else(f(cdr l)(cons(car l)s)))))(f c'()))

```

Try it Online!

# Answer
> 1 votes
## Lua, 99 Bytes

I started looking for improvements for this answer, but ended with a solution that I find sufficently different to be an answer on its own.

As usual, you can Try it online!

It takes input as a list of arguments, and outputs each number separated by commas. The top of the stack (first element to `pop()`) is the last one printed

```
r={}for i=1,#arg
do
a=arg[i]+0s=a>0 and a or x
r[#r+(s and 1or 0)]=s
end
print(table.concat(r,","))

```

### Ungolfed

```
r={}          -- Define our output array
for i=1,#arg  -- iterate over the argument
do
a=arg[i]+0    -- shorthand for the current argument, add 0 to coerce it into a number
s=a>0         -- s define the operation to do in the current loop
    and a     -- if a>0, then s=a
  or x        -- else, s=x, x isn't initialiazed, so it's equivalent to s=nil

r[#r+         -- modify the end of the array
  (s          -- if s is true (which means not nil)
      and 1   -- add 1 to the current index to perform a push
    or 0)]    -- else, let it alone, which means we overwrite the last value of the table
  =s          -- attrib s to that index

  --[[
    if s is nil, it gives us, ungolfed, r[r.length+0]=nil, which erase the last value we have
    if s is a number, it's equivalent to r[r.length+1]=arg[i], or table.push(r, arg[i])
  ]]
end

print(table.concat(r,",")) -- outputs the table separating each element by commas

```

# Answer
> 1 votes
# Prolog (SWI), 47 bytes

```
R-L:-append(A,[_,0|T],L),append(A,T,M),R-M;R=L.

```

Try it online! Call as `output-input`.

### Explanation

```
R-L:-
     append(A,[_,0|T],L),                       % if list contains _,0
                         append(A,T,M),R-M;     % then remove it and recurse
                                           R=L. % else we're done, output = input

```

# Answer
> 1 votes
# Ahead, 23 bytes

```
~$k*2!:Ivj~
~oNO@k!d<~#

```

Try it online!

# Answer
> 1 votes
# Dart, 69 bytes

```
f(l){var m=[];l.forEach((n){n>0?m.add(n):m.removeLast();});return m;}

```

Alternative

`f(l,{m=List}){l.forEach((n){n>0?m.add(n):m.removeLast();});return m;}`

Try it online!

Naive answer until I find a better way.

# Answer
> 1 votes
# Common Lisp, 54 bytes

```
(let(s)(dolist(x(read)s)(if(= 0 x)(pop s)(push x s))))

```

Ultra-straightforward implementation!

Try it online!

# Answer
> 1 votes
## Burlesque - 27 bytes

```
%f={Jz?{vvvv}if}ps(%f!)[]e!

```

But this is rather bad to be honest. Anyway:

```
%f={Jz?{vvvv}if}             defines f
                ps           parse
                  (%f!)      quoted call to f
                       []    intersperse
                         e!  eval

```

This essentially inserts a call to `f` between the numbers.

```
J            duplicate
 z?          zero?
   {vvvv}    pop two elemnets
         if  if

```

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
0'\‡».V)

```

Try it online!

```
0'\‡».V)  # full program
     .V   # run...
          # implicit input...
   ‡      # with all digits of...
0         # literal...
   ‡      # replaced with corresponding characters in...
 '\       # literal...
    »     # joined by newlines...
     .V   # as 05AB1E code
       )  # push stack
          # implicit output

```

# Answer
> 1 votes
# Pxem, filename only: 51 bytes.

Emulating stack with stack-based language. `\001` is unprintable character 0x01.

```
.w._.c.w.cXXX.-.a.s.s.c\001.+.a.sL.w.n.c.c.z.d.a,.oL.a

```

Try it online!

## Usage

* Input as strings of decimal integers, from stdin.
* Separate each item of list with one or more blank characters, from begining to end.
* Append `-1` to indicate end of list.
* Output is to stdout, separated with a comma.

## How it works

```
XX.z
# while stack is empty or pop!=0; do
.a.wXX.z
 # get integer from stdin, and push it
 .a._XX.z
 # dup; while pop!=0; do
 .a.c.wXX.z
  # dup; push dummy item; break; done
  .a.cXXX.-.aXX.z
 # pop twice and discard them
 .a.s.sXX.z
# dup; add one; done
.a.c\001.+.aXX.z
# pop
.a.sXX.z
# while :; do
# NOTE L is for dummy
.aL.wXX.z
 # pop and print it as an integer
 .a.nXX.z
 # dup; dup; while size<2||pop!=pop; do exit; done
 # NOTE dup is not done if empty
 .a.c.c.z.d.aXX.z
 # print a comma; done
 .a,.oL.a

```

# Answer
> 1 votes
# JavaScript (Node.js), 53 bytes

```
(l,n=[])=>(l.map(t=>t?n.push(t):n.pop()),n.reverse())

```

Try it online!

##### More readable version

```
(list, stack=[]) =>
    (list.map(t =>
        t ? stack.push(t) : stack.pop()
    ), stack.reverse())

```

# Answer
> 1 votes
# APL (Dyalog APL), ~~37~~ 36 bytes

```
{{t←1-⍨o←⍵⍳0⋄o<≢⍵:⍵[t o~⍨⍳≢⍵]⋄⍵}⍣≡⍵}

```

Attempt This Online!

Whew this took me hours. 99% sure can still be golfed.

```
{{t←1-⍨o←⍵⍳0⋄o<≢⍵:⍵[t o~⍨⍳≢⍵]⋄⍵}⍣≡⍵}
{                                     } ⍝ Define a function
                                   ⍣≡   ⍝ Iterate until fixed point
                                     ⍵  ⍝ Starting with the input
 {                                }     ⍝ The function to iterate
         ⍵⍳0                            ⍝ Find the 1st 0
       o←                               ⍝ Store it in the variable 'o'
    1-⍨                                 ⍝ Subtract 1
  t←                                    ⍝ Store it in the variable 't'
            ⋄                           ⍝ <statement separator>
             o<                         ⍝ Is o less than
               ≢⍵                      ⍝ The length of the input?
                  :                     ⍝ If true
                   ⍵[         ]        ⍝ Keep the following indexes:
                           ⍳≢⍵            ⍝ Generate the indexes of the input array
                          ~               ⍝ Remove from ^
                      t o                 ⍝ The values in t and o
                                ⋄      ⍝ If false
                                 ⍵     ⍝ Return the input

```

# Answer
> 0 votes
# Python 2, 65 bytes

```
def f(p,s=[]):
 for i in p:
  if i:s+=i,
  else:s.pop()
 return s

```

**Try it online!**

# Answer
> 0 votes
# JavaScript (Node.js), 63 bytes

```
a=>{let b=[];a.map(x=>x?b.push(x):b.pop());return b.reverse();}

```

Try it online!

Can probably be improved

# Answer
> 0 votes
# JavaScript (ES6), 44 bytes

This code works directly on the original array rather than creating a new one. This is however longer than @Shaggy's answer.

```
a=>a.reverse(x=0).filter(n=>n?x?!x--:1:!++x)

```

Try it online!

# Answer
> 0 votes
# Python 3, 186 bytes

```
l = list()
while True:
    one = int(input())
    if one<0:
        break
    elif one==0:
        if len(l)>0:
            l.pop()
    else:
        l.append(one)

l.reverse()
print(l)

```

Try it online!

# Answer
> 0 votes
# Python 3, 60 bytes

```
def f(L,r=[]):
 for n in L:r=[n]+r if n else r[1:]
 return r

```

Try it online!

# Answer
> 0 votes
# Pepe, 57 bytes

```
rrEEReRerEerEEEEerEERrERREeEreErEEEEereeRrErEEReEEReeEree

```

Try it online!

Requires the input to end with `-1`. Note that "Separated by" option must be enabled. You might prefer to change the separator to `,` (it's a `;` by default). Also, putting `,-1` on a newline might help you not accidentally remove the `,-1`, preventing infinite loops and browser crashes.

### Explanation

Text in brackets `[]` are values taken from the stack, `r` is the control-flow stack, `R` is the data stack

```
# prepare (11 bytes)
rrEE           # Define [implicit 0] as
  Re Re          # Double pop from R
rEe            # Return

# main (29 bytes)
rEEEEe         # Decrement [implicit 0], always returns -1
rEE            # Create label [-1]
  RrE            # Prepend 0 to r
  RREeE          # Prepend input to R
  reE            # Execute 0 (double pop) if [input] was 0
  rEEEEe         # Decrement [0] in r, always returns -1
ree           # If [input] wasn't -1, goto label -1

# output (17 bytes)
RrE           # Prepend 0 to r
rEE           # Create label [0]
  ReEE ReeE     # Output [pop R] and a newline
ree           # If there's anything on the stack (non-zero), goto [0]

```

# Answer
> 0 votes
# sed, 42 bytes

```
s/^/%/
:l
s/!+,%0,/%/;tl
s/%(!+),/\1,%/;tl

```

Try it online!

The top of the stack is on the right. Input and output are in unary, separated by a comma. Zeroes are represented by the digit `0`.

# Answer
> 0 votes
# Pyth, 13 bytes

```
 m?daYd.)YQ_Y

```

Try it online!

# Answer
> 0 votes
# Go, 90 bytes

```
func f(i[]int)(o[]int){for _,e:=range i{if e>0{o=append(o,e)}else{o=o[:len(o)-1]}}
return}

```

Attempt This Online!

Implements a stack where the last element is the top of the stack.

# Answer
> 0 votes
# Vyxal `W`, 8 bytes

```
(n¨in_)^

```

Try it Online!

A no-eval approach

## Explained

```
(n¨in_)^
(     )   # For each item in the input
 n        # Push n
  ¨in_    # if that's truth, push n again, else pop top
       ^  # reverse the stack for outputting with W flag

```

---
Tags: code-golf, array, stack, data-structures
---


# Question
Title: CGAC2022 Day 15: Chimney cleaning, Part 2
Part of **Code Golf Advent Calendar 2022** event. See the linked meta post for details.

---

While other Elves are busy carrying air blowers, Fen comes and shouts, "I've got a spell for this job!"

To recap, a chimney is modeled as a rectangular grid. The number in each cell represents the amount of smoke in the region. The left and right sides are walls, and the top and bottom are open.

```
||========||
||  |90|  ||
||--+--+--||
||  |  |24||
||--+--+--||
||36|12|  ||
||--+--+--||
||  |  |  ||
||--+--+--||
||  |50|  ||
||========||

```

Fen can use "Vick" spell at a selected cell in the grid. When he uses it, the following happens:

1. The smoke at the selected cell is blown into three cells above it. Upper left and upper right cells get `floor(n/4)` amount of smoke each (if such cells exist) and the remaining smoke goes to the upper middle cell.
```
|  |   |  |    |12|26|12|
+--+---+--+ -> +--+--+--+
|  |50*|  |    |  |  |  |

||   |  |...    ||10| 3|...
||---+--+... -> ||--+--+...
||13*|  |...    ||  |  |...

```
2. The Vick spell itself moves to the cell above it.
3. The steps 1 and 2 are repeated until the Vick spell escapes the chimney.

Given the initial state above, casting Vick spell on the 50 (row 5, column 2) will result in the following:

```
||=========||
||  |90 |  ||
||--+---+--||
||  |   |24||
||--+---+--||
||36|12 |  ||
||--+---+--||
||  |   |  ||
||--+---+--||
||  |50*|  ||
||=========||

||=========||
||  |90 |  ||
||--+---+--||
||  |   |24||
||--+---+--||
||36|12 |  ||
||--+---+--||
||12|26*|12||
||--+---+--||
||  |   |  ||
||=========||

||=========||
||  |90 |  ||
||--+---+--||
||  |   |24||
||--+---+--||
||42|26*|6 ||
||--+---+--||
||12|   |12||
||--+---+--||
||  |   |  ||
||=========||

||=========||
||  |90 |  ||
||--+---+--||
||6 |14*|30||
||--+---+--||
||42|   |6 ||
||--+---+--||
||12|   |12||
||--+---+--||
||  |   |  ||
||=========||

||=========||
||3 |98*|3 ||
||--+---+--||
||6 |   |30||
||--+---+--||
||42|   |6 ||
||--+---+--||
||12|   |12||
||--+---+--||
||  |   |  ||
||=========||

||=========||
||3 |   |3 ||
||--+---+--||
||6 |   |30||
||--+---+--||
||42|   |6 ||
||--+---+--||
||12|   |12||
||--+---+--||
||  |   |  ||
||=========||

```

## Task

Given a 2D grid of non-negative integers which represents the current state of smoke in the chimney, and the initial position of the Vick spell, simulate the chimney as specified above and output the resulting state. You may assume that the chimney is at least 2 units wide and 2 units tall, and the Vick spell starts inside the chimney. The coordinates may be either 1- or 0-indexed.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
[[0, 90, 0], [0, 0, 24], [36, 12, 0], [0, 0, 0], [0, 50, 0]], (5, 2)
-> [[3, 0, 3], [6, 0, 30], [42, 0, 6], [12, 0, 12], [0, 0, 0]]

[[3, 0, 3], [6, 0, 30], [42, 0, 6], [12, 0, 12], [0, 0, 0]], (4, 1)
-> [[0, 11, 3], [0, 12, 30], [0, 3, 6], [0, 0, 12], [0, 0, 0]]

```

# Answer
# Python3, 159 bytes:

```
def f(b,x,y):
 while x>=0:
  c=(C:=b[x][y])//4
  b[x][y]=0;x-=1
  if x>=0:
   for Y in[1,-1]:
    if 0<=y+Y<len(b[0]):b[x][y+Y]+=c;C-=c
   b[x][y]+=C
 return b

```

Try it online!
> 2 votes

# Answer
# Charcoal, 67 bytes

```
≔§θηεＷη«≔§εζδ§≔εζ⁰≦⊖η≔§θηεＵＭε⁺κ⎇⁼λζ⁻δ×÷δ⁴№↔Ｅε⁻νζ¹∧⁼¹↔⁻λζ÷δ⁴»§≔εζ⁰Ｉθ

```

Try it online! Link is to verbose version of code. 0-indexed. Takes the initial row and column as separate inputs. Explanation:

```
≔§θηε

```

Get the row of the chimney at the initial row of the spell.

```
Ｗη«

```

Repeat until the spell reaches the top of the chimney.

```
≔§εζδ

```

Get the smoke at the current cell.

```
§≔εζ⁰

```

Clear the smoke at the current cell.

```
≦⊖η

```

Move the spell up one row.

```
≔§θηε

```

Get the row of the chimney at the new row of the spell.

```
ＵＭε⁺κ⎇⁼λζ⁻δ×÷δ⁴№↔Ｅε⁻νζ¹∧⁼¹↔⁻λζ÷δ⁴

```

Update the row in-place, adjusting for the amount of smoke that gets blown diagonally.

```
»§≔εζ⁰

```

Clear the remaining smoke from the chimney.

```
Ｉθ

```

Output the final state of the chimney.
> 1 votes

# Answer
# JavaScript (Node.js), 104 bytes

```
m=>x=>p=g=y=>(P=p>>2,p&=3,r=m[y])&&g(y-1,p=[r[x]+P+P+p],r[x]=0,[x-1,x+1].map(i=>1/r[i]?r[i]+=P:p[0]+=P))

```

Try it online!

Currying input m, x, y (0-indexed). Output by modify m in-place.

```
m=> // the input matrix
x=> // the input coordinate "x"
p=  // amount of smoke from row under it
    // p is an integer, and could be anything that may be convert to integer
    // for example, we initial p as a function so it converted into 0
g=  // recursive function
y=> // the input coordinate "y"
(P=p>>2, // smoke propagate to left / right
p&=3, // p+P+P is the smoke move to middle
r=m[y])&& // whenever the smoke not get out of the chimney
g(y-1, // it propagate to row y-1
p=[r[x]+P+P+p], // with amount p (assuming the smoke can propagate to left and right
r[x]=0, // smoke go away (empty the cell)
[x-1,x+1].map(i=> // for each left / right cell
1/r[i]?r[i]+=P: // if the cell exist, P amount smoke propagate into it
p[0]+=P // otherwise, P amount smoke still leave in middle cell
        // which propagate to the next row as described
))

```
> 1 votes

---
Tags: code-golf, grid
---


title: CGAC2022 Day 9: Playing with bits

text:
# Question
Title: CGAC2022 Day 9: Playing with bits
Part of **Code Golf Advent Calendar 2022** event. See the linked meta post for details.

---

The Elves like playing number games. One day, Bin (a friend of Fen) suggests a new game: given a positive integer `n`, each Elf says a number which has exactly `n` runs of ones in binary. The first Elf must say the smallest number, and the next ones must say the smallest number greater than the last one.

## Task

Given `n`, output the sequence.

You can use any of I/O methods:

* Given `n`, output the corresponding sequence infinitely
* Given `n` and the index `k` (may be 1- or 0-indexed), output the `k`th number in the sequence for `n`
* Given `n` and `k`, output the first `k` numbers of the sequence for `n`

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
n = 1
1, 2, 3, 4, 6, 7, 8, 12, 14, 15, 16, 24, 28, 30, 31, 32, 48, 56, 60, 62, 63,
64, 96, 112, 120, 124, 126, 127, ...

n = 2
5, 9, 10, 11, 13, 17, 18, 19, 20, 22, 23, 25, 26, 27, 29, 33, 34, 35, 36, 38,
39, 40, 44, 46, 47, 49, 50, 51, 52, 54, 55, 57, 58, 59, 61, 65, 66, 67, 68, ...

n = 3
21, 37, 41, 42, 43, 45, 53, 69, 73, 74, 75, 77, 81, 82, 83, 84, 86, 87, 89,
90, 91, 93, 101, 105, 106, 107, 109, 117, ...

n = 4
85, 149, 165, 169, 170, 171, 173, 181, 213, 277, 293, 297, 298, 299, 301, 309,
325, 329, 330, 331, 333, 337, 338, 339, 340, 342, 343, 345, ...

n = 5
341, 597, 661, 677, 681, 682, 683, 685, 693, 725, 853, 1109, 1173, 1189, 1193,
1194, 1195, 1197, 1205, 1237, 1301, 1317, 1321, 1322, 1323, 1325, ...

n = 6
1365, 2389, 2645, 2709, 2725, 2729, 2730, 2731, 2733, 2741, 2773, 2901, 3413,
4437, 4693, 4757, 4773, 4777, 4778, 4779, 4781, 4789, 4821, 4949, 5205, ...

```

The corresponding OEIS sequences are A023758 (without leading 0), A043682, A043683, A043684, A043685, and A043686.

# Answer
> 8 votes
# PARI/GP, 55 bytes

```
n->for(i=1,oo,sumdigits(bitxor(i,2*i),2)-2*n||print(i))

```

Attempt This Online!

Outputs the sequence infinitely.

For each positive integer \\$i\\$, print it if the sum of binary digits of \\$\operatorname{bitxor}(i,2i)\\$ is \\$2n\\$.

# Answer
> 6 votes
# Python 3, 61 bytes

```
def f(n,i=1):
 while[n-1!=bin(i).count('01')or print(i)]:i+=1

```

A function that, given the number of runs, \\$n\\$, will print indefinitely.

**Try it online!**

### How?

The number of runs of `1`s is the number of occurrences of `01` plus one (a binary number always starts with a one).

The clause of the `while` loop will always be truthy as it is either `[True]` (when `i` has not got the right number of runs of ones) or `[None]` (when it does and `print(i)` executes and returns `None`).

# Answer
> 5 votes
# JavaScript (V8), 56 bytes

*-2 thanks to @dingledooper*

Prints the sequence infinitely. And so do the other versions.

Using alephalpha's method is more straightforward and shorter. Instead of incrementing each run one by one, \\$k \operatorname{XOR} 2\times k\\$ isolates all of them at once.

```
n=>{for(k=0;g=k=>k&&.5+g(k&k-1);)g(++k^2*k)-n||print(k)}

```

Try it online!

---

# JavaScript (V8), 61 bytes

```
n=>{for(k=0;g=k=>k&&k%2+g(++k/(k&-k)>>1);)g(++k)-n||print(k)}

```

Try it online!

### Recursion logic

Below is an example of the recursion that happens in \\$g\\$ for \\$k=441=110111001\_2\\$, which has three runs of 1's:

```
 0110111001 | odd -> we have a first run of 1's
 0110111010 | increment
 011011101  | divide by (k & -k) --> remove the trailing zeros
 01101110   | right-shift by 1
------------+--------------------------------------------------
 01101110   | even -> this is not a run of 1's
 01101111   | increment
 01101111   | divide by (k & -k) --> no change here
 0110111    | right-shift by 1
------------+--------------------------------------------------
 0110111    | odd -> we have a 2nd run of 1's
 0111000    | increment
 0111       | divide by (k & -k) --> remove the trailing zeros
 011        | right-shift by 1
------------+--------------------------------------------------
 011        | odd -> we have a 3rd run of 1's
 100        | increment
 1          | divide by (k & -k) --> remove the trailing zeros
 0          | right-shift by 1
------------+--------------------------------------------------
 0          | stop

```

---

# JavaScript (V8), 63 bytes

A longer, slower, less fun solution using a regular expression.

```
n=>{for(k=1;;k++)k.toString(2).split(/1+/).length+~n||print(k)}

```

Try it online!

# Answer
> 5 votes
# MATL, ~~14~~ 12 bytes

```
`@BY'wsG=?@D

```

Outputs the sequence indefinitely.

**Try it online!** (you can stop it to see the output).

### Explanation

```
`       % Do...while
  @     %   Push iteration index, starting at 1
  B     %   Convert to binary. Gives, for example, [1 1 0 0 0] at iteration 24
  Y'    %   Run-length encoding. Gives two outputs: [1 0], [2 3] in the example.
        %   (The first output is the one really needed; the second will be
        %   repurposed as loop condition to create an infinite loop)
  w     %   Swap. Moves [1 0] to the top of the stack
  s     %   Sum. This gives the number of runs of ones
  G=    %   Does it equal the input?
  ?     %   If so
    @D  %     Push iteration index and display immediately
        %   End (implicit)
        % End (implicit). The loop condition, [2 3] in the example, is always
        % a vector of non-zero numbers, which is truthy, thereby producing an
        % infinite loop

```

# Answer
> 5 votes
# Rust, 52 bytes

```
|j|(1u32..).filter(move|i|(i^i*2).count_ones()==j*2)

```

Attempt This Online!

Uses the xor trick. Could save 1 byte by using u8 and abusing the "ignore number limits" rule.

# Answer
> 5 votes
# Excel (ms365), ~~86~~, 80 bytes

-8 Bytes thanks to jdt

Formula in `A1`:

```
=LET(x,ROW(A:A),FILTER(x,MAP(BASE(x,2),LAMBDA(a,COUNTA(TEXTSPLIT(a,0,,1))))=B1))

```

`ROW(1:1048576)` is used since that is the upper limit for Excel's rowcount in ms365.

# Answer
> 4 votes
# Raku, 36 bytes

```
{grep *.base(2).comb(/1+/)==$_,1..*}

```

Try it online!

Anonymous function that takes \\$n\\$ and returns an infinite sequence.

# Answer
> 4 votes
# Jelly, 9 bytes

```
BŒgSḢ=ð#`

```

Try it online!

Full program taking `n` and `k` as successive command line arguments, outputting the first `k` elements of the sequence for `n`. A fun 11-byte alternative is `BIAS:2‘ð#``.

```
      ð#`    Count up the first k integers from n, which satisfy, given n:
 Œg          Group runs in the
B            binary representation of the candidate.
   S         Sum the runs column-wise.
    Ḣ=       Is the first sum equal to n?

```

# Answer
> 4 votes
# Python 3, 100 bytes

```
from itertools import*
def f(n):
 k=1
 while 1:
  if 0<len([*groupby(bin(k))])-2*n<3:print(k)
  k+=1

```

Try it online!

`itertools.groupby` can be used to find consecutive groups of equal values, and we can check the total number of groups to verify if its valid.

# Answer
> 3 votes
# Pip, ~~23~~ 21 bytes

```
W++iI$+TBiBXi*2=a*2Pi

```

Try It Online!

Port of @alephalpha's answer. ALternatively, a ~~27~~ 23 byte version taking `n` and `k` and returning the first `k` items

-2 bytes (and -4 from the `n+k` version) thanks to @DLosc

# Answer
> 3 votes
# JavaScript (V8), 55 bytes

Takes \\$ n \\$ as input, and outputs the corresponding sequence infinitely.

Based on the recurrence `f(i) = f(i/2) + (i%4==1)`, which records the number of runs of ones in binary. The funny-looking expression, `i%4%3%2`, is used to save a byte over `(i%4==1)`.

```
n=>{for(i=0;;)(os[++i]=i%4%3%2+~~os[i>>1])-n||print(i)}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
∞ʒbγĀOQ

```

Outputs the infinite sequence.

Try it online or verify the first 100 items up to \\$n\\$=6.

`γĀO` could alternatively be `Ô1ö`:
Try it online or verify the first 100 items up to \\$n\\$=6.

**Explanation:**

```
∞        # Push the infinite list of positive integers: [1,2,3,...]
 ʒ       # Filter it by:
  b      #  Convert the current integer to a binary-string
   γ     #  Split it into groups of equal adjacent items
    Ā    #  Python-style truthify each group: 1 for runs of 1s: "1"/"11"/"111"/etc.;
         #  0 for runs of 0s: "0"/"00"/"000"/etc.
     O   #  Sum it together to get the amount of groups of 1s
      Q  #  Check if its equal to the (implicit) input-integer
         # (after which the filtered infinite list is output implicitly as result)

   Ô     #  Connected-uniquify each group of equal adjacent items
    1ö   #  Convert it from base-1 to base-10, basically summing the digits

```

# Answer
> 3 votes
# \>\<\> (Fish), 71 bytes

```
i1:0$:2%?\2 ,40.
>:?v~{:}= ?^1+10.
01.\:2%?v\$1+$1-2,
1.11,2-1/  /:naob

```

Try

## Explanation

\>\<\> lacks any kind of bitwise operators. So the only way to do this is with modulo. Basically, There I built a state machine that keeps track of the last bit. If `num%2 == 1` and this wasn't true in the last state we add one to the streak.

Top edge, red corner: Setup: Read the input, and start counting from 1.

Top edge: Left dark blue half. Start a loop. Set current streak to 0. Then we reach the state if the last bit was a 0. We mod 1 and if it is 1 we go down to add 1 to the streak. Otherwise we divide the number by 2 and return to the `:2` part.

Second row, left part and third row left half: This is the state where the last bit was a 1. If it is a 1 again we sub 1 div 2 then jump back. If it is a 0 we can go back to the last state 0 state. If the entire number is 0 we jump to middle row right half.

Middle row, right half: Compare the streak to the input. If they are equal print it (bottom right corner red) In either case add 1 to the counter and jump back to the start.

Third row right half: This is the case if the last digit was a 0 but this is a 1. Add one to the streak.

# Answer
> 2 votes
# Charcoal, ~~29~~ 28 bytes

```
ＮθＮη≔⁰ζＷ‹ⅉη«≦⊕ζ¿⁼θ⊕№⍘ζ²01⟦Ｉζ

```

Try it online! Link is to verbose version of code. Outputs the first `k` elements. Explanation:

```
ＮθＮη

```

Input `n` and `k`.

```
≔⁰ζ

```

Start at zero.

```
Ｗ‹ⅉη«

```

Repeat until `k` numbers have been output.

```
≦⊕ζ

```

Try the next number.

```
¿⁼θ⊕№⍘ζ²01

```

If this number has `n-1` copies of `01`, then...

```
⟦Ｉζ

```

... output this number on its own line.

Edit: Saved 1 byte by using @JonathanAllen's run counting technique.

# Answer
> 2 votes
# Vyxal, 8 bytes

```
bĠ∩Ṡ⁰c)ȯ

```

Try it Online!

Takes `k` and `n` and returns the first `k` items.

Port of Jelly.

## Explained (old)

```
b0€ꜝL⁰=)ȯ
-------)ȯ # first k integers where:
b0€       #   the binary representation of the number
   ꜝ      #   with empty lists removed
    L⁰=   #   is of length n

```

# Answer
> 2 votes
# Retina, 129 bytes

```
L$`\d+$
*
"$+"{`_(1*)$
_0$1
T`d`10`01*$
/^(_)+(?<-1>1+(0+|$))+(?(1)^)$/^{`_(1*)$
_0$1
))T`d`10`01*$
+`(\d*)\D+(\d)
$.($1*2*_$2*)¶

```

Try it online! No test suite because of the way the program uses history. Takes `k` and `n` as input and outputs the `k`th number in the sequence for `n`. Explanation:

```
L$`\d+$
*

```

Drop `k` and convert `n` to unary.

```
"$+"{`
)`

```

Repeat `k` times.

```
_(1*)$
_0$1
T`d`10`01*$

```

Increment the binary number after `n`.

```
/^(_)+(?<-1>1+(0+|$))+(?(1)^)$/^{`
)`

```

Repeat while the binary number does not have exactly `n` runs of `1` bits...

```
_(1*)$
_0$1
T`d`10`01*$

```

... increment the binary number after `n`.

```
+`(\d*)\D+(\d)
$.($1*2*_$2*)¶

```

Convert the binary number to decimal.

# Answer
> 2 votes
# Brachylog, 7 bytes

```
ℕ≜ḃḅzh+

```

A generator predicate that takes \\$n\\$ through its output parameter and produces the numbers from the corresponding sequence through its input parameter. Try it online!

### Explanation

```
ℕ≜ḃḅzh+
ℕ        The input parameter is a nonnegative integer
 ≜       Try each possibility in ascending order
  ḃ      Convert to binary digits
   ḅ     Group into blocks (runs of identical items)
    z    Zip the list of blocks
     h   Take the first sublist (which contains the first element of each block)
      +  Sum
         The predicate succeeds if that sum is equal to the output parameter
         (i.e. n); otherwise, it fails, backtracks, and tries the next number

```

# Answer
> 1 votes
# Japt, 12 bytes

```
_¤qT èÊ¥U}jV

```

Try it

Inputs as `n k`. Outputs the first `k` elements. Can be changed to output the `k`-th element (0-indexed) by swapping `j` to `i`. Can reverse the inputs by swapping `U` and `V`.

```
_¤qT èÊ¥U}jV
_        }jV # Get the first k non-negative integers where this is true:
 ¤           #  Convert to binary string
  qT         #  Split using "0" as a delimiter
     èÊ      #  Count the non-empty items
       ¥U    #  Return true if it equals n

```

There could easily be a 4-byte alternative to `qT èÊ`, but I haven't been able to find one yet.

# Answer
> 1 votes
# Pip, 16 bytes

```
W++iI+X1NTBi=aPi

```

Outputs the sequence forever. Try it online!

(Works in both Pip Classic and modern Pip.)

### Explanation

Implements the spec directly.

```
W++iI+X1NTBi=aPi
                  a is first command-line argument; i is 0 (implicit)
W                 Loop while
 ++i              increment i
                  is truthy (i.e. forever):
    I               If...
      X1              Convert 1 to a regex
     +                Apply the + quantifier to it (one or more 1's)
        N             Count the number of matches in
         TBi          i, converted to binary
            =a      ... equals the program argument:
              Pi      Print that value of i

```

# Answer
> 1 votes
# Python, 83 bytes

```
f=lambda n,k,b=1,s=.5:n and((k<b)*(4**(s+n-1)-f(n-.5,b-k-1))or f(n,k,b+b*n/s,s+.5))

```

Attempt This Online!

Given n and k this directly computes the k-th term of the n-th series.

Not competitive with the count-up-and-filter methods but I thought it may be interesting.

# Answer
> 1 votes
# x86 32-bit machine code, 22 bytes

```
53 31 C0 40 6B D8 FE 4B 21 C3 F3 0F B8 DB 39 D3 75 F1 E2 EF 5B C3

```

Try it online!

Following the `fastcall` calling convention, this takes a 1-indexed `k` in ECX and `n` in EDX, and returns a number in EAX.

In assembly:

```
f:  push ebx        # Save the value of EBX onto the stack.
    xor eax, eax    # Set EAX to 0.
r:  inc eax         # Add 1 to EAX. EAX will hold the number, x, being tested.
    imul ebx, eax, -2   # Set EBX to EAX times -2.
    dec ebx         # Reduce EBX by 1, making -2x-1, which is the ones' complement of 2x.
    and ebx, eax    # Set EBX to its bitwise AND with EAX.
        # Before this, EBX has a 1 bit to the left of each 0 bit in x and at the end.
        # The result of this AND has a 1 bit at the end of each run of 1 bits in x.
    popcnt ebx, ebx # Set EBX to the number of 1 bits in EBX.
    cmp ebx, edx    # Compare that with n (in EDX).
    jne r           # Jump back, to repeat, if they are not equal.
    loop r          # Reduce ECX by 1 and jump back if it's nonzero, counting down from k.
    pop ebx         # Restore the value of EBX from the stack.
    ret             # Return.

```

# Answer
> 1 votes
# , 27 bytes

```
[{[:I.]=1#.2</\"1[:#:@i.4^+

```

Try it online!

Takes *k*, 0-indexed, as left argument and *n* as right argument.

```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

```

---

Some earlier versions:

```
[i.~[:+/\]=1#.2</\"1[:#:@i.4^+
[i.~[:+/\]=[:+/2</\0|:[:#:@i.4^+
[i.~[:+/\]=0+/@(}:<}.)@|:[:#:@i.4^+

```

# Answer
> 0 votes
# C (gcc), 79 bytes

```
i;j;m;t;f(n,k){for(i=0;k;k-=!m)for(m=n,j=i++,t=0;j;j/=2)t^j&1?t=!t,m-=t:0;--i;}

```

Try it online!

Inputs \\$n\\$ and \\$k\\$.
Returns the \\$k^\text{th}\\$ number which has exactly \\$n\\$ runs of ones in binary.

# Answer
> 0 votes
# Perl 5, 60 + 2 (`-na` options) = 62 bytes

Given `n` and `k` and outputs the first `k` numbers of the sequence for `n`.

```
{$F+=say if$F[0]==split/0+/,sprintf'%b',++$_;$F[1]>$F&&redo}

```

Try it online!

# Answer
> 0 votes
# Japt, 11 bytes

Returns the `k`th term, 0-indexed

```
@¶X¤ò< Ê}iV

```

Try it

```
@¶X¤ò< Ê}iV     :Implicit input of integers U=n & V=k
@               :Function taking an integer X as argument
 ¶              :  Test if U is equal to
  X¤            :    X converted to a binary string
    ò<          :    Partitioned between characters that are less than each other
       Ê        :    Length
        }       :End function
         iV     :Get the Vth integer that returns true

```

# Answer
> 0 votes
# Julia, 52 bytes

```
>(x,i=0)=count("01",bitstring(i))==x&&@show(i)~x>i+1

```

Attempt This Online!

infinite recursive function, needs Julia 1.3 or later

---
Tags: code-golf, sequence, binary
---


title: LOOOOONG TEEEEEXT

text:
# Question
Title: LOOOOONG TEEEEEXT
## Definition of long text

Long text usually **shows emphasis**, for instance, `loooooool` or `yaaaaaaaaaay`. Usually the vowel is replicated many times. In this challenge we require:

* At least 3 times, which means `yaaay` and `yaaaay` are allowed, but `yay` and `yaay` are not.
* Consistent, which means that shoes can turn out be `shoooeees` or `shooooeeees` but not `shoooeeees` or `shooooeees`. Of course, it seems that no one would do that, however, this is to reinforce the next law.
* Undoubling, which means `beeping` turns out to be `beeepiiing` or `beeeepiiiing` but not `beeeeeepiiing` or `beeeeeeeepiiiing`. This is not the case for long text, but such makes this challenge non-trivial.
* Thus, the long text **might** turn out shorter than the original text, that is, `aaaaa` can turn out to be `aaa`.

## Your challenge

### Input

Your input will be a sentence, that is, you may **not** assume there are only words. We do **not** guarantee all will be English words, so look out for `theeeeeeeeese`.

### Output

The long text for the input.

## Test cases

**We assume you repeat 3 times**.

`The fox yawns...`  =\> `Theee fooox yaaawns...`

`Everything is good!!!!!`  =\> `Eeeveeerythiiing iiis goood!!!!!`  and **NOT** `EEEveeerythiiing iiis gooooood!!!!!`

`Eeny, meeny, miny, moe` =\> `Eeeeeeny, meeeny, miiiny, moooeee`

`AAARGH` =\> `AaaRGH`

`Weeeeeeeeheeeeeee` =\> `Weeeheee`

**Note the treatment of capital letters**: The first letter remains capital, and the others are lowered. `eE` will be `eeeEee`, they won't be the same. "Undoubling" only happens for letters which are of the same case (like `ee` or `AA`, but not for `Ee`)

**Only the letters from `a`, `e`, `i`, `o`, and `u` are vowels, case insensitive**.

# Answer
# Vyxal `d`, 10 bytes

```
ĠƛhA[h:d⇩+

```

Try it Online!

Nice simple answer.

## Explained

```
ĠƛhA[h:d⇩+
Ġƛ         # to each group of consecutive characters:
  hA       #   is the character a vowel?
    [      #   if so:
     h:d   #     Push the character and a string with two copies of that character
        ⇩+ #     and add the lowercase version of that to the character.
# The -d flag flattens all sublists to depth 1 and then sums the list.

```
> 17 votes

# Answer
# Perl 5 `-p`, 29 bytes

Now handles undoubling thanks to \[@Jo King\]!

```
s/((?i)[aeiou])\1*/$1\L$1$1/g

```

Try it online!
> 10 votes

# Answer
# Jelly, 15 bytes

```
ŒgµŒlṁ3fØcȯaẆḢ)

```

Try it online!

```
Œgµ           )    For each run of consecutive equal elements:
   Œl              Lowercase it,
     ṁ3            mold it to length 3,
       fØc         remove non-vowels,
          ȯ        and substitute the original run if that left it empty.
           aẆḢ     Fix the capitalization:
           a       vectorizing logical AND with
            Ẇ      each sublist of the run, individually
           a       because of something to do with how vectorization handles depth?
             Ḣ     and take the head of the resulting list.

```
> 7 votes

# Answer
# Python, 78 bytes

```
lambda s:re.sub(r"([aeiouAEIOU])\1*",lambda m:m[1]+2*m[1].lower(),s)
import re
```

Attempt This Online!

I don't read Perl unless under duress, but if would I'd have to note that this looks very similar to @Dom Hastings' answer.
> 7 votes

# Answer
# JavaScript (ES6), 63 bytes

Repeats 3 times.

```
s=>s.replace(/([AEIOUaeiou])\1*/g,([c])=>c+(c+c).toLowerCase())

```

Try it online!
> 7 votes

# Answer
# Retina, ~~28~~ bytes

```
((?i)[aeiou])\1*
$1$l$1$l$1

```

Try it online! Link includes test cases. Explanation: Port of @DomHastings' Perl answer, but Retina's `$l` operator only operates on the next token, so either as here it has to be repeated for each token to be lowercased or the letters need to be grouped `$1$l$($1$1` which here happens to be the same length as the group does not need to be explicitly closed. Unfortunately Retina's repetition operator does not help here as `$12*$l$1` parses as `${12}*$($l$1)` so the best we can do is `${1}2*$l$1` which is still the same length. Edit: Saved 1 byte thanks to @DomHastings by porting his `(?i)` golf from his answer.
> 6 votes

# Answer
# 05AB1E (legacy), 16 bytes

```
γεDlžMÃĀiÙDlDJ]J

```

Uses the legacy version of 05AB1E, because there is a bug in the new version with `Ā` (Python-style truthify builtin) on empty strings `""`, incorrectly giving a truthy result instead of falsey.

Try it online.

**Explanation:**

```
γ              # Split the (implicit) input-string into parts of equal adjacent
               # characters
 ε             # Map over each part:
  D            #  Duplicate the current part
   l           #  Lowercase the copy
    žM         #  Push the vowels constant "aeiou"
      Ã        #  Only keep those characters from the lowercase copy
       Āi      #  If it's non-empty (thus a part with vowels):
         Ù     #   Uniquify to a single character
          D    #   Duplicate it
           l   #   Lowercase the copy
            D  #   Duplicate that again
             J #   Join the three characters together
 ]             # Close the if-statement and map
  J            # Join everything back together
               # (after which the result is output implicitly)

```
> 5 votes

# Answer
# Python, ~~82~~ ~~80~~ 79 bytes

```
lambda s,*e:''.join([c,(c+2*c.lower())*(e!=c)][(e:=c)in"AEIOUaeiou"]for c in s)
```

Attempt This Online! First time realising that you can use the walrus operator (`:=`) in list comprehension to store the previous value of the iterable. Just needs to be initialised

-1 byte thanks to @Unrelated String
> 5 votes

# Answer
# Husk, 23 bytes

```
ṁ?oS:oR2_←Iȯ€"AEIOU"a←g

```

Try it online!

```
ṁ?oS:oR2_←Iȯ€"AEIOU"a←g
                      g # group identical adjacent letters
ṁ                       # and, for each group, do this and combine the results:
  ?                     # if
                     ←  # the first element
                    a   # in uppercase form
           ȯ€"AEIOU"    # is one of "AEIOU"
         ←              # then get the first element,
        _               # lowercase it,
      R2                # duplicate it,
   S:o                  # and add that to itself;
          I             # otherwise leave the group unchanged

```
> 5 votes

# Answer
# Japt, 14 bytes

```
r"(%v)%1*"Ï+²v

```

Try it (Includes all test cases)

```
r"(%v)%1*"Ï+²v     :Implicit input of string
r                  :Replace
 "(%v)%1*"         :Regex /([AEIOUaeiou])\1*/g
          Ï        :Pass the first submatch (i.e., the first character in the match) through the following function
           +       :Append
            ²      :The character duplicated
             v     :And lowercased

```
> 5 votes

# Answer
# Factor \+ `grouping.extras math.unicode sequences.repeating`, ~~119~~ ~~111~~ ~~109~~ ~~102~~ ~~100~~ 95 bytes

```
[ [ ] group-by values [ dup "aeiouAEIOU"⊂ [ 3 cycle 1 cut >lower append ] when ] map-concat ]

```

Attempt This Online!

Unfortunately Factor's regular expressions are very limited by design so they can't be used to help much. This is still maybe quite golfable regardless.

* `[ ] group-by values` Break the input into groups of contiguous equal characters.
* `[ ... ] map-concat` Map each group to a sequence, all of which get concatenated together in the end.
* `dup "aeiouAEIOU"⊂` Is it a group of vowels?
* `[ 3 cycle 1 cut >lower append ] when` Make it length three and 'capitalize' it if so. (i.e. "aaa" -\> "aaa", "AAA" -\> "Aaa")
> 3 votes

# Answer
# Retina 0.8.2, ~~63~~ ~~47~~ 43 bytes

```
([AEIOUaeiou])\1*
$1$1$1
rT`L`l`\1([AEIOU])

```

~~This can definitely be shorter..~~ It can, see *@Neil*'s Retina answer. My answer uses the older version, which didn't had builtin `$l` yet (nor `$1$1$1` to `3*$1`).
~~I again have the feeling this can be shorter..~~ And it can: -16 bytes thank to *@Neil*, and I've been able to golf it slightly more.

Try it online.

**Explanation:**

Get all consecutive matches of 1 or more of the same vowels, and shorten/extend them to three of these vowels:

```
([AEIOUaeiou])\1*
$1$1$1

```

Lowercase every match of two adjacent uppercase vowels by transliterating in reverse order:

```
rT`L`l`\1([AEIOU])

```
> 3 votes

# Answer
# C (gcc), ~~125~~ ~~121~~ 119 bytes

* -2 thanks to ceilingcat

Scans for vowels and coalesces duplicates, lowercasing the extra output vowels.

```
i,c;f(char*s){for(;c=*s++;){if(index("aeiou",c|32)){for(;i=c==*s;s++);for(;i<3;)putchar(c|!!i++*32);}else putchar(c);}}

```

Try it online!
> 2 votes

# Answer
# V (vim), 34 bytes

```
:%s/\v([aeiouAEIOU])\1*/\1\L\1\1/g

```

Try it online!

Very similar to other regex based solutions.
> 2 votes

# Answer
# Charcoal, 29 bytes

```
ＦＳ¿¬⁼ιψ«ι≔ωψ¿№AEIOU↥ι«≔ιψ↧ι↧ι

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＳ

```

Loop over the characters of the input string.

```
¿¬⁼ιψ«

```

If this is not a duplicate vowel, then:

```
ι

```

Output the current character.

```
≔ωψ

```

Clear the last duplicate vowel.

```
¿№AEIOU↥ι«

```

If this is a vowel, then:

```
≔ιψ

```

Store the last vowel.

```
↧ι↧ι

```

Output the lowercased vowel twice.
> 1 votes

# Answer
# Go, ~~440~~ 428 bytes

```
import(."regexp";."strings")
type S=string
func f(s S)S{M,Q,N,x:=MustCompile,Repeat,NewReplacer,`((?i)[aeiou]`
L:=[]S{}
for _,r:=range`AEIOU`{c:=S(r);l:=ToLower(c);L=append(L,Q(c,3),c,Q(c,2),c,Q(l,3),l,Q(l,2),l)}
R:=N(L...)
l:=R.Replace(s)
for;l!=s;l,s=R.Replace(l),l{}
return N([]S{"AAA","Aaa","EEE","Eee","III","Iii","OOO","Ooo","UUU","Uuu"}...).Replace(M(x+`)`).ReplaceAllString(M(x+`+)`).ReplaceAllString(l,"$1"),"$1$1$1"))}

```

Attempt This Online!

What no regex backtracking does to a mfer.

Looking at other answers, Golang lacks the following regex features that other answers are dependent on:

* Backtracking `(abc)\1`
* Lowercase mode `\L`

So, I've had to make do with a mix of regex and pure string replacement using `strings.Replacer`s to handle the lack of backtracking and lowercase mode.

### Edits

* -12 bytes by moving the code for initializing the translation pairs for `R` out of the function.

### Explanation

```
import(."regexp";."strings") // boilerplate imports
type S=string                // alias string for byte saving
func f(s S)S{                // function of string to string
// define the following:
// - abbreviations for commonly-used functions
// - a partial shared regex
M,Q,N,x:=MustCompile,Repeat,NewReplacer,`((?i)[aeiou]`
// create a new replacer that maps "AAA"=>"A", "AA"=>"A", etc
R:=N(func()(L[]S){for _,r:=range`AEIOU`{c:=S(r);l:=ToLower(c);L=append(L,Q(c,3),c,Q(c,2),c,Q(l,3),l,Q(l,2),l)};return}()...)
// do the replacement...
l:=R.Replace(s)
// ...while the input hasn't changed
for;l!=s;l,s=R.Replace(l),l{}

return
// create another replacer, for the uppercase case
N([]S{"AAA","Aaa","EEE","Eee","III","Iii","OOO","Ooo","UUU","Uuu"}...).Replace(
// match `((?i)[aeiou])`...
    M(x+`)`).ReplaceAllString(
// replace (de-duplicated) vowels...
    M(x+`+)`).ReplaceAllString(l,"$1"),
// with 3 copies of the vowel
    "$1$1$1"))}

```
> 0 votes

# Answer
# Julia 1.0, 59 bytes

```
!x=replace(x,r"((?i)[aeiou])\1*"=>i->i[1]lowercase(i[1]^2))

```

Try it online!

sadly Julia doesn't seem to support `\l` or `\L`
> 0 votes

---
Tags: code-golf, string
---


title: Simple CSV/DSV importer

text:
# Question
Title: Simple CSV/DSV importer
Slightly more than an inverse of this.

**In:** Multi-line DSV data and a single delimiter character. The DSV may be taken as a file, a filename, line-break separated string, list of strings, etc. All records have the same number of fields, and no field is empty. Data does not contain the delimiter character and there is no quoting or escaping mechanism.

**Out:** A data structure representing the DSV, e.g. a list of lists of strings or a matrix of strings.

**Examples**

`["here is,some,sample","data,delimited,by commas"]` and `","`:
`[["here is","some","sample"],["data","delimited","by commas"]]`

`["hello;\"","\";world","\";\""]` and `";"`:
`[["hello","\""],["\"","world"],["\"","\""]]` (escapes because this example uses JSON)

`["to be or not","that is the question"]` and `" "`:
`[["to","be","or","not"],["that","is","the","question"]]`

# Answer
# Jelly, ~~3~~ 2 bytes

*Dennis points out that while the 2 byte solution appears to not work, the dyadic link itself does, and that it is actually the way command line arguments are parsed that make it look that way.*

```
ṣ€

```

**Try It Online!** \- footer calls the function with left and right set explicitly, and formats as a grid\*.

Exactly as the below, except  splits at occurrences of the right argument rather than at sublists equal to the right argument.

---

```
œṣ€

```

The **3 byter** \- footer displays the result as a grid\*.

A dyadic link (function) that takes the DSV list on the left and the delimiter on the right.

### How?

```
œṣ€ - Main link: list l, delimiter d
  € - for each item in l:
œṣ  -     split at occurrences of sublists equal to d

```

* As a full program the implicit output would simply "smush" together all the characters, so the footer of the TIO link calls the link as a dyad and uses `G` to format the result nicely.
> 3 votes

# Answer
# Powershell, ~~25~~ 22/23 bytes

Two Options, one just calls split on the first arg, using the second arg as a delim value.

```
$args[0]-split$args[1]

```

One byte longer, builtin to parse csvs, takes filename as first arg and delim as second.

```
ipcsv $args[0] $args[1]

```

-2 because it doesn't require the `-Delimiter` (`-D`) param, and will assume it by default.

sadly powershell cannot pass an array of two params, as it will assume they are both files, and will run the command against it twice, no other two-var input method is shorter than this as far as I can see, so this is likely the shortest possible answer.

`ipcsv` is an alias for `Import-Csv`, takes a file name as the first unnamed input, and the delim character as the second by default behavior.

Run against the example from the wiki page returns

```
PS C:\Users\Connor\Desktop> .\csvparse.ps1 'example.csv' ','

Date     Pupil               Grade
----     -----               -----
25 May   Bloggs, Fred        C
25 May   Doe, Jane           B
15 July  Bloggs, Fred        A
15 April Muniz, Alvin "Hank" A

```
> 7 votes

# Answer
# Japt, 3 bytes

```
mqV

```

Test it online! (Uses the `-Q` flag to prettyprint the output)

```
mqV  // Implicit: U, V = inputs
m    // Map each item in U by the following function:
 qV  //   Split the item at instances of V.
     // Implicit: output result of last expression

```
> 7 votes

# Answer
# Python, 33 bytes

```
lambda a,c:[x.split(c)for x in a]

```
> 6 votes

# Answer
## Haskell, 29 bytes

```
import Data.Lists
map.splitOn

```

Usage example: `(map.splitOn) " " ["to be or not","that is the question"]` -\> `[["to","be","or","not"],["that","is","the","question"]]`.
> 5 votes

# Answer
# 05AB1E, 5 bytes

```
vy²¡ˆ

```

Try it online!

Explanation:

```
v     For each element in the input array
 y    Push the element
  ²   Push second input
   ¡  Split
    ˆ Add to array

```
> 4 votes

# Answer
## JavaScript, 26 bytes

```
x=>y=>x.map(n=>n.split(y))

```

Receives input in format (array of strings)(delimiter)

Try it online!
> 4 votes

# Answer
# Mathematica, 11 bytes

```
StringSplit

```

Builtin function taking two arguments, a list of strings and a character (and even more general than that). Example usage:

```
StringSplit[{"to be or not", "that is the question"}, " "]

```

yields

```
{{"to", "be", "or", "not"}, {"that", "is", "the", "question"}}

```
> 4 votes

# Answer
# MATLAB / Octave, ~~41~~ 25 bytes

```
@(x,d)regexp(x,d,'split')

```

Creates an anonymous function named `ans` which accepts the first input as a cell array of strings and the second input as a string.

```
ans({'Hello World', 'How are you'}, ' ')

```

**Try it Online**
> 4 votes

# Answer
# Cheddar, 19 bytes

```
a->b->a=>@.split(b)

```

nice demonstration of looping abilities. I added new composition and f.op. blocks so that allows for interesting golfing. `(=>:@.split)` is supposed to work but it doesn't :(
> 4 votes

# Answer
# MATL, ~~14~~ ~~12~~ 4 bytes

```
H&XX

```

Try it at **MATL Online** (the link has a modification at the end to show the dimensionality of the output cell array).

**Explanation**

```
        % Implicitly grab the first input as a cell array of strings
        % Implicitly grab the delimiter as a string
H       % Push the number literal 2 to the stack
&XX     % Split the input at each appearance of the delimiter
        % Implicitly display the result

```
> 3 votes

# Answer
# CJam, 5 bytes

```
l~l./

```

Explanation:

```
l~     e#Input evaluated (as list)
  l    e#Another line of input
   ./  e#Split first input by second

```
> 1 votes

# Answer
## Ruby using '-n', 17+1 = 18 bytes

```
p chomp.split *$*

```

### How it works

* Input from file
* separator is given as command line parameter
* since we only have 1 parameter, `*$*` splats the string and we can use it as a parameter for the `split` function
* I tried to avoid `chomp` but any other solution seems to be longer than this.
> 1 votes

# Answer
# Rebol, 33 bytes

```
func[b s][map-each n b[split n s]

```
> 1 votes

# Answer
## GNU sed, 48 + 1(r flag) = 49 bytes

```
1h;1d
:
G
/,$/bp
s:(.)(.*)\n\1:,\2:
t
:p;s:..$::

```

**Try it online!**

In sed there are no data types, but a natural representation of a list would be a collection of lines. As such, the input format consists of DSV records each on a separate line, with the delimiter present on the first line.

**Explanation:** by design, sed runs the script as many times as there are input lines

```
1h;1d                  # store delimiter, start new cycle
:                      # begin loop
G                      # append saved delimiter
/,$/bp                 # if delimiter is ',', skip replacements and go to printing
s:(.)(.*)\n\1:,\2:     # replace first occurrence of delimiter with ','
t                      # repeat
:p;s:..$::             # print label: delete appended delimiter (implicit printing)

```
> 1 votes

# Answer
## REXX, 95 bytes

```
arg f d
do l=1 while lines(f)
    n=linein(f)
    do #=1 while n>''
        parse var n w (d) n
        o.l.#=w
    end
end

```

Takes a filename and a delimiter as arguments, contents of file are put in stem `o`.
> 1 votes

# Answer
# APL (Dyalog), 4 bytes

In versions up to and including 15.0, this needs `⎕ML←3` which is default by many. From version 16.0  can just be replaced by  for the same effect.

Takes separator as left argument and DSV as right argument.

```
≠⊂¨⊢

```

Try it online!

the inequalities (of the left argument and the right argument)

`⊂¨` partition each

right argument

By partition is mean to remove all elements indicated by a corresponding zero in the left argument, and begin a new partition whenever a the corresponding number in the left argument is greater than its predecessor, i.e. on every one if the left argument is Boolean, as is the case here.
> 0 votes

# Answer
# R, 8 bytes (2 ways)

R has two builtin functions that meet the requirements of this challenge:

```
strsplit

```

takes a vector of strings and a separator, and returns a list of vectors of the separated strings.

```
read.csv

```

takes a file name and a separator, and returns a data frame. Technically this might be 10 bytes because it needs the option `header=F` so it won't read the first elements as the column names. Currently the TIO link reads from stdin.

Try these online!
> 0 votes

# Answer
# Go, 136 bytes

```
import."strings"
func f(S[]string,d rune)(O[][]string){for _,s:=range S{O=append(O,FieldsFunc(s,func(r rune)bool{return r==d}))}
return}

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, string, parsing, generation, data-structures
---


title: Output a random OEIS sequence

text:
# Question
Title: Output a random OEIS sequence
Your challenge: Connect to the Online Encyclopedia of Integer Sequences OEIS.org, access any random valid sequence, output it's ID, and ouput all of the members of the sequence provided by the OEIS entry. The *only* website you're allowed to connect to is OEIS.org.

Hints: Sequences are found in URLs such as http://oeis.org/A280629, however a more easily parseable version is found at URLs such as http://oeis.org/search?q=id:A280629&fmt=text. Every present *and future* sequence matches the regex `"[A-Z]\d{6}"`. (The regex is there to describe what an ID looks like. There are a lot of invalid sequences that match it, too). The webcam (http://oeis.org/webcam) feature of OEIS generates random sequences, but you'll have to find a way to change the dropdown menu from 'best sequences' to 'all sequences' to use it.

Example output:

```
A280629
1, 1, 7, 139, 6913, 508921, 57888967, 9313574419, 1984690709953, 547467006437041, 188946742298214727, 79783392959511537499, 40498043815904027702593, 24314800861291379306213161, 17047720745682515427867108487, 13802952030641885344209574247779, 12780883488499783875309105315925633, 13420910251496135926622603184056054881, 15863354775169518855398667975850797997447, 20966527201075972453953302254528386060431659

```

Every existing sequence has to have a chance of being outputed, it does not have to be an equal chance.

Your program should continue to function properly regardless of future sequences being added. Even though all IDs presently start with A, there will eventually be a sequence B000001 after all the A sequences run out. You can assume that there will be no more sequences after Z999999 is defined, but you do have to assume that it *will* eventually be defined.

An invalid sequence, which your program should never output, is one that doesn't exist. You may treat sequences with no given members (such as A280611 either as invalid or give just the sequence ID and nothing else or a falsy value, but you must be consistent.

This is , fewest bytes wins!

# Answer
## Perl, 93 bytes

```
$u=chr(65+rand 26).sprintf("%06d",rand 1e6),$_=`curl oeis.org/$u`while!/tt>(.*?)</;say"$u
$1"

```

Run it with `-E` flag (and I suggest redirecting `STDERR`, as `curl` prints its progression on it):

```
perl -E '$u=chr(65+rand 26).sprintf("%06d",rand 1e6),$_=`curl oeis.org/$u`while!/tt>(.*?)</;say"$u
$1"' 2> /dev/null

```

Explanations:
-`$u=chr(65+rand 26).sprintf("%06d",rand 1e6)` generates a random name,
-`$_=curl oeis.org/$u` tries to retrieve the sequence,
-`/tt>(.*?)</` checks if a tag `<tt>` is present on the page (it's only present on valid pages). If so, it stores the sequence's elements in `$1`. And if not, the `while` keeps looping.
-`say"$u\n$1"` outputs the sequence's name and its elements.
> 4 votes

# Answer
## Python 3, 221,208 bytes

```
from requests import*
from random import*
import re
r=randint
g=lambda x:re.findall(r'(?<=tt>)[^<]*',get('https://oeis.org/'+x).text)
a=''
while not g(a):a=chr(r(65,90))+str(r(0,999999))
print(a+'\n'+g(a)[0])

```

I'm sure there's a few tricks I missed (and requests is an external lib), but this was a fun first go at python code golf
> 2 votes

# Answer
# JavaScript, 104 bytes

Because someone commented that this isn't possible in JS!

Must be run from the root directory of OEIS (consensus). Returns a 2-element array, with the first element being the sequence number and the second the sequence itself.

```
f=async n=>(s=/tt>[^<]+/.exec(await(await fetch(n+=Math.random()*1e6|0)).text()))?[n,s[0].slice(3)]:f`A`

```

To test it, go to the OEIS homepage (or any sequence's page), open your browser's console and copy & paste the code below:

```
f=async n=>(s=/tt>[^<]+/.exec(await(await fetch(n+=Math.random()*1e6|0)).text()))?[n,s[0].slice(3)]:f`A`
await f()

```

## 97 bytes

This *should* work and could maybe be golfed a little further but I'm on my phone so can't test it properly.

```
f=async n=>(s=/(?<=tt>)[^<]+/.exec(await(await fetch(n+=Math.random()*1e6|0)).text()))?[n,s]:f`A`

```
> 1 votes

---
Tags: code-golf, sequence, random, internet
---