[Question]
  [
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) 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 [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") 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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") 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](http://oeis.org/A023758) (without leading 0), [A043682](http://oeis.org/A043682), [A043683](http://oeis.org/A043683), [A043684](http://oeis.org/A043684), [A043685](http://oeis.org/A043685), and [A043686](http://oeis.org/A043686).
  
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 55 bytes
```
n->for(i=1,oo,sumdigits(bitxor(i,2*i),2)-2*n||print(i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN83zdO3S8os0Mm0NdfLzdYpLc1My0zNLijWSMksqQOI6RlqZmjpGmrpGWnk1NQVFmXklGpmamhDtS9I0zKDMBQsgNAA)
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]
# [Python 3](https://docs.python.org/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!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI08n09ZQ04pLoTwjMyc1Ok/XUNE2KTNPI1NTLzm/NK9EQ93AUF0zv0ihoCgTyMvUjLXK1LY1/J@mYab5HwA "Python 3 – 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]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 12 bytes
```
`@BY'wsG=?@D
```
Outputs the sequence indefinitely.
[**Try it online!**](https://tio.run/##y00syfn/P8HBKVK9vNjd1t7B5f9/IwA) (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]
# [Rust](https://www.rust-lang.org), 52 bytes
```
|j|(1u32..).filter(move|i|(i^i*2).count_ones()==j*2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LcwxDoIwGAXgnVNUpr9GG0VNDFA8g4ujxJA2-bG0prQulJO4MOjudbyNGHzLS17yvsfT-tYNb6lJc0ENtFPCEclf3snl_rMNdYC13ySMUSZROWGhMXcRMACecZ5QVhmvXWm0aIFyXo_T_3vMImksQYKaTATfkS4iY24WtVN6BnGXHvp4IQEpc5ergGT1E5USlUvT_CSqvCwKoDSL-qif4GGY-gs)
Uses the xor trick. Could save 1 byte by using u8 and abusing the "ignore number limits" rule.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 56 bytes
*-2 thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)*
Prints the sequence infinitely. And so do the other versions.
Using [alephalpha's method](https://codegolf.stackexchange.com/a/255350/58563) 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!](https://tio.run/##BcFRCoAgDADQ28iWGCUEgcyjBBIoNjAx8Sc7u713ueaes8RcVduHp5HIvv4uwLSYQEyWhZg3GYAFqxUNBpCSDz0xqtR7LjFVYPyGB43jBw "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 61 bytes
```
n=>{for(k=0;g=k=>k&&k%2+g(++k/(k&-k)>>1);)g(++k)-n||print(k)}
```
[Try it online!](https://tio.run/##HchBCoAgEADA1yS7iFSeAln/EoFiCyYmXrK3b9Ac59z7fh81lWb6JoEkk3/CVYFpcZGYPCvFk9URtOYZWBlG71d0@A@aPEapKTdgfCWARfkA "JavaScript (V8) – 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)](https://v8.dev/), 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!](https://tio.run/##DcpBCoAgEADA7yiSYqdA7BO9QCLLFBVdvGR9ffM8c5tm6l5chqktaDVGvT42FeK1VMozRj2HtEFx8SQz5TUHB0RIJigPRzzhYl/sPQ8H4umLdiz8AQ "JavaScript (V8) – Try It Online")
[Answer]
# Excel (ms365), ~~86~~, 80 bytes
-8 Bytes thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)
[![enter image description here](https://i.stack.imgur.com/YQNgd.png)](https://i.stack.imgur.com/YQNgd.png)
[![enter image description here](https://i.stack.imgur.com/NX90l.png)](https://i.stack.imgur.com/NX90l.png)
[![enter image description here](https://i.stack.imgur.com/PL5lL.png)](https://i.stack.imgur.com/PL5lL.png)
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]
# [Raku](https://github.com/nxadm/rakudo-pkg), 36 bytes
```
{grep *.base(2).comb(/1+/)==$_,1..*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@786vSi1QEFLLymxOFXDSFMvOT83SUPfUFtf09ZWJV7HUE9Pq/Z/cWKlQpqGoWZ0nLFBrDUXhGuEyjWGcv8DAA "Perl 6 – Try It Online")
Anonymous function that takes \$n\$ and returns an infinite sequence.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
BŒgSḢ=ð#`
```
[Try it online!](https://tio.run/##y0rNyan8/9/p6KT04Ic7Ftke3qCc8P//f7P/RgYA "Jelly – 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]
# [Python 3](https://docs.python.org/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!](https://tio.run/##DcpBCsMgEEDRvaeYpVoKsaGbkJykdBPqNINmRsyUktMbl//xy6mb8NgaVtmBNFYVyQfQXqSqN5@IgJbdZCAtwcB/oxwh9ARCGOYc2b78t8qvrKddiW1y7u3uD8/zOJVKrF36nW5LaGifrl0 "Python 3 – 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]
# [JavaScript (V8)](https://v8.dev/), 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!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9auOi2/SCPT1sDaWlMjvzhaWzsz1jZT1UTVWNVIu64OKJJpZ2cYq6mbV1NTUJSZV6KRqVn7P03DSPM/AA "JavaScript (V8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒbγĀOQ
```
Outputs the infinite sequence.
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8U5OSzm0@0uAf@P@/CQA) or [verify the first 100 items up to \$n\$=6](https://tio.run/##AS8A0P9vc2FiaWX/NkVOwqk/IiDihpIgIj//4oieypJizrPEgE/CrlH/fdGCwqMswrY//w).
`γĀO` could alternatively be `Ô1ö`:  
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8U5OSDk8xPLwt8P9/EwA) or [verify the first 100 items up to \$n\$=6](https://tio.run/##AS8A0P9vc2FiaWX/NkVOwqk/IiDihpIgIj//4oieypJiw5Qxw7bCrlH/fdGCwqMswrY//w).
**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]
# [Pip](https://github.com/dloscutoff/pip), ~~23~~ 21 bytes
```
W++iI$+TBiBXi*2=a*2Pi
```
[Try It Online!](https://tio.run/##K8gs@P8/XFs701NFO8Qp0ykiU8vINlHLKCDz////xgA)
Port of [@alephalpha's answer](https://codegolf.stackexchange.com/a/255350/110555). ALternatively, [a ~~27~~ 23 byte version](https://dso.surge.sh/#@WyJwaXAiLCIiLCJMYntUJCtUQjIqVWlCWGk9YSoyeFBpfSIsIiIsIjMgMTAiLCIiXQ==) taking `n` and `k` and returning the first `k` items
-2 bytes (and -4 from the `n+k` version) thanks to @DLosc
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 71 bytes
```
i1:0$:2%?\2 ,40.
>:?v~{:}= ?^1+10.
01.\:2%?v\$1+$1-2,
1.11,2-1/  /:naob
```
[Try](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTE6MCQ6MiU/XFwyICw0MC5cbj46P3Z+ezp9PSA/XjErMTAuXG4wMS5cXDoyJT92XFwkMSskMS0yLFxuMS4xMSwyLTEvICAvOm5hb2IiLCJpbnB1dCI6Ilx1MDAwMiIsInN0YWNrIjoiIiwibW9kZSI6Im51bWJlcnMifQ==)
## Explanation
[![enter image description here](https://i.stack.imgur.com/OuiuZ.png)](https://i.stack.imgur.com/OuiuZ.png)
><> 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]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
bĠ∩Ṡ⁰c)ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJixKDiiKnhuaDigbBjKcivIiwiIiwiMTBcbjIiXQ==)
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]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 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!](https://tio.run/##VcstDgIxEIZhP8fYfGJ@AttZFAkBg0Qim3ZIisAgyDo4FwfgYgUcqDeveG7n@XI9ee8HRG4GUhpgwz0quwqoJjgdo4WnSK6gsXAV491m4Vs3TvaAfJ9dimAs/1Lk11pwbip5b58KYclwnbRiUnk9e1/T6g0 "Retina – 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]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 28 bytes
```
ＮθＮη≔⁰ζＷ‹ⅉη«≦⊕ζ¿⁼θ⊕№⍘ζ²01⟦Ｉζ
```
[Try it online!](https://tio.run/##TYy7CsIwFIbn9ikOnU4gQtVJnLQ4FFQEJxGHWNMmkKZtLgoVnz0GdOi/ff@tEsxUHVMhlLr37ujbOzc4kHU6ZRF5Y61sNOYUxkgvIRUH3HNr8YKEgiAE3mlyYP2/WOrK8JZrxx@/SSJrwN3gmbI4UJjkWHReO9wyy8/OSN3gSGERT7N8npEoOEXX4bVg1uFIbvHtE8ISVmH2VF8 "Charcoal – 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]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
ℕ≜ḃḅzh+
```
A [generator](https://codegolf.meta.stackexchange.com/a/10753/16766) predicate that takes \$n\$ through its output parameter and produces the numbers from the corresponding sequence through its input parameter. [Try it online!](https://tio.run/##ASsA1P9icmFjaHlsb2cy/37ihrDigoHhuoniiqX/4oSV4omc4biD4biFemgr//82 "Brachylog – 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]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_¤qT èÊ¥U}jV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X6RxVCDoyqVVfWpW&input=NiA1)
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]
# [Pip](https://github.com/dloscutoff/pip), 16 bytes
```
W++iI+X1NTBi=aPi
```
Outputs the sequence forever. [Try it online!](https://tio.run/##K8gs@P8/XFs701M7wtAvxCnTNjEg8////8YA "Pip – 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]
# [Python](https://www.python.org), 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!](https://ato.pxeger.com/run?1=NY5BDoIwEEXXeoouZ8q0QmKNIfYUnqANVgEdCMWFZ3HDRu_kbSxRlv_9vJ__fPeP8dLxNL3uY1D7zzHYq7v5ygmmlrwtKFptShaOK4D24FHCVkqIGasCVQBW2pBXbUrYDSKB2cu85E2kmGmD-J_ehdQ3omYxOD6foMhzLNerfqh5hIYCGGqQfM0wg1_ExV4OfgE)
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]
# 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!](https://tio.run/##jVLdToMwFL5un@I4s6QVMHOaGIfzDbzxysSZpStlnAmF8KMsulcXT9mcUxNjL3o4/c73A1QHS627TlUZCLgbCB5PWNFUCZhFy1mbl2BU67uNlxOGVvePDLMmdSP@Fg7GnEVGb0nKRnuIsyIvtK13Bw7WWbHrIupW1kDJWZrnhas03U@ZCStNzeVAhnw@V3Vd4qKpzXwuRKyqWqs0lRKQhGPh9ie/b6wM4TlH8hcy7I4pbtpEBq6rOsL8NLnhbihTaIXkr@RWUh@LAbw5HxbT2/ZqK5jCWUjlaApXVD1PcjhYe97wAgc@rBz582xmAy/45/ruiltXdK6XVJ0ro5QH0kN8Iz90tL/Tsi/WLmQsVj5Kx9wchp3ZW6UTpL@g88hM@kROtCXRkQ9raqMcXr/ERuN7UltPhWhshUtrItCJKk9kLB/aRxlu4CXB1MBvHDxoPc@l/AmZww8IYoiwWNemkjNLVq0D6TI0pYVRyDfdu45Ttay6IDsf00ZXd0pMk34A "C (gcc) – 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]
# [J](http://jsoftware.com/), 27 bytes
```
[{[:I.]=1#.2</\"1[:#:@i.4^+
```
[Try it online!](https://tio.run/##y/r/P03B1kohujraylMv1tZQWc/IRj9GyTDaStnKIVPPJE77f2pyRr6ChqGCtkKmnqmmgkZanYKSgoGCgaa@ggZI5D8A "J – Try It Online")
Takes *k*, 0-indexed, as left argument and *n* as right argument.
* `4` `^` `+`: Raise 4 [to the power (`^`)](https://www.jsoftware.com/help/dictionary/d200.htm) of [the sum (`+`)](https://www.jsoftware.com/help/dictionary/d100.htm) of *k* and *n*. This is an upper bound for the result, as can be proven by considering numbers of the form `(10)*10*` in binary.
* `[:` `#:` `@` `i.`: [Make a list of the integers from 0 (inclusive) to 4*k*+*n* (exclusive) using `i.`](https://www.jsoftware.com/help/dictionary/didot.htm), and then [by composition (`@`)](https://www.jsoftware.com/help/dictionary/d620.htm), [convert those numbers into their binary representations (`#:`)](https://www.jsoftware.com/help/dictionary/d402.htm), using [a 'cap' (`[:`)](https://www.jsoftware.com/help/dictionary/d502.htm) to do so monadically.  
The result is a table like this, where each row is a binary representation:
```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
```
* `2` `<` `/` `\` `"` `1`:
	+ [For each infix (`\`)](https://www.jsoftware.com/help/dictionary/d430.htm) of length 2 (each pair of consecutive bits), apply ['less than' (`<`)](https://www.jsoftware.com/help/dictionary/d010.htm) [between the bits (`/`)](https://www.jsoftware.com/help/dictionary/d420.htm), producing 1 for each 0–1 pair (which appears at the start of each run of ones) and 0 otherwise.  
	Note that this will miss the first run when the very first bit is 1, in the second half of the numbers, but there is enough excess in the upper bound of 4*k*+*n* to let us ignore the second half.
	+ On its own, that construction would incorrectly take pairs of *rows*. To fix that, [set its rank (`"`)](https://www.jsoftware.com/help/dictionary/d600v.htm) to 1, so that it applies separately to each row, and then it takes pairs of bits within the rows.
* `1` `#.`: [Convert from base 1](https://www.jsoftware.com/help/dictionary/d401.htm), obtaining the number of runs of ones in each number. Conveniently, this naturally has rank 1, so it doesn't need rank adjustment.
* `]` `=`: [Check for equality (`=`)](https://www.jsoftware.com/help/dictionary/d000.htm) with [the right argument *n* (`]`)](https://www.jsoftware.com/help/dictionary/d500.htm).
* `[:` `I.`: On a list of 0s and 1s, as here, [`I.` gives a list of the indices of the 1s](https://www.jsoftware.com/help/dictionary/dicapdot.htm). Again, use [a 'cap' (`[:`)](https://www.jsoftware.com/help/dictionary/d502.htm) to do this monadically.
* `[` `{`: Use [the left argument *k* (`[`)](https://www.jsoftware.com/help/dictionary/d500.htm) [as an index (`{`) into the list](https://www.jsoftware.com/help/dictionary/d520.htm).
---
Some earlier versions:
```
[i.~[:+/\]=1#.2</\"1[:#:@i.4^+
[i.~[:+/\]=[:+/2</\0|:[:#:@i.4^+
[i.~[:+/\]=0+/@(}:<}.)@|:[:#:@i.4^+
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 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!](https://tio.run/##fVXtbtpAEPyfp7gipcLBKL4P39l13f6o@hQJlSJiUkxwInBV1IhXL51Z85HEqJFY1rNze7NzhzMdP0ynu928qItl0RazYRMvopfZ02o4L5NiUSzG5YdlxOdl2cR1OR@N4haVuqivSxO1P@qP@mtbfmjj5bhsPyXFeDwvtrt506rl3bwZRurlQuGPQLV5rqZtda9vJqpULzpWJlY2Vi5WPlYhVlmsNCANQKf4ADXIDXCb4IMVFnWH5xQ1D8zj2aOHBy8HpqWBSRjYxhAzYVv0VJhOBfbJQeECtNdopaFEUwpwNjLoaIAbUNnOoG5Qs8As9rDALXBLmcAd1jjgDpgD1wFLgaXon6JXilqKNSlqKUdB3aPmgXmOBdxnZxTbTrGhDeyLb0c7aCH70Qb0CvgO2CMAC3QVvAy8DHgGPMMeGXFwc@jKUc85d0IDEhqf0LWEPiQ0R5/zz3VqMvI5ovZyZMwC3QzsRi2aAgydNUGsY5ZLljHQSm5tuZely7azl0cuZy5Oc2QrHtNkS5ctx7dOziE9IzHtJFo6lXJHLz4HMZgZbfH0xXMMT2WBAjJ6qQ/DS55JLj7p3ElMJQa5b8wNJWqZRVu5RdZIzhuEaCWeE@r3vwhLD43lXsbzTE2gBiOiECWnL4haorjqJA/iqzjp6LZzcktkKhd425xwELs8k8gbG@gGIvOMml0utxZznVHbdGrX8z/V02x4/FVH13vk6gTF6h3L9Fmmz7J9lu2zXJ/l@qy0z0r7LN9n@eg0@9Vx@G7244Tx6X1ySu0pdaf0YOX0qVm3avrzbnWFWE0X1aprOrjdfDe3m/wbPukgVq@f7WC/Gq9iNeRpzJv7aoNlSbFPP7@fKVLX6v1QUaFGI@Ef3sxvmtavutaHtoFr6t6iw7VoQO@oI6WLXnmBcv2f@hr17t9Ov1ahdjReekxuul6Tt@TnFeiz4aApL@9jtUBU4y8K8XJ928DKBiDOPD74jU3RefJqy@3FKa6q9teqgQcX293f6ezx7mG9G//ejR@X/wA "C (gcc) – Try It Online")
Inputs \$n\$ and \$k\$.  
Returns the \$k^\text{th}\$ number which has exactly \$n\$ runs of ones in binary.
[Answer]
# [Perl 5](https://www.perl.org/), 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!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/WsVN27Y4sVIhM03FLdog1ta2uCAns0TfQFtfp7igKDOvJE1dNUldR1tbJd4aqMIw1k7FTU2tKDUlv/b/f2MFQ4N/@QUlmfl5xf918xIB "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Returns the `k`th term, 0-indexed
```
@¶X¤ò< Ê}iV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLZYpPI8IMp9aVY&input=NQo4)
```
@¶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]
# [Julia](https://julialang.org), 52 bytes
```
>(x,i=0)=count("01",bitstring(i))==x&&@show(i)~x>i+1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdN7DQqdDJtDTRtk_NL80o0lAwMlXSSMkuKS4oy89I1MjU1bW0r1NQcijPyy4G8ugq7TG1DiN4ldhpmmhAmzDgA)
infinite recursive function, needs Julia 1.3 or later
]