title: Numbers with multiple runs of ones

text:
# Question
Title: Numbers with multiple runs of ones
### Task

Find the set of numbers such that the binary representation contains two or more runs of `1` separated by at least one `0`.

For example, the for the numbers that are 4 bits long:

```
 0 0000        (no ones)
 1 0001        (only one run)
 2 0010        (only one run)
 3 0011        (only one run)
 4 0100        (only one run)
 5 0101 Valid
 6 0110        (only one run)
 7 0111        (only one run)
 8 1000        (only one run)
 9 1001 Valid
10 1010 Valid
11 1011 Valid
12 1100        (only one run)
13 1101 Valid
14 1110        (only one run)
15 1111        (only one run)

```

### Input

An integer provided to the application via some input in the range `3 .. 32`. This represents the maximum number of bits to count up to.

The input of `n` indicates that the numbers `0 .. 2<sup>n</sup>-1` need to be examined.

### Output

A delimited (your choice) list of all numbers meeting the criteria. The numbers are to be presented in numeric order. An extra trailing delimiter is acceptable. Data structure enclosures (e.g. `[]` and similar) are also acceptable.

### Example

```
Input: 3
Output: 5

Input: 4
Output: 5, 9, 10, 11, 13

Input: 5
Output: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29

```

This is - the answer with the least amount of bytes wins.

# Answer
# Pyth, 12 bytes

```
f<2r.BT8U^2Q

```

Try it online.

### Idea

The binary representation of any positive number always begins with a run of **1**s, possibly followed by other, alternating runs of **0**s and **1**s. If there are at least three separate runs, two of them are guaranteed to be runs of **1**s.

### Code

```
              (implicit) Store the evaluated input in Q.
         ^2Q  Calculate 2**Q.
f       U     Filter; for each T in [0, ..., 2**Q-1]:
    .BT         Compute T's binary representation.
   r   8        Perform run-length encoding.
                This returns a list of character/run-length pairs.
 <2             Discard the trailing two pairs.
                This returns a non-empty array if there are more than 2 runs.
              Keep T if the array was truthy (non-empty).

```
> 8 votes

# Answer
## Python, 48

```
lambda n:[i for i in range(2**n)if'01'in bin(i)]

```

I had been vastly overthinking this. We just need to check if the binary expansion contains `'01'`.

For there to be two runs of ones, the one on the right must be preceded by a `0`. If there's only one run, there won't be any leading `0`'s, so that won't happen.

---

Old answer:

```
lambda n:[i for i in range(2**n)if len(set(bin(i).split('0')))>2]

```

The Python binary representation works very nicely here. A binary number is written like `bin(9)=='0b10110'`. Splitting at `'0'` results in a list of

* Empty strings to the left of the initial `0`, between any two consecutive `0`'s, and to the right of any final `0`
* The letter `b` followed by one or more leading ones
* Runs of `1`'s that are not leading

The first two categories always exist, but the last one only exists if there is a run one `1`'s that doesn't contain the leading `'1'`, and so only if there's more than one run of `1`'s. So, it suffices to check if the list contains more than `2` distinct elements.

Python 3.5 saves 2 chars by unpacking `{*_}` in place of `set(_)`.
> 23 votes

# Answer
## Ruby, ~~44~~ ~~40~~ 38 chars

crossed out 44 is still regular 44 ;(

```
->n{(0..2**n).select{|x|/01/=~'%b'%x}}

```

An anonymous function (proc, actually) that takes an integer and returns an array.

~~Uses the regex `/10+1/`: a `1`, at least one `0`, and then another `1`.~~ @histocrat points out that if `01` is anywhere in the string, there *must* be a `1` somewhere before it.
> 15 votes

# Answer
# Julia, ~~43~~ 41 bytes

```
n->filter(i->ismatch(r"01",bin(i)),1:2^n)

```

This creates an unnamed function that accepts an integer and returns an array. It uses histocrats's regex trick (used in Doorknob's answer), where `01` will only match if there's a preceding 1.

Ungolfed:

```
function f(n::Int)
    # Take the integers from 1 to 2^n and filter them down to
    # only those such that the binary representation of the integer
    # matches the regex /01/.
    filter(i -> ismatch(r"01", bin(i)), 1:2^n)
end

```
> 8 votes

# Answer
# Matlab, ~~79 68 64~~ 59

The idea is interpreting the binary number as array of zeros and ones, and then calculating the absolute difference between each pair of neighbours. If we have two or more times a difference of 1, then we obviously have a run of two or more ones. Note that this only works if we represent the binary number without leading zeros.

```
@(n)find(arrayfun(@(k)sum(~~diff(dec2bin(k)+0))>1,1:2^n-1))

```

Old versions:

```
k=1:2^input('')-1;k(arrayfun(@(k)sum(~~diff(dec2bin(k)+0))>1,k))

for k=1:2^input('')-1;if sum(~~diff(dec2bin(k)+0))>1;disp(k);end;end

for k=1:2^input('')-1;if sum(~~conv(dec2bin(k)+0,[-1,1],'v'))>1;disp(k);end;end

```
> 7 votes

# Answer
# JavaScript (ES7), ~~89~~ ~~85~~ ~~72~~ ~~69~~ 62 bytes

Holy cow, creating ranges in JS is not easy. ~~Perhaps it would be shorter with an actual `for` loop.~~ Nope, I lied; it's actually a bit longer. Oh well. I guess I'll just have to settle for 27 bytes saved. (7 thanks to Mwr247!)

```
x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a]

```

Works properly in the latest versions of Firefox, but probably not in any other browser. Try it out:

```
<!--                               Try the test suite below!                              --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px">5</textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode="x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a]";function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>
```

(Snippet taken from this page)

Suggestions welcome!
> 6 votes

# Answer
# Haskell, ~~68~~ ~~61~~ 53 bytes

Improvement from Damien

```
g x|x`mod`4==1=x>4|2>1=g$x`div`2
a x=filter g[1..2^x]

```

History:

This fixes the bug(Switched == and =, and square instead of power of two). And replace true with 2\>1 and false with 1\>2. Also thanks to point out that 2^x is always fail. Thanks to Thomas Kwa and nimi

```
g x|x<5=1>2|x`mod`4==1=2>1|2>1=g$x`div`2
a x=filter g[1..2^x]

```

Originally

```
g x|x<5=False|x`mod`4=1==True|2>1=g$x`div`2
a x=filter g[1..(x^2-1)]

```

If it have to be full program,

```
g x|x<5=False|x`mod`4==1=True|2>1=g$x`div`2
main=interact$show.a
a x=filter g[1..2^(read x)]

```
> 6 votes

# Answer
# APL, ~~34~~ 27 bytes

```
{0~⍨{⍵×2<+/2≢/⍵⊤⍨⍵/2}¨⍳2*⍵}

```

This creates an unnamed monadic function that accepts an integer on the right and returns an array.

Explanation:

```
                     }¨⍳2*⍵}  ⍝ For each integer from 1 to 2^input...
              ⍵⊤⍨⍵/2         ⍝ Get the binary representation as a vector
           2≢/                ⍝ Pairwise non-match, yielding a boolean vector
       2<+/                   ⍝ Check whether the number of trues is >2
     ⍵×                       ⍝ Yield the integer if so, otherwise 0
{0~⍨{                         ⍝ Remove the zeros from the resulting array

```

Saved 7 bytes thanks to Dennis!
> 5 votes

# Answer
# C (gcc), 111 99 bytes

```
long i,x;main(a,b)char**b;{for(;++i<1L<<atol(b[1]);x>>ffsl(~x)-1&&printf("%ld,",i))x=i>>ffsl(i)-1;}

```

Try it online!

12 bytes shaved of thanks to @ceilingcat!

Ungolfed:

```
int main(int a, char **b) {
  for(long i = 0, x = 0; ++i < (1LL << atol(b[1])); ) {
    x = i >> (ffsl(i) - 1);
    if (x >> (ffsl(~x) - 1))
      printf("%ld,", i);
  }
}

```

The function ffsl() gives you the index of the first bit that is set in a long integer. So we loop from `i = 1` to 2^number\_of\_bits. We set `x` to `i` shifted right until we have removed all consecutive zero bits on the least significant end. Then, we shift `x` right until we have removed all consecutive 1 bits at the least signficant end. If the result is still non-zero, we found a match.
> 5 votes

# Answer
## Java, ~~214~~ ~~165~~ ~~155~~ ~~154~~ ~~148~~ ~~141~~ 110 bytes

This submission exploits the fact that a binary string representation of a number in Java never has a leading zero. If the string "01" appears in the binary representation of a number, that *must* mark the second occurrence of the number "1".

Golfed:

```
String f(int l){String r="";for(long i=5;i<1L<<l;++i)if(Long.toString(i,2).contains("01"))r+=i+", ";return r;}

```

Ungolfed:

```
public class NumbersWithMultipleRunsOfOnes {

  public static void main(String[] a) {
    // @formatter:off
    String[][] testData = new String[][] {
      { "3", "5" },
      { "4", "5, 9, 10, 11, 13" },
      { "5", "5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29" }
    };
    // @formatter:on

    for (String[] data : testData) {
      System.out.println("Input: " + data[0]);
      System.out.println("Expected: " + data[1]);
      System.out.print("Actual:   ");
      System.out.println(new NumbersWithMultipleRunsOfOnes().f(Integer.parseInt(data[0])));
      System.out.println();
    }
  }

  // Begin golf
  String f(int l) {
    String r = "";
    for (long i = 5; i < 1L << l; ++i)
      if (Long.toString(i, 2).contains("01")) r += i + ", ";
    return r;
  }
  // End golf
}

```

Program output (remember, trailing delimiters are acceptable):

```
Input: 3
Expected: 5
Actual:   5,

Input: 4
Expected: 5, 9, 10, 11, 13
Actual:   5, 9, 10, 11, 13,

Input: 5
Expected: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29
Actual:   5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29,

```
> 4 votes

# Answer
# CJam, 14

```
2qi#{2b2,#)},p

```

3 bytes shorter thanks to Dennis. Try it online
> 4 votes

# Answer
# R, 55 47 bytes

(with some help from @Alex.A)

```
cat(grep("10+1",R.utils::intToBin(1:2^scan())))

```

R doesn't have a built in function to display converted numbers in a convenient way, so I'm using `R.utils::intToBin` for this, while all the rest is pretty much just report the location of the matched regex expression and print to STDOUT while separated by a space.
> 4 votes

# Answer
# JavaScript (ES6), ~~69~~ ~~68~~ ~~67~~ 62 bytes

```
a=>[...Array(1<<a).keys()].filter(i=>/01/.test(i.toString(2)))

```

Today I discovered a new shorter way to dynamically fill arrays without the use of fill or map. Doing `x=>[...Array(x).keys()]` will return an array of range 0 to x. If you want to define your own range/values, use `x=>[...Array(x)].map((a,i)=>i)`, as it's just a few bytes longer.
> 4 votes

# Answer
# JavaScript (ES6) 76

```
f=n=>Array(1<<n).fill().map((_,x)=>/01/.test(x.toString(2))?x+',':'').join``

//TEST
for(i=1;i<16;i++)O.innerHTML+=i+' -> '+f(i)+'\n'
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# K5, 19 bytes

This operates along similar principles as Dennis' solution, but with fewer builtins to take advantage of.

```
{&2<+/'~0=':'+!x#2}

```

First, generate a series of binary x-tuples (`+!x#2`), then for each tuple find every point that a digit does not match the previous if we treat the -1st element of the list as 0 for this purpose (`~0=':'`). Our solutions are where two is less than the sum of each run count. (`&2<+/'`).

Showing each intermediate step is clearer:

```
  4#2
2 2 2 2

  !4#2
(0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1)

  +!4#2
(0 0 0 0
 0 0 0 1
 0 0 1 0
 0 0 1 1
 0 1 0 0
 0 1 0 1
 0 1 1 0
 0 1 1 1
 1 0 0 0
 1 0 0 1
 1 0 1 0
 1 0 1 1
 1 1 0 0
 1 1 0 1
 1 1 1 0
 1 1 1 1)

  ~0=':'+!4#2
(0 0 0 0
 0 0 0 1
 0 0 1 1
 0 0 1 0
 0 1 1 0
 0 1 1 1
 0 1 0 1
 0 1 0 0
 1 1 0 0
 1 1 0 1
 1 1 1 1
 1 1 1 0
 1 0 1 0
 1 0 1 1
 1 0 0 1
 1 0 0 0)

  +/'~0=':'+!4#2
0 1 2 1 2 3 2 1 2 3 4 3 2 3 2 1

  2<+/'~0=':'+!4#2
0 0 0 0 0 1 0 0 0 1 1 1 0 1 0 0

  &2<+/'~0=':'+!4#2
5 9 10 11 13

```

And all together:

```
  {&2<+/'~0=':'+!x#2}'3 4 5
(,5
 5 9 10 11 13
 5 9 10 11 13 17 18 19 20 21 22 23 25 26 27 29)

```
> 3 votes

# Answer
## C++, ~~197~~ ~~188~~ 141 bytes

Note: this was written and tested using MSVC++ 2013. It appears that `#include`ing `<iostream>` includes all of the necessary C headers to make this work. It also appears that the code is no longer truly C++, but compiling using C++ allows that header trick which reduces the code size compared to including a bunch more C headers.

Using `printf` instead of `cout` also saves a couple bytes.

Golfed:

```
#include<iostream>
int main(int a,char**b){char c[34];for(long i=5;i<1L<<atol(b[1]);++i){_ltoa(i,c,2);if(strstr(c,"01"))printf("%ld\n",i);}}

```

Ungolfed:

```
#include <iostream>
int main(int a, char **b) {
  char c[34];
  for (long i = 5; i < 1L << atol(b[1]); ++i) {
    _ltoa(i, c, 2);
    if (strstr(c, "01"))
      printf("%ld\n", i);
  }
}

```
> 2 votes

# Answer
## Perl 5, ~~55~~ ~~53~~ ~~49~~ ~~47~~ 41 bytes

```
sprintf("%b",$_)=~/01/&&say for 0..2**<>

```

~~54~~ ~~52~~ ~~48~~ ~~46~~ 40 bytes, plus one for the `-E` flag instead of `-e`.

---

Thanks to xnor for the hint about using `/01/` instead of `/10+1/`, which saved two bytes.

Thanks to Dennis for the advice to use `<>` instead of `$ARGV[0]`, which saved six bytes.
> 2 votes

# Answer
# Pip, 13 + 1 = 14 bytes

Takes input from the command line and uses the `-s` flag for spaces between output numbers.

```
01NTB_FI,2**a

```

Pretty straightforward: build `range(2**a)` and filter on `lambda _: "01" in toBinary(_)`. I was pretty happy about thinking up the `01` idea independently. No quotes are needed around `01` because it scans as a numeric literal (numbers and strings are the same type in Pip).
> 2 votes

# Answer
# Julia, 40 bytes

```
n->filter(i->count_ones(i$i>>1)>2,1:2^n)

```

This uses a somewhat different approach to the other Julia solution - rather than doing a string search for "01" in the bit string, it uses some mathematics to determine whether the number satisfies the condition.

`i$i>>1` will have ones only in the places where the digit changes from zero to one, or one to zero. As such, there must be at least three ones for `i` to switch back and forth between zero and one enough times. `count_ones` finds the number of ones, and then `filter` removes the ones that don't have enough ones.
> 2 votes

# Answer
**C, ~~84~~ 81 bytes**

```
long i,j,k;main(){for(scanf("%ld",&j);++i<1L<<j;k&k+1&&printf("%ld ",i))k=i|i-1;}

```

This is based on the comments I made on another C answer to this question about the possibility of using simple bitwise operators. It works by switching all trailing 0 bits to 1 in the statement i|(i-1). Then it switches all trailing 1 bits to 0 using k&(k+1). This will result in a zero if there is only one run of ones and non-zero otherwise. I do make the assumption that long is 64-bit but could correct this at the expense of three bytes by using int64\_t instead.

Ungolfed

```
long i,j,k;
main()
{
    for(scanf("%ld",&j);++i<1L<<j;)
    {
        k=i|(i-1);
        if((k&(k+1)) == 0)
            printf("%d ",i);
    }
}

```
> 2 votes

# Answer
# Python 2.7, 89 bytes

```
print[i for i in range(1,2**input())if[n[:1]for n in bin(i)[2:].split("0")].count("1")-1]

```

I think this could be golfed a bit.
> 1 votes

# Answer
# Pyth, ~~20~~ ~~17~~ 16 bytes

```
f:.BT"10+1"ZU^2Q

```

Live demo.
> 1 votes

# Answer
# TI-BASIC, ~~34~~ ~~32~~ 30 bytes

For a TI-83+/84+ series calculator.

```
For(X,5,e^(Ans
If log(sum(2=int(4fPart(X/2^randIntNoRep(1,Ans
Disp X
End

```

For a number to contain two runs of 1s, it must contain two `10`s when we tack a trailing zero onto the binary representation.

Rather than generate the binary representation and check for a `10`, we test pairs of bits mathematically by using remainder by 4 (`int(4fPart(`), which will give `2` where there is a `10`. Because we don't care about order, `randIntNoRep(` is the shortest way to generate the list of exponents.

We use `log(` to check for the number of runs:

* If there are at least 2 runs, then the `log(` is positive, and the number is displayed.
* If there is one run, then the `log(` is 0, and the number is not displayed.
* If there are no runs (which first happens at X=2^Ans), then `log(` throws an ERR:DOMAIN, stopping the output at exactly the right point.

We use `e^(Ans` as the ending argument of the `For(` loop—it's always greater than `2^Ans`, but `e^(` is a single token, so it's one byte shorter.

Input/output for N=4:

```
4:prgmRUNSONES
               5
               9
              10
              11
              13

```

Then the calculator throws an error; the error screen looks like this:

```
ERR:DOMAIN
1:Quit
2:Goto

```

When 1 is pressed, the home screen is displayed again:

```
4:prgmRUNSONES
               5
               9
              10
              11
              13
           Error

```

TI calculators store all numbers in a BCD float with 14 digits of precision, not an int or binary float. Therefore, divisions by powers of two greater than `2^14` may not be exact. While I have verified that the trickiest numbers, `3*2^30-1` and `2^32-1`, are handled correctly, I have not ruled out the possibility of rounding errors. I would however be surprised if there were errors for any input.
> 1 votes

# Answer
* this doesnt beat flawr's answer but i couldnt resist the charm of the question

## matlab~~(90)~~(70)

```
j=input('');for l=2:j-1,a=1;for k=l:-1:2,a=a+2^k;a:a+2^(k-1)-2,end,end

```

## execution

`4`

ans =

```
5

```

ans =

```
9    10    11

```

ans =

```
13

```

## principle

* The series of numbers are a result of consequent strip of 1's, which does mean f(n,l)=2^l+2^(l+1)+....2^n

Any number taken from the interval \]f(n,l),f(n,l)+2^(l-1)\[ where l\>1 verifies this condition, so the outcome is a result of the negation of this series in terms of n.

x=1

x=x+1=`01`,

x=x+2^0=`11`,

x=x+1=`001`,

x=x+2^1=`011`,

x=x+2^0=`111`,

x=x+1=`0001`,

x=x+2^2=`0011`,

x=x+2^1=`0111`,

x=x+2^0=`0111`,

x=x+1=`1111` ...

x+1, x=x+2^n, x=x+2^(n-1)...x=x+2^0

My program prints the range between each two lines (if exists)

---

> **Edit:** unfortunately that doesnt make it golfed more but i wanted to add another approach of proceding this idea

after a period of struggle i succeded to find a mathematical representation for this series which is:

2^l(0+1+2^1+...2^k) with l+k \< n

=2^l(2^k-1)

**score=90**

```
@(n)setdiff(0:2^n-1,arrayfun(@(x)2^mod(x,(n+1)-fix(x/(n+1)))*(2^fix(x/(n+1))-1),0:(n+1)^2))

```
> 1 votes

# Answer
# C, ~~103~~ 102 bytes

```
long i,x;main(int a,char**b){for(;++i<1L<<atoi(b[1]);)for(x=i;x>4&&(x%4!=1||!printf("%ld,",i));x/=2);}

```

Expanding (actually contracting) on G.Sliepen entry, taking advantage of xnor remark on the `01` pattern in the binary representation, but using only standard functions and some bit twiddling.

Ungolfed version:

```
long i, x;
main(int a, char**b) {
    for (; ++i < 1L << atoi(b[1]);) {
        for (x = i; x > 4 && (x % 4 != 1 || !printf("%ld,", i)); x /= 2)
            ;
    }
}

```

The inner loop scans `i` for the binary pattern `01` by iteratively shifting `x` to the right as long as it has 3 bits left. `printf` returns the number of characters printed, hence never `0`, so the inner loop test fails after the `printf`, avoiding the need for a `break` statement.

# C++, ~~129~~ 128 bytes

Adapting the same idea, the C++ variant is here:

```
#include<iostream>
long i,x;int main(int a,char**b){for(;++i<1L<<atoi(b[1]);)for(x=i;x>4&&(x%4!=1||!(std::cout<<i<<','));x/=2);}

```

Technically, I should make `i` a `long long` to ensure 64 bit operation and compute upto `2^32` for an extra 5 bytes, but modern platforms have 64 bit ints.
> 1 votes

# Answer
# JavaScript ES6, 60 bytes

## Code

```
n=>[...Array(1<<n).keys()].filter(g=x=>x>4?x%4==1|g(x>>1):0)

```

Try it online!

## Explanation

```
[...Array(1<<n).keys()]                                          Create an array of numbers from 0 to 2^n-1
                       .filter(                                  Find the numbers which meet criteria
                               g=x=>x>4?                  :0     If x is less than or equal to four return zero (false/invalid)
                                        x>4?x%4==1|              If the binary pattern ends with 01 return one (true/valid)
                                                   g(x>>1)       Otherwise bitshift right by one and try again

```
> 1 votes

# Answer
# C 99

**Thanks to @ceilingcat for making it much shorter**

```
x,c;main(n,v){for(n--;c<1<<n;c++)for(v=0;v<32&&!(c&1<<v&&x&&x<v&&printf("%d ",c));)x=c&1<<v++?v:x;}

```

Try it online!
> 0 votes

# Answer
# PowerShell, 80 bytes

```
while([Math]::Pow(2,$args[0])-gt$n++){$n|?{[Convert]::ToString($n,2)-match"01"}}

```
> 0 votes

# Answer
# Python, 44 Bytes

Okay, this could probably be shorter but it's my first codegolf:

```
x=1
while True:
    if '01' in bin(x):
        print(x)
    x+=1

```

Think this answers the question, please don't down vote if it doesn't, just post whats wrong with it below.
> 0 votes

# Answer
another different matlab answer of good score.

## matlab ~~60~~(57)

```
@(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1))

```

## execution

```
>> @(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1))

```

`ans =`

```
@(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1))

```

`>> ans(5)`

`ans =`

```
 5     9    10    11    13    17    18    19    20    21    22    23    25    26    27    29

```

---

* ***The idea*** is picking up numbers x where the binary representation of -(x)+1 doesnt contain only one occurence of `1`

example:

`0000111` is rejected because ~x=`1111`,~x+1=`00001` contains one digit=1

`0100111` is accepted because ~x=`1011`,~x+1=`0111` contains many 1's
> 0 votes

# Answer
# k4, ~~32~~ 28 bytes

```
{&1<+/'1='-':'0b\:'o:!*/x#2}

```

---

explanation

```
                      */x#2   /x^2
                   o:!        /assign o to [0,x^2 -1), e.g. for x=2, o<-0 1 2 3
              0b\:'           /get binary value of each array elem
          -':'                /get delta of adjacent digits in each binary num
    +/'1='                    /sum each array to find how many deltas=1
 &1<                          /return elems where there were greater than 1 deltas=1

```
> 0 votes

# Answer
# Jelly, 10 bytes

```
2*’BŒgṫɗƇ3

```

Try it online!

Translated from Dennis' Pyth solution.

```
        Ƈ     Filter the range from 1 to
2*’           2^input - 1
   B   ɗ      for elements the binary representations of which,
    Œg        when split into runs,
      ṫ  3    are nonempty with their first 2 elements removed.

```
> 0 votes

# Answer
# Thunno 2, 7 bytes

```
OLæḃkdƇ

```

Try it online!

#### Explanation

```
OLæḃkdƇ  # Implicit input
OLæ      # Filter range(2**input) by:
   ḃkdƇ  #  Binary contains "01"?
         # Implicit output

```
> 0 votes

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


# Question
Title: Convert Salesforce 15-character ID to 18-character
In Salesforce CRM, every object has 15-character alphanumeric ID, which is case-sensitive. If anyone's curious, actually it's base-62 number. However, tools used for data migration and integration may or may not support case sensitivity. To overcome that, IDs can be safely converted to 18-character case-insensitive alphanumeric IDs. In that process 3-character alphanumeric checksum is appended to the ID. The conversion algorithm is:

**Example**:

```
a0RE000000IJmcN

```
1. Split ID into three 5-character chunks.

```
a0RE0  00000  IJmcN

```
2. Reverse each chunk.

```
0ER0a  00000  NcmJI

```
3. Replace each character in every chunk by `1` if it's uppercase or by `0` if otherwise.

```
01100  00000  10011

```
4. For each 5-digit binary number `i`, get character at position `i` in concatenation of uppercase alphabet and digits 0-5 (`ABCDEFGHIJKLMNOPQRSTUVWXYZ012345`).

```
00000 -> A,
00001 -> B,
00010 -> C, ...,
11010 -> Z,
11011 -> 0, ...,
11111 -> 5`

```

Yielding:

```
M  A  T

```
5. Append these characters, the checksum, to the original ID.

**Output**:

```
a0RE000000IJmcNMAT

```

Write program or function which takes 15-character alphanumeric (ASCII) string as input and returns 18-character ID.

Input validation is out of scope of this question. Programs may return any value or crash on invalid input.

Please, don't use Salesforce propretiary languages' features that make this challenge trivial (such as formula `CASESAFEID()`, converting `Id` to `String` in APEX &c).

### Test Cases

```
a01M00000062mPg    -> a01M00000062mPgIAI
001M000000qfPyS    -> 001M000000qfPySIAU
a0FE000000D6r3F    -> a0FE000000D6r3FMAR
0F9E000000092w2    -> 0F9E000000092w2KAA
aaaaaaaaaaaaaaa    -> aaaaaaaaaaaaaaaAAA
AbCdEfGhIjKlMnO    -> AbCdEfGhIjKlMnOVKV
aBcDEfgHIJKLMNO    -> aBcDEfgHIJKLMNO025

```

# Answer
# Pyth, ~~23~~ 22 bytes

*1 byte saved by FryAmTheEggman.*

```
sm@s+JrG1U6i}RJ_d2c3pz

```

Try it online. Test suite.

This might be the first time I've used the `p`rint instruction in golfing.

### Explanation

```
     JrG1                   save uppercase alphabet in J
                     z      input string
                    p       print it without newline
                  c3        split into 3 parts
 m              d           for each part:
               _              reverse
            }R                map characters to being in
              J                 uppercase alphabet (saved in J)
           i     2            parse list of bools as binary
  @                           get correct item of
     J                          uppercase alphabet (saved in J)
   s+    U6                     add nums 0-5 to it
s                           concatenate and print

```
> 8 votes

# Answer
## Ruby, 97 bytes

```
->s{s+s.scan(/.{5}/).map{|x|[*?A..?Z,*?0..?5][x.reverse.gsub(/./){|y|y=~/[^A-Z]/||1}.to_i 2]}*''}

```

```
->s{               # define an anonymous lambda
s+                 # the original string plus...
s.scan(/.{5}/)     # get every group of 5 chars
.map{|x|           # map over each group of 5 chars...
[*?A..?Z,*?0..?5]  # build the array of A-Z0-5
[                  # index over it with...
x.reverse          # the 5-char group, reversed...
.gsub(/./){|y|     # ... with each character replaced with...
y=~/[^A-Z]/||1     # ... whether it's uppercase (0/1)...
}.to_i 2           # ... converted to binary
]                  # (end index)
}*''               # end map, join into a string
}                  # end lambda

```

This one's got some really neat tricks.

My original instinct for splitting the string into groups of 5 chars was `each_slice`:

```
irb(main):001:0> [*1..20].each_slice(5).to_a
=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]

```

Turns out that's waaay too long compared to a simple regex (`x.chars.each_slice(5)` vs. `x.scan(/.{5}/)`). This seems obvious in hindsight, but I never really thought about it... perhaps I can optimize some of my old Ruby answers here.

The thing I'm most proud of in this answer, though, is this piece of code:

```
y=~/[^A-Z]/||1

```

Alright, so here's some background for the non-Rubyists. Ruby completely separates booleans (`TrueClass`, `FalseClass`) from integers/numbers (`Numeric`)—that means there's no automatic conversion from true to 1 and false to 0 either. This is annoying while golfing (but a good thing... for all other purposes).

The naïve approach to checking whether a single character is uppercase (and returning 1 or 0) is

```
y.upcase==y?1:0

```

We can get this down a little further (again, with a regex):

```
y=~/[A-Z]/?1:0

```

But then I really started thinking. Hmm... `=~` returns the index of a match (so, for our single character, always `0` if there's a match) or `nil` on failure to match, a falsy value (everything else except `FalseClass` is truthy in Ruby). The `||` operator takes its first operand if it's truthy, and its second operand otherwise. Therefore, we can golf this down to

```
y=~/[^A-Z]/||1

```

Alright, let's look at what's happening here. If `y` is an uppercase letter, it will fail to match `[^A-Z]`, so the regex part will return `nil`. `nil || 1` is `1`, so uppercase letters become `1`. If `y` is anything but an uppercase letter, the regex part will return `0` (because there's a match at index `0`), and since `0` is truthy, `0 || 1` is `0`.

... and only after writing all of this out do I realize that this is actually the same length as `y=~/[A-Z]/?1:0`. Haha, oh well.
> 7 votes

# Answer
# MATL, 24 bytes

```
j1Y24Y2hG5IePtk=~!XB1+)h

```

Uses current version (9.1.0) of the language/compiler.

### Examples

```
>> matl
 > j1Y24Y2hG5IePtk=~!XB1+)h
 >
> a0RE000000IJmcN
a0RE000000IJmcNMAT

>> matl
 > j1Y24Y2hG5IePtk=~!XB1+)h
 >
> a01M00000062mPg
a01M00000062mPgIAI

```

### Explanation

```
j            % input string
1Y2          % predefined literal: 'ABC...Z'
4Y2          % predefined literal; '012...9'
h            % concatenate into string 'ABC...Z012...9'
G            % push input string
5Ie          % reshape into 5x3 matrix, column-major order
P            % flip vertically
tk=~         % 1 if uppercase, 0 if lowercase
!XB1+        % convert each column to binary number and add 1
)            % index 'ABC...Z012...9' with resulting numbers
h            % concatenate result with original string

```
> 4 votes

# Answer
# JavaScript (ES6), 108

```
x=>x.replace(/[A-Z]/g,(x,i)=>t|=1<<i,t=0)+[0,5,10].map(n=>x+='ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'[t>>n&31])&&x

```

**Test**

```
f=x=>x.replace(/[A-Z]/g,(x,i)=>t|=1<<i,t=0)+[0,5,10].map(n=>x+='ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'[t>>n&31])&&x

// Less golfed

U=x=>{
  x.replace(/[A-Z]/g,(x,i)=>t|=1<<i,t=0); // build a 15 bit number (no need to explicit reverse)
  // convert 't' to 3 number of 5 bits each, then to the right char A..Z 0..5
  [0,5,10].forEach(n=> // 3 value for shifting
    x += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345' // to convert value to char
     [ t>>n&31 ] // shift and mask
  );
  return x
}

console.log=x=>O.innerHTML+=x+'\n';

;[
  ['a01M00000062mPg','a01M00000062mPgIAI']
, ['001M000000qfPyS','001M000000qfPySIAU']
, ['a0FE000000D6r3F','a0FE000000D6r3FMAR']
, ['0F9E000000092w2','0F9E000000092w2KAA']
, ['aaaaaaaaaaaaaaa','aaaaaaaaaaaaaaaAAA']
, ['AbCdEfGhIjKlMnO','AbCdEfGhIjKlMnOVKV']
, ['aBcDEfgHIJKLMNO','aBcDEfgHIJKLMNO025']
].forEach(t=>{
  var i=t[0],x=t[1],r=f(i);
  console.log(i+'->'+r+(r==x?' OK':' Fail (expected '+x+')'));
})
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# JavaScript (ES6), ~~137~~ 132 bytes

```
s=>s+s.replace(/./g,c=>c>"9"&c<"a").match(/.{5}/g).map(n=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"[0|"0b"+[...n].reverse().join``]).join``

```

*4 bytes saved thanks to @ՊՓԼՃՐՊՃՈԲՍԼ!*

## Explanation

This challenge is not suited for JavaScript at all. There's no short way to reverse a string and it looks like the shortest way to convert the number to a character is to hard-code each possible character.

```
s=>
  s+                                   // prepend the original ID
  s.replace(/./g,c=>c>"9"&c<"a")       // convert each upper-case character to 1
  .match(/.{5}/g).map(n=>              // for each group of 5 digits
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
    [0|"0b"+                            // convert from binary
      [...n].reverse().join``]          // reverse the string
  ).join``

```

If the digits in the checksum were allowed to be lower-case it could be done in 124 bytes like this:

```
s=>s+s.replace(/./g,c=>c>"9"&c<"a").match(/.{5}/g).map(n=>((parseInt([...n].reverse().join``,2)+10)%36).toString(36)).join``

```

## Test

```
var solution = s=>s+s.replace(/./g,c=>c>"9"&c<"a").match(/.{5}/g).map(n=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"[0|"0b"+[...n].reverse().join``]).join``
```

```
<input type="text" id="input" value="AbCdEfGhIjKlMnO" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 2 votes

# Answer
## MATLAB, 100 98 bytes

```
s=input('');a=flip(reshape(s,5,3))';e=['A':'Z',48:53];disp([s,e(bin2dec(num2str(a~=lower(a)))+1)])

```

A string will be requested as input and the output will be displayed on the screen.

## Explanation

I'm probably using the most straight-forward approach here:

* Request input
* Reshape to 5 (rows) x 3 (columns)
* Flip the row order
* Transpose the matrix to prepare it for being read as binary
* Allocate the ABC...XYZ012345 array
* Compare the character indices of the transposed matrix to its lower-case equivalent and convert the booleans to strings, which are then read as binary and converted to decimal.
* Interpret these decimals (incremented by 1) as indices of the allocated array.
* Display the input with the additional 3 characters

Now below 100 bytes thanks to Luis Mendo!
> 2 votes

# Answer
## CJam, 27 bytes

```
l_5/{W%{_el=!}%2bH+43%'0+}%

```

Run all test cases.

A fairly straightforward implementation of the spec. The most interesting part is the conversion to characters in the checksum. We add 17 to the result of each chunk. Take that modulo 43 and add the result of that to the character `'0`.
> 2 votes

# Answer
# C, ~~120~~ 118 bytes

```
n,j;main(c,v,s)char**v,*s;{for(printf(s=v[1]);*s;s+=5){for(n=0,j=5;j--;)n=n*2+!!isupper(s[j]);putchar(n+65-n/26*17);}}

```

Works for any input whose length is a multiple of 5 :)

## Ungolfed

```
n,j;

main(c,v,s) char **v, *s;
{
    for(printf(s = v[1]); *s; s+=5)
    {
        for(n=0, j=5; j--;)
            n=n*2+!!isupper(s[j]);

        putchar(n+65-n/26*17);
    }
}

```
> 2 votes

# Answer
# Japt, 46 bytes

```
U+U®f"[A-Z]" ?1:0} f'.p5)®w n2 +A %36 s36 u} q

```

Not too happy with the length, but I can't find a way to golf it down. Try it online!
> 2 votes

# Answer
## PHP, ~~186~~ 181 bytes

```
<?$z=$argv[1];$x=str_split($z,5);$l="ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";foreach($x as$y){foreach(str_split(strrev($y))as$a=>$w)$y[$a]=ctype_upper($w)?1:0;$z.=$l[bindec($y)];}echo $z;

```

## Unglofed

```
<?php
$z = $argv[1];
$x = str_split($z,5);
$l = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
foreach($x as $y) {
    foreach( str_split( strrev($y) ) as $a => $w) {
        $y[$a] = ctype_upper($w) ? 1 : 0;
    }
    $z .= $l[bindec($y)];
}
echo $z;

```

I started out thinking I could make it much shorter than this, but I ran out of ideas to make it shorter.
> 2 votes

# Answer
# Japt, 21 bytes

```
;+ò5 ®Ô£BèXÃÍgB¬c6oÃ¬

```

Try it (includes all test cases)

```
;+ò5 ®Ô£BèXÃÍgB¬c6oÃ¬     :Implicit input of string
 +                        :Append
  ò5                      :Partitions of length 5
     ®                    :Map
      Ô                   :   Reverse
       £                  :   Map each X
;       B                 :     Uppercase alphabet
         èX               :     Count occurrences of X
           Ã              :  End map
            Í             :  Convert from binary string to integer
             g            :  Index into
;             B           :    Uppercase alphabet
               ¬          :    Split
                c         :    Concatenate
                 6o       :    Range [0,6)
                   Ã      :End map
                    ¬     :Join

```
> 2 votes

# Answer
# Jelly, 19 18 17 bytes

```
Ȯe€ØAs5UḄ‘ịØA;ØD¤

```

Try it online!

## Explanation

```
Ȯe€ØAs5UḄ‘ịØA;ØD¤   Main monadic link
Ȯ                   Print (without newline)
  €                 Map:
 e                   is element of
   ØA                 the uppercase alphabet
     s              Split into chunks of
      5              five
       U            Reverse [each]
        Ḅ           Convert [each] from binary
         ‘          Add 1 [to each]
          ị         Lookup [each] by 1-based index in
                ¤   (
           ØA        the uppercase alphabet
             ;       join with
              ØD     digits 0-9
                ¤   )

```

*-1 byte by inspiration from ovs' O5AB1E answer, printing the initial string directly instead of joining it at the end*

*-1 byts because I'm a dumb and didn't realize that `U` vectorizes*
> 2 votes

# Answer
## Perl, 80 bytes

```
$_.=join"",map{(A..Z,0..5)[oct"0b".join"",map{lc cmp$_}split//,reverse]}/.{5}/g

```

To be run as:

```
perl -ple '$_.=join"",map{(A..Z,0..5)[oct"0b".join"",map{lc cmp$_}split//,reverse]}/.{5}/g'

```

Pretty straightforward except `lc cmp $_` and `oct "0b" . $str` for binary conversion.
> 2 votes

# Answer
# Vyxal, ~~18~~ 17 bytes

```
ƛꜝ;5ẇRvBkAkd+$İṅ+

```

Try it Online!

My first attempt at golfing in Vyxal.

## Explanation

```
ƛꜝ;5ẇRvBkAkd+$İṅ+
ƛ ;                 Map
 ꜝ                    Is uppercase?
   5ẇ               Split into chunks of 5
     R              Reverse each
      v             Vectorize
       B              Convert from binary
        kAkd+       Push uppercase letters joined with digits
             $      Swap
              İ     Index
               ṅ    Join into a string
                +   Append to the original string

```
> 2 votes

# Answer
## Python 2, 97 bytes

```
lambda i:i+''.join(chr(48+(17+sum((2**j)*i[x+j].isupper()for j in range(5)))%43)for x in[0,5,10])

```
> 1 votes

# Answer
## PowerShell, 162 bytes

```
function f{param($f)-join([char[]](65..90)+(0..5))[[convert]::ToInt32(-join($f|%{+($_-cmatch'[A-Z]')}),2)]}
($a=$args[0])+(f $a[4..0])+(f $a[9..5])+(f $a[14..10])

```

OK, a lot of neat stuff happening in this one. I'll start with the second line.

We take input as a string via `$args[0]` and set it to `$a` for use later. This is encapsulated in `()` so it's executed and the result returned (i.e., `$a`) so we can immediately string-concatenate it with the results of three function calls `(f ...)`. Each function call passes as an argument the input string indexed in reverse order chunks as a char-array -- meaning, for the example input, `$a[4..0]` will equal `@('0','E','R','0','a')` with each entry as a char, not a string.

Now to the function, where the real meat of the program is. We take input as `$f`, but it's only used way toward the end, so let's focus there, first. Since it's passed as a char-array (thanks to our previous indexing), we can immediately pipe it into a loop with `$f|%{...}`. Inside the loop, we take each character and perform a case-sensitive regex match with `-cmatch` which will result in true/false if it's uppercase/otherwise. We cast that as an integer with the encapsulating `+()`, then that array of 1's and 0's is `-join`ed to form a string. *That* is then passed as the first parameter in the .NET `[convert]::ToInt32()` call to change the binary (base `2`) into decimal. We use that resultant decimal number to index into a string (`-join(...)[...]`). The string is first formulated as a range `(65..90)` that's cast as a char-array, then concatenated with the range `(0..5)` (i.e., the string is `"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"`). All of that is to return the appropriate character from the string.
> 1 votes

# Answer
## C# 334

```
string g(string c){string[]b=new string[]{c.Substring(0,5),c.Substring(5, 5),c.Substring(10)};string o="",w="";for(int i=0,j=0;i<3;i++){char[]t=b[i].ToCharArray();Array.Reverse(t);b[i]=new string(t);o="";for(j=0;j<5;j++){o+=Char.IsUpper(b[i][j])?1:0;}int R=Convert.ToInt32(o,2);char U=R>26?(char)(R+22):(char)(R+65);w+=U;}return c+w;}

```

If requested, I'll reverse my code back to readable and post it.
> 1 votes

# Answer
# C#, 171 bytes

I'm not really well-practiced in golfing C#, but here's a shot.

```
s=>{for(var u=s;u.Length>0;u=u.Substring(5)){int p=0,n=u.Substring(0,5).Select(t=>char.IsUpper(t)?1:0).Sum(i=>(int)(i*Math.Pow(2,p++)));s+=(char)(n+65-n/26*17);}return s;}

```
> 1 votes

# Answer
# Jolf, 30 bytes

Finally, a probably still-jolfable! Try it here!

```
+i mZci5d.p1CρA_Hpu1"[^1]'0"2
    Zci5                      split input into groups of 5
  _m                          map it
        d                      with this function
               _H              reverse H
              A  pu1            and replace in it all uppercase letters with 1
             ρ      "[^1]'0"    replace all non-ones with zeroes
            C               2   parse as binary integer
         .p1                    get the (^)th member of "A...Z0...9"

```
> 1 votes

# Answer
# Python 3, ~~201 174~~ 138 bytes

Big thanks to Trang Oul for pointing out a function declaration that no longer needed to exist. And Python ternary operators. And some incorrect output. Just...just give him the upvotes.

```
i=input();n='';c=l=15;
while c:c-=1;n+=('0','1')[i[c].isupper()]
while l:v=int(n[l-5:l],2);l-=5;i+=(chr(v+65),str(v-26))[v>25]
print(i)

```
> 1 votes

# Answer
# J, 36 bytes

```
,_5(u:@+22+43*<&26)@#.@|.\]~:tolower

```

Usage:

```
   (,_5(u:@+22+43*<&26)@#.@|.\]~:tolower) 'a0RE000000IJmcN'
a0RE000000IJmcNMAT

```

Try it online here.
> 1 votes

# Answer
# Python 3, 87 bytes

```
lambda s:s+bytes(48+(17+sum((~s[i+j]&32)>>(5-i)for i in range(5)))%43 for j in(0,5,10))

```
> 1 votes

# Answer
# Husk, 26 bytes

```
S+öm!+…'A'Zṁsŀ6mȯ→ḋ↔†o±DC5

```

Try it online!

Getting the alphabets takes a lot of bytes. Otherwise, I think this qould be at par with the other languages.
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
?5ôvžKuÙyR€.uJCè?

```

Try it online!

**Commented**:

```
?                 # print the input
 5ô               # split into groups of 5
   ε              # iterate over the groups:
    žK            #   push [a-zA-Z0-9]
      u           #   convert to uppercase
       Ù          #   deduplicate: [A-Z0-9]
        y         #   push the group
         R        #   reverse it
          €       #   for each char:
           .u     #     is it uppercase?
             J    #   join into a binary string
              C   #   convert from binary
               è  #   index into the string
                ? #   print the char at index

```
> 1 votes

# Answer
# Raku, 63 bytes

```
{$_~S:g[((<:Lu>)||.)**5]=flat('A'..'Z',^6)[:2[?«$0[4…0;0]]]}

```

Try it online!

* `$_` is the single argument to this function, the Salesforce ID.
* `$_ ~ S:g[regex] = expr` concatenates `$_` with the result of globally replacing the regular expression `regex` with `expr`.
* `<:Lu>` matches any uppercase letter. `(<:Lu>) || .` matches an uppercase letter or any other character. An uppercase letter will be stored in a capture group; other characters won't.
* `((<:Lu>) || .) ** 5` matches five such alternates. `$0` is the capture group for the outermost group. Since it is repeated, it will be a list of match objects. Each such match object will contain a capture group match object only if it's an uppercase letter.
* As for the replacement text, `flat('A'..'Z', ^6)` evaluates to a list of all uppercase letters followed by the numbers zero through five. The following bracketed expression is an index into that list, providing the replacement character for each set of five ID characters.
* `$0` is a list of match objects, one per character.
* `$0[4…0;0]` is a list of the submatch objects, in reverse order. For uppercase letters, this is a match object; for other characters, it's `Nil`.
* coerces that list of objects to boolean values. Match objects beome `True`, and `Nil` becomes `False`.
* `:2[...]` combines those binary/boolean digits into a number.
> 1 votes

# Answer
# K (ngn/k), ~~41~~ 37 bytes

```
{x,,/[`c$65+!26;$!6]@2/|+3 5#~"A["'x}

```

Try it online!

* `~"A["'x` generate a bit mask indicating which values of `x` (the input) are uppercase letters
* `|+3 5#` chunk the input into five-length sections, transposing them and reversing the result to set up for...
* `2/` converting each column from a list of base-two values to a single base-ten number
* `,/[`c$65+!26;$!6]@` generate `"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"` and index into it with the above
* `x,` append the checksum to the input (and implicitly return)
> 1 votes

# Answer
# BQN, 40 bytes<sup>SBCS</sup>

```
{∾(u∾u-17)⊏˜2⊸×⊸+˜´¨(5/↕3)⊔∊u←'A'+↕26}

```

Run online!

Or 31 bytes in dzaima/BQN:

```
{∾(2⊸×⊸+˜´¨(5/↕3)⊔∊•a)⊏•a∾•d}

```
> 1 votes

# Answer
Dyalog APL, 23 bytes

```
{⍵,⎕A[1+2⊥⍉⎕A∊⍨⌽3 5⍴⍵]}

```

This is a straightforward mapping of the problem statement.

```
3 5⍴⍵ ⍝ Reshape the vector into a matrix of
      ⍝ 3 rows by 5 columns.
⌽     ⍝ Reverse the rows.
⎕A∊⍨  ⍝ For each element, check whether they
      ⍝ are a member(∊) of the uppercase
      ⍝ alphabet, ⎕A.
2⊥⍉   ⍝ Decode, ⊥, the columns as a base 2
      ⍝ number. The transpose, ⍉, is so the
      ⍝ rows becomes the columns. The result
      ⍝ is a three element vector.
1+    ⍝ Add one to each element so that they
      ⍝ map to the indexes of the letters on
      ⍝ the alphabet. This is because arrays
      ⍝ in APL are 1 indexed by default.
⎕A[]  ⍝ Maps the indexes to their
      ⍝ corresponding uppercase letter.
⍵,    ⍝ Finally concatenate the original
      ⍝ vector with the result.

```
> 1 votes

# Answer
# Canvas, 31 bytes

```
５ｎ｛±｛┐Ｚ｛²≡］∑］２┴╵（Ｚ◂［］６＠）∑＠］⤢╶；＋

```

Try it here!
> 0 votes

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

```
map{y/A-Z/0/c;y/A-Z/1/;$\.=(A..Z,0..5)[oct"0b".reverse]}/.{5}/g

```

Try it online!
> 0 votes

# Answer
# Nibbles, 19 bytes (37 nibbles)

```
@   # The input
.   # Map
  `/ 5 @   # Split the input into chunks of 5
  =   # Index
    +   # Add
      `@2   # Convert from binary
        .   # Map
          \ $   # Reverse the argument of the outer map
          ,\ $ u   # Is the argument an uppercase letter?
      ~   # 1
    :   # Join
      + '@' ,26   # The uppercase alphabet
      +   # Concatenate
        .   # Map
          `, ~   # Numbers from 0
          `p   # Convert number to string

```
> 0 votes

# Answer
# Stax, ~~16~~ 15 bytes

```
ë"Y╚∙╘.b¢┘⌠:-\∩

```

Run and debug it
> 0 votes

# Answer
# Thunno 2 `j`, 14 bytes

```
⁵ırfḅ2ḋkȦRUi;$

```

Try it online!

#### Explanation

```
⁵ırfḅ2ḋkȦRUi;$  # Implicit input
⁵               # Split into chunks of length 5
 ı          ;   # Map over each chunk:
  r             #  Reverse it
   f            #  Get the case of each character
                #   (1 = uppercase; 0 = lowercase;
                #    -1 = non-alphabetic)
    ḅ           #  Check for each if it equals 1
     2ḋ         #  Convert from a binary list
       kȦ       #  Push [a-zA-Z0-9]
         RU     #  Uppercase and uniquify
           i    #  Index into this string
             $  # Push the input
                # Implicit output of joined stack

```
> 0 votes

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


title: Primes with prime bit-counts

text:
# Question
Title: Primes with prime bit-counts
### Task

> Find all the non-negative integers up to and including a given non-zero positive integer *n*, that are prime and the count of `1's` and `0's` in their binary representation (having no leading zeroes) are prime too.

Here are the first five such primes,

```
17, 19, 37, 41, 79

10001, 10011, 100101, 101001, 1001111

```

### Clarifications and rules

* Default I/O methods are accepted.
* The answer can be a program or a function.
* If there are no such primes then output garbage or nothing.
* Standard loopholes are forbidden.
* `2 3 5 7` did not make it to the list because in their binary representation number of occurrences of `0's` and `1's` are not prime. Consider `7`whose binary representation is `111`, here `0` occurs zero times and zero is not prime.
* Built-ins are allowed.
* The shortest code in bytes wins!

### Test cases

```
10
[]

100
[17, 19, 37, 41, 79]

150
[17, 19, 37, 41, 79, 103, 107, 109, 131, 137]

```

```
/* Configuration */

var QUESTION_ID = 107050; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 47650; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
ÅPʒbTS¢pP

```

Pretty straight-forward.

Try it online or verify all test cases.

**Explanation:**

```
ÅP         # Push a list of all prime numbers below or equal to the (implicit) input
  ʒ        # Filter this list of primes by:
   b       #  Convert it to a binary string
    TS     #  Push 10, and pop and convert it to a list of digits as strings: ["1","0"]
      ¢    #  Count those characters in the binary string
       p   #  Check for both those counts whether they're a prime number
        P  #  Check that this is truthy for both of them
           # (after which the filtered list is output implicitly as result)

```

There seems to be a bug in the count builtin `¢` when using an integer list on a string, so some alternatives to `TS` like `Ð‰`, `0L`, or  doesn't seem to work and result in a pair of the binary string instead, unless we add a `§` (cast to string): Try it online.

# Answer
> 10 votes
# Python 2, ~~106~~ ~~102~~ 100 bytes

```
k=m=1;p={0}
exec"p^={m%k*k,0};c=bin(k).count\nif{k,c('1'),c('0')-1}<p:print k\nm*=k*k;k+=1;"*input()

```

Try it online!

### Background

To identify primes, we use a corollary of Wilson's theorem:

### How it works

We start by initializing **k** and **m** as **1** and **p** as the set **{0}**. Note that **m = 1 = 0!² = (k - 1)!²**. Immediately afterwards, the following code is executed **n** times, where **n** is the integer read from standard input.

```
p^={m%k*k,0};c=bin(k).count
if{k,c('1'),c('0')-1}<p:print k
m*=k*k;k+=1

```

By the corollary, **m % k** will be **1** if **k** is prime and **0** otherwise. Thus, `{m%k*k,0}` will return the set **{k, 0}** if **k** is prime and the set **{0}** otherwise.

If (and only if) **k** is prime, since **p** cannot contain **k** at this point, the in-place symmetric difference `p^={m%k*k,0}` will add **k** to the set **p**. Also, **p** will contain **0** after the update if and only if it does not contain **0** before, so **0 ∊ p** if and only if **k** is even.

On the same line, we define a function **c** via `c=bin(k).count`, which will count the occurrences of its argument in **k**'s binary representation.

The second line produces the actual output. `{k,c('1'),c('0')-1}` returns the set that consists of **k** itself, the number of set bits in **k**, and the number of unset bits in **k**. Since the output of `bin(k)` begins with **0b**, we have to decrement `c('0')` to account for the leading **0**.

If all of them are prime, they will all belong to **p**, which by now contains all prime numbers up to **k** (and potentially **0**). If **k** is a Mersenne number (i.e., if it has only set bits), `c('0')-1` will yield **0**. Since Mersenne numbers are odd, **p** will *not* contain **0**, so the condition will fail.

After (potentially) printing **k**, we multiply **m** by . Since **m = (k-1)!²** before the update, **m = k!²** after it. After incrementing **k**, the relation **m = (k-1)!²** holds again and we're ready for the next iteration.

# Answer
> 9 votes
# Mathematica, ~~80~~ ~~68~~ 54 bytes

```
Select[p=PrimeQ;Range@#,p@#&&And@@p/@#~DigitCount~2&]&

```

**Explanation**

```
Select[p=PrimeQ;Range@#,p@#&&And@@p/@#~DigitCount~2&]&

       p=PrimeQ                                        (* Store prime check func. in p *)
Select[                                             ]  (* Select *)
                Range@#                                (* from a list {1..n} *)
                        p@#                            (* numbers that are prime *)
                           &&                          (* And *)
                                     #~DigitCount~2    (* whose digit counts in binary *)
                             And@@p/@                  (* are prime as well *)

```

# Answer
> 8 votes
# JavaScript (ES6), ~~123~~ ~~118~~ ~~115~~ ~~111~~ ~~104~~ 96 bytes

*Saved 4 bytes thanks to @Arnauld*

```
G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1)
F=n=>F(n-1,G(n,a=[0,0,n])||alert(n))

```

A combination of three typical recursive functions. Alerts the sequence in reverse order and terminates on a "too much recursion" error.

### Test snippet

(modified to output to the page)

```
alert = s => O.textContent += s + "\n"

G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1)
F=n=>F(n-1,G(n,a=[0,0,n])||alert(n))

F(1000)
```

```
<pre id=O></pre>
```

The main function can return an array for 104 bytes:

```
G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1)
F=n=>n?F(n-1).concat(G(n,a=[0,0,n])?[]:n):[]

```

It can also be non-recursive at the cost of another byte:

```
G=n=>n?G(n>>1,++a[n%2]):a.some(n=>(P=x=>n%--x?P(x):x)(n)-1)
n=>[for(_ of Array(n))if(!G(--n,a=[0,0,n]))n]

```

---

Here's the one I started with: *(Saved 6 bytes thanks to @Arnauld)*

```
P=(n,x=n)=>n>1&--x<2||n%x&&P(n,x)
G=n=>n?G(n>>1,o+=n%2,t++):P(o)&P(t-o)
F=n=>n?F(n-1).concat(P(n)&G(n,o=t=0)?n:[]):[]

```

I tried golfing this further and managed to do it in 104 bytes—then realized I had already found that solution (it's at the bottom of the answer). Don't you hate it when that happens? :P

A non-recursive attempt at the main function (again, same byte count):

```
n=>[for(i of Array(n))if(P(--n)&G(n,o=t=0))n]

```

---

This one takes the easy route of counting how many 0's and 1's are in the binary representation:

```
F=n=>n?F(n-1).concat([n,(G=x=>n.toString(2).split(x).length-1)(0),G(1)].some(n=>(P=x=>n%--x?P(x):x)(n)-1)?[]:n):[]

```

Same thing with an array comprehension:

```
n=>[for(_ of Array(n))if(![--n,(G=x=>n.toString(2).split(x).length-1)(0),G(1)].some(n=>(P=x=>n%--x?P(x):x)(n)-1))n]

```

This one takes a slightly harder route to do the same thing:

```
F=n=>n?F(n-1).concat([n,(G=(x,w=n)=>w&&G(x,w>>1)+(w%2==x))(0),G(1)].some(n=>(P=x=>n%--x?P(x):x)(n)-1)?[]:n):[]

```

And this one takes yet another related route that's as short as the original:

```
F=n=>n?F(n-1).concat([n,o=(G=x=>x&&x%2+G(n>>++t))(n,t=0),t-o].some(n=>(P=x=>n%--x?P(x):x)(n)-1)?[]:n):[]

```

Again, you can golf 8 bytes by making it alert the sequence in reverse order:

```
F=n=>F(n-1,[n,o=(G=x=>x&&x%2+G(n>>++t))(n,t=0),t-o].some(n=>(P=x=>n%--x?P(x):x)(n)-1)||alert(n))

```

# Answer
> 6 votes
# Jelly, ~~17~~ 16 bytes

```
BĠL€µ;LÆPẠ
ÆRÇÐf

```

**Try it online!**

### How?

```
BĠL€µ;LÆPẠ - Link 1, hasPrimeBits: n  e.g. 7         or 13
B          - convert to binary        e.g. [1,1,1]  or [1,1,0,1]
 Ġ         - group indices            e.g. [1,2,3]  or [3,[1,2,4]]
  L€       - length of €ach           e.g. 3          or [1,3]
    µ      - monadic chain separation
     ;L    - concatenate length       e.g. [3,1]      or [1,3,2]
           -     this caters for the edge case of Mersenne primes (like 7), which have
           -     no zero bits, the length will be 1, which is not prime.
       ÆP  - isPrime?                 e.g. [1,0]      or [0,1,1]
         Ạ - All?                     e.g. 0          or 0

ÆRÇÐf - Main link: N
ÆR    - prime range (primes up to and including N)
   Ðf - filter keep those satisfying
  Ç   - last link (1) as a monad

```

# Answer
> 6 votes
# 05AB1E, 14 bytes

```
ƒNpNbSD_‚OpP&–

```

Try it online!

**Explanation**

```
ƒ               # for N in [0 ... input]
 Np             # push N is prime
   Nb           # push N converted to binary
     S          # split into individual digits
      D_        # push an inverted copy
        ‚       # pair the 2 binary lists
         O      # sum them
          p     # elementwise check for primality
           P    # product of list
            &   # and with the primality of N
             –  # if true, print N

```

# Answer
> 6 votes
# Jelly, ~~14~~ 13 bytes

```
RBċþd`ÆPPTfÆR

```

Try it online!

### How it works

```
RBċþd`ÆPPTfÆR  Main link. Argument: n

R              Range; yield [1, ..., n].
 B             Binary; convert each integer to base 2.
    d`         Divmod self; yield [n : n, n % n], i.e., [1, 0].
  ċþ           Count table; count the occurrences of 1 and 0 in each binary
               representation, yielding a pair of lists of length n.
      ÆP       Test each count for primality.
        P      Product; multiply the corresponding Booleans.
         T     Truth; get all indices of 1, yielding the list of integers in
               [1, ..., n] that have a prime amount of 0's and 1's.
           ÆR  Prime range; yield all primes in [1, ..., n].
          f    Filter; intersect the lists.

```

# Answer
> 4 votes
# 05AB1E, ~~17~~ 15 bytes

```
LDpÏvybSD_)OpP—

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 4 votes
## Perl, 101 bytes

99 bytes of code + `-nl` flags.

```
$r=q/^1?$|^(11+)\1+$/;for$@(2..$_){$_=sprintf"%b",$@;print$@if(1x$@)!~$r&y/01/1/dr!~$r&s/0//gr!~$r}

```

To run it:

```
perl -lne '$r=q/^1?$|^(11+)\1+$/;for$@(2..$_){$_=sprintf"%b",$@;print$@if(1x$@)!~$r&y/01/1/dr!~$r&s/0//gr!~$r}' <<< 150

```

**Some short explanations**
`$r` holds the classical prime checking regex (`q/^1?$|^(11+)\1+$/`).
For all numbers between 2 and the input,
`(1x$@)!~$r` checks if the number is prime,
`y/01/1/dr!~$r` checks if the number of `0` in the binary representation is prime,
`s/0//gr!~$r` checks if the number `1` in the binary representation is prime.
(if the 3 conditions are met, `print$@` prints it).

# Answer
> 4 votes
# MATL, ~~16~~ 15 bytes

```
:"@tB!t~hshZp?@

```

Try it online!

```
:         % Input n (implicit). Push range [1 2 ... n]
"         % For each k in [1 2 ... n]
  @       %   Push k
  tB!     %   Duplicate. Binary expansion as an m×1 vector
  t~      %   Duplicate. Negate
  hs      %   Concatenate horizontally into an m×2 matrix. Sum of each column.
          %   This gives a 1×2 vector. However, for k==1 this gives the sum of
          %   the original 1×2 matrix (m==1). But fortunately it doesn't matter
          %   because 1 is not a prime anyway
  h       %   Concatenate horizontally into a 1×3 row vector
  Zp      %   Isprime function applied on each of those three numbers
  ?       %   If all gave true
    @     %     Push k
          %   End (implicit)
          % End (implicit)
          % Display (implicit)

```

# Answer
> 3 votes
# Python, ~~129~~ ~~125~~ 123 bytes

If only zero were prime...

```
p=lambda n:all(n%m for m in range(2,n))*n>1
lambda n:[i for i in range(n+1)if p(i)*all(p(bin(i)[2:].count(x))for x in'01')]

```

**Try it online**

Function `p` is the prime-checking function, which has `>0` at the end so that it works for zero as well, which would otherwise return `-1`. The anonymous lambda is the lambda that checks all the conditions required.

---

Here's a slightly different method using a set comprehension. The result will be a set. (**124 bytes**):

```
p=lambda n:all(n%m for m in range(2,n))*n>1
lambda n:{i*p(i)*all(p(bin(i)[2:].count(x))for x in'01')for i in range(n+1)}-{0}

```

# Answer
> 3 votes
# Perl 6, 65 bytes

```
{grep {all($^a,|map {+$a.base(2).comb(~$_)},0,1).is-prime},0..$_}

```

Try it

## Expanded:

```
{           # bare block lambda with implicit parameter ｢$_｣

  grep      # find all of the values where

  {         # lambda with placeholder parameter ｢$a｣

    all(    # all junction ( treat multiple values as a single value )

      $^a,  # declare parameter to block

      |\    # slip the following list into the outer list

      # get the count of 0's and 1's in the binary representation
      map

      {             # bare block lambda with implicit parameter ｢$_｣

        +           # turn to numeric ( count the values in the list )
        $a          # the outer parameter
        .base(2)    # in base 2
        .comb(~$_)  # find the characters that are the same as
      },0,1         # 0 or 1

    # ask if $a, count of 0's, count of 1's are all prime
    ).is-prime

  },

  0 .. $_ # Range from 0 to the input inclusive

}

```

# Answer
> 3 votes
# Octave, 73 bytes

```
@(n)(p=primes(n))(all(isprime([s=sum(dec2bin(p)'-48);fix(log2(p))+1-s])))

```

Try It Online!

```
@(n)
    (p=primes(n))                           generate prime numbers
        (all(                               from them select those that
            isprime(                        are prime both
                [s=sum(dec2bin(p)'-48);     sum of 1s
                fix(log2(p))+1-s])))        and sum of 0s

```

# Answer
> 2 votes
# CJam, ~~26~~ 27 bytes

```
ri){mp},{2b_1-,mp\0-,mp&},p

```

Straightforward algorithm, will golf further.

EDIT: Forgot n was inclusive.

Try it online!

For fun, this is very similar and also 27 bytes:

```
ri){_mp\2b_1-,mp\0-,mp&&},p

```

**Explanation**

```
ri                          e# Take an int as input
  ){mp},                    e# Take the range up and including to the input,
                            e#   including only prime numbers
       {                    e# For each prime...
        2b_                 e# Convert it to binary and copy it
           1-,mp            e# Take the top binary number, remove 1's, check if the length
                            e#   is prime
                \           e# Swap top elements
                 0-,mp      e# Do the same but remove 0's
                      &     e# And
                       },   e# Filter out primes for which the above block was false
                         p  e# Print nicely

```

# Answer
> 2 votes
## Python, ~~172~~ ~~170~~ ~~168~~ ~~159~~ ~~154~~ ~~133~~ 130 bytes

```
p=lambda n:[i for i in range(1,n)if n%i==0]==[1]
lambda n:[i for i in range(n+1)if p(i)*all(p(bin(i)[2:].count(x))for x in'10')]

```

---

Usage: Call the anonymous lambda function
Method `p` checks whether a number is prime

---

Saved 2+2+9=13 bytes thanks to Gurupad Mamadapur
Saved 5 bytes thanks to mbomb007

# Answer
> 2 votes
# Jelly, 14 bytes

```
BċÆPðÐf
ÆRç0ç1

```

Try it online!

Unfortunately, I could only tie with @Dennis, but the algorithm seems to be somewhat different so I'm posting this anyway.

## Explanation

Helper function (deletes list elements that don't have a prime number of occurrences of a given bit):

```
BċÆPðÐf
     Ðf   Filter {the first argument}, looking for truthy returns from
    ð     the preceding code, which takes two arguments:
B         Convert {the element being checked} to binary
 ċ        Count the number of occurrences of {the second argument}
  ÆP      Return true if prime, false if not prime

```

Main program:

```
ÆRç0ç1
ÆR        Generate all primes from 2 to the input
  ç0      Call the subroutine to require a prime 0 count
    ç1    Call the subroutine to require a prime 1 count

```

# Answer
> 2 votes
# Bash \+ GNU utilities, ~~129~~ ~~126~~ ~~123~~ ~~114~~ ~~111~~ 109 bytes

```
seq '-fp()([ `factor|wc -w` = 2 ]);g()(dc -e2o${n}n|tr -cd $1|wc -c|p);n=%.f;p<<<$n&&g 0&&g 1&&echo $n' $1|sh

```

Try it online!

Noticed the comment that the output doesn't have to be in increasing order -- shaved off 3 bytes by counting down instead of counting up.

Replaced grep with wc to save 3 additional bytes.

Eliminated a variable (9 more bytes off).

Changed the way factor is used -- 3 more bytes.

Made it golfier with seq (2 bytes).

# Answer
> 2 votes
# Haxe, ~~169~~ 171 bytes

```
function f(n,?p)return[for(j in(p=[for(i in 0...++n)i<2?0:i]))if(j>0){var x=j*2,y=0,z=0,k=j;while(k<n)p[k+=j]=0;while((x>>=1)>0)x&1>0?y++:z++;p[y]<1||p[z]<1?continue:j;}];

```

Nothing crazy. Essentially a modified sieve of Eratosthenes that evaluates the primality of the 0 / 1 count in the same iteration as crossing out higher non-primes. With some whitespace:

```
function f(n, ?p)
  return [ for (j in (p = [ for(i in 0...++n) i < 2 ? 0 : i ]))
    if (j > 0){
      var x = j * 2, y = 0, z = 0, k = j;
      while (k < n)
        p[k += j] = 0;
      while((x >>= 1) > 0)
        x & 1 > 0 ? y++ : z++;
      p[y] < 1 || p[z] < 1 ? continue : j;
    }
  ];

```

But today I learned I could put `continue` in a ternary operator and Haxe doesn't even mind.

Edit: +2 because `n` is an inclusive upper bound!

# Answer
> 2 votes
# Perl 6, 50 bytes

```
{grep {($_&+.base(2).comb(~0&~1)).is-prime},0..$_}

```

Variation of b2gills' answer, using the `&` junction operator to great effect.

Try it online!

### How it works

```
{                                                }  # Lambda
                                            0..$_   # Range from 0 to the lambda argument.
 grep {                                   },        # Filter values satisfying:
       ($_                      ).is-prime          #  a) The Number itself is prime.
       (   +.base(2).comb(~0   )).is-prime          #  b) The count of 0's is prime.
       (   +.base(2).comb(   ~1)).is-prime          #  c) The count of 1's is prime.
          &                 &                       # Junction magic! :)

```

# Answer
> 2 votes
# Stax, 14 bytes

```
ò≥úû╙2ï⌡T5è╧²■

```

Run and debug it

# Answer
> 2 votes
# Vyxal, 14 bytes

```
'bĊvtJ₅3=$væA∧

```

Try it Online!

```
'              # (implicitly convert to range), then filter by...
 b             # Binary representation
  Ċ            # Count the amount of each value in a (1 & 0 only)
   vt          # Get the counts
     J         # Join the current number to each of those
      ₅        # Duplicate and get length
       3=      # Is it equal to 3?
         $     # Swap
          væA  # Are all prime?
             ∧ # Are both true?

```

# Answer
> 1 votes
## Pyke, 21 bytes

```
S#j_PI\0[jb2R/_P)I\1[

```

Try it here!

```
S#j                   - for j in filter(range(1, input+1))
   _PI                -  if is_prime(j):
        [jb2R/_P)     -   function_[(a) = V
         jb2          -      base_2(j)
            R/        -     ^.count(a)
      \0         I    -   if function_[("0"):
                  \1[ -    function_[("1")

```

# Answer
> 1 votes
# Pyth, 18 bytes

```
f.APM_M+T/LSjT2U2S

```

Try it online here.

# Answer
> 1 votes
## Groovy, 120 bytes

```
p={x->(2..<x).every{x%it!=0}&x>1|x==2}
{x->(1..x).findAll({y->p(y)&'10'.every{p(Integer.toBinaryString(y).count(it))}})}

```

This is an unnamed closure.

Try it here!

# Answer
> 1 votes
# JavaScript (ES6), 110 bytes

```
B=n=>n?B(n>>1,v[n%2]++):v.every(n=>(P=i=>n%--i?P(i):1==i)(n))
F=(n,a=[])=>n?F(n-1,B(n,v=[0,0,n])?[n,...a]:a):a

```

```
B=n=>n?B(n>>1,v,v[n%2]++):v.every(n=>(P=i=>n%--i?P(i):1==i)(n))
F=(n,a=[])=>n?F(n-1,B(n,v=[0,0,n])?[n,...a]:a):a

const update = () => {
  console.clear();
  console.log(F(input.value))
}

input.oninput = update;
update();
```

```
<input id="input" type="number" min="1" value="100" />
```

# Answer
> 1 votes
# Python 3, 97 bytes

```
def f(n,k=2,m=1,p={0}):f(n-1,k+1,m*k*k,p^{m%k*k,{*map(bin(m%k%n*k)[2:].count,'01')}<p==print(k)})

```

This is the same algorithm as in my Python 2 answer, but the implementation is quite different. The function prints to STDOUT and terminates with an error.

Try it online!

# Answer
> 1 votes
# **MATLAB, 50 bytes**

```
@(n)all(isprime([n,sum(de2bi(n)),sum(~de2bi(n))]))

```

# Answer
> 1 votes
# Haxe, ~~158~~ 147 bytes

```
function p(n,x=1)return n%++x<1||n<2?x==n:p(n,x);function f(n){var q=n,t=0,o=0;while(q>0){t++;o+=q%2;q>>=1;}p(n)&&p(o)&&p(t-o)?trace(n):0;f(n-1);};

```

Outputs to STDOUT and terminates on a "too much recursion" error; call with e.g. `f(1000);`. You can use a `while` loop with no error for 156 bytes:

```
function p(n,x=1)return n%++x<1||n<2?x==n:p(n,x);function f(n){while(n>0){var q=n,t=0,o=0;while(q>0){t++;o+=q%2;q>>=1;}p(n)&&p(o)&&p(t-o)?trace(n):0;n--;}};

```

Using a range turned out three bytes longer:

```
function p(n,x=1)return n%++x<1||n<2?x==n:p(n,x);function f(n){for(i in 0...n+1){var q=i,t=0,o=0;while(q>0){t++;o+=q%2;q>>=1;}p(i)&&p(o)&&p(t-o)?trace(i):0;}};

```

Test it online!

# Answer
> 1 votes
# Rust, 147 bytes

```
fn f(x:u32){let p=|n|n>1&&(2..n).all(|x|n%x!=0);for n in 9..x+1{if p(n)&&p(n.count_ones())&&p(n.count_zeros()-n.leading_zeros()){print!("{} ",n)}}}

```

playground link

The `count_ones`, `count_zeros`, and `leading_zeros` methods came in handy.

### Formatted version

```
fn f(x: u32) {
    // primality test closure using trial division
    let p = |n| n > 1 && (2..n).all(|x| n % x != 0);

    for n in 9..x + 1 {
        if p(n) && p(n.count_ones()) && p(n.count_zeros() - n.leading_zeros()) {
            print!("{} ", n)
        }
    }
}

```

# Answer
> 1 votes
# Husk, 16 bytes

```
↑<⁰foΛṗo§e#0Σḋİp

```

Try it online!

# Answer
> 1 votes
# Husk, ~~15~~ 13 bytes

```
fȯΛṗmėΣ#0ḋḋŀ→

```

Try it online!

### Explanation:

```
fȯΛṗmėΣ#0ḋḋŀ→
           ŀ→    Inclusive range from 0 to input
fȯ               Filter by
    mė             Map three functions over
          ḋ        The binary digits
      Σ              Sum of digits
       #0            Count of zeroes
         ḋ           And convert back to decimal
  Λṗ               Are all the results prime?

```

# Answer
> 1 votes
# Japt, 15 bytes

```
õA fÈ¤ü mÊpX ej

```

Try it

# Answer
> 0 votes
# Thunno 2, 11 bytes

```
œPæ2B01,cPp

```

Try it online!

#### Explanation

```
œPæ2B01,cPp  # Implicit input
œP           # Only keep primes from [1..input]
  æ          # Filter this list of primes by:
   2B        #  Convert it to a binary list
     01,c    #  Count 0s and 1s
         Pp  #  Are they both prime?
             # Implicit output

```

---
Tags: code-golf, primes, binary
---


# Question
Title: Replace me by the sum of my cyclic successors!
I have a simple challenge for you this time. Given an array of positive integers **A** (or the equivalent in your language), replace each entry **Ai** with the sum of the next **Ai** elements of **A**, cycling back from the beginning if there are not enough items.

As usual, you can compete in any programming language and can take input and provide output through any standard method and in any reasonable format, while taking note that these loopholes are forbidden by default. You may optionally take the size of **A** as input too. This is , so the shortest submission (in bytes) for *every language* wins.

# Examples / Test Cases

Given `[1,3,4,5]`, your code should output `[3,10,13,14]`, because `1` is replaced by `3`, `3` is replaced by `4+5+1=10` (notice how it wrapped back from the start), `4` by `5+1+3+4=13` and `5` by `1+3+4+5+1=14`.

Given `[3,2,1,9]`, your program should produce `[12,10,9,33]`, because we substitute `3` with `2+1+9=12`, `2` with `1+9=10`, `1` with `9` and `9` with `3+2+1+9+3+2+1+9+3=33` (notice how we wrapped back from the start more than once).

Some more test cases for you to choose from:

```
[4,3,2,1]                       -> [10,7,5,4]
[3,2,1,9]                       -> [12,10,9,33]
[1,3,4,5]                       -> [3,10,13,14]
[4,4,3,2,2]                     -> [11,11,8,6,8]
[3,5,3,2,1]                     -> [10,14,6,4,3]
[3,2,4,3,2,1,1]                 -> [9,7,7,4,2,1,3]
[7,8,6,5,4,3,2,1,5]             -> [29,33,20,15,11,8,6,5,30]
[28,2,4,2,3,2,3,4,5,3]          -> [137,6,10,5,9,7,12,38,39,34]
[1,2,3,4,5,4,3,2,1,2,3,4,3,2,1] -> [2,7,13,14,12,8,5,3,2,7,9,7,4,2,1]

```

# Answer
# MATL, ~~10~~ 9 bytes

```
"G@:X@+)s

```

Try it online!

```
	% implicit input
"	% for loop, iterate over the input array
G	% push input x
@	% push for loop index, x[i]
:	% range, push [1,...,x[i]]
X@	% push for loop index, i
+	% sum, so stack holds [i+1,...,i+x[i]]
)	% index, modularly, so gets the cyclic successors
s	% sum cyclic successors, leaving the sum on the stack
	% implicit end of for loop
	% implicit output of stack

```
> 8 votes

# Answer
# Jelly, 6 bytes

```
ṙJṁS¥"

```

Try it online!
> 6 votes

# Answer
# Python, 55 bytes

```
lambda a:[sum((-~v*a)[i:i+v])for i,v in enumerate(a,1)]

```

**Try it online!**
> 6 votes

# Answer
# C (gcc), ~~86~~ 85 bytes

* Saved a byte thanks to Jakob.

```
C(y,c,l,i,k)int*y;{for(l=~0;++l<c;printf("%d,",k))for(k=i=0;i++<y[l];k+=y[(l+i)%c]);}

```

Try it online!
> 6 votes

# Answer
## Haskell, ~~50~~ ~~47~~ 44 bytes

```
zipWith((sum.).take)<*>scanr(:)[].tail.cycle

```

Try it online!

```
                    -- <*> in function context is Haskell's S combinator, i.e.
                    --     (zipWith ... <*> scanr ...) arg
                    -- resovles to
                    --     zipWith ... arg (scanr ... arg)
zipWith             -- so we zip
                    --   the input list and
 scanr(:)[]         --   the tails (tails of [1,2,3] are [[1,2,3],[2,3],[3],[]])
      tail          --   of the tail of
          cycle     --   and infinite cycle of the input list
                    -- with the function
 (sum.).take        --   take that many elements given by the element
                    --   of the input list from the list given by the inits
                    --   and sum it

```
> 6 votes

# Answer
# J, 33 bytes

```
[:({.+/@{.}.)"1 i.@#|."{($~>./*#)

```

## ungolfed

```
[: ({. +/@{. }.)"1 i.@# |."0 _ ($~ (>./ * #))

```

## explanation

Try it online!
> 6 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
εL¾+èO¼

```

Try it online!

**Explanation**

```
ε        # apply to each element x of the input
 L       # push range [1 ... x]
  ¾+     # add counter to each (initially 0)
    è    # cyclically index into input with each
     O   # sum
      ¼  # increment counter

```
> 4 votes

# Answer
# K4 / K (oK), ~~20~~ 19 bytes

**Solution:**

```
+/'x#'1_(1+2##x)#x:

```

Try it online!

**Examples:**

```
q)k)+/'x#'1_(1+2##x)#x:1 3 4 5
3 10 13 14
q)k)+/'x#'1_(1+2##x)#x:4 3 2 1
10 7 5 4
q)k)+/'x#'1_(1+2##x)#x:3 2 4 3 2 1 1
9 7 7 4 2 1 3
q)k)+/'x#'1_(1+2##x)#x:1 2 3 4 5 4 3 2 1 2 3 4 3 2 1
2 7 13 14 12 8 5 3 2 7 9 7 4 2 1

```

**Explanation:**

Reshape input, drop first, take x length of each, sum up.

```
+/'x#'1_(1+2##x)#x: / the solution
                 x: / store input as x
                #   / reshape
        (      )    / do this together
             #x     / count x
           2#       / duplicate (2-take)
         1+         / add 1
      1_            / 1 drop (_), remove first element
   x#'              / x take each-both
+/'                 / sum (+/) each

```
> 4 votes

# Answer
# , ~~62~~ 58 bytes

```
function(a,l)diag(diffinv(matrix(a,max(a)*l+1,l))[a+2,])-a

```

Try it online!

An alternative to the other R solution. In the comments JayCe made a mention of `cumsum` which triggered something in my brain to use `diffinv` and matrix recycling instead of `rep`.

### Explanation:

Given input array `a`, let `M=max(a)` and `l=length(a)`.

Observe that `M+l` is the maximum possible index we'd need to access, and that `M+l<=M*l+1`, since if `M,l>1`,`M+l<=M*l` (with equality only when `M=l=2`) and if `l==1` or `M==1`, then `M+l==M*l+1`.

By way of example, let `a=c(4,3,2,1)`. Then `M=l=4`.

We construct the `M*l+1 x l` matrix in R by `matrix(a,max(a)*l+1,l)`. Because R recycles `a` in column-major order, we end up with a matrix repeating the elements of `a` as such:

```
      [,1] [,2] [,3] [,4]
 [1,]    4    3    2    1
 [2,]    3    2    1    4
 [3,]    2    1    4    3
 [4,]    1    4    3    2
 [5,]    4    3    2    1
 [6,]    3    2    1    4
 [7,]    2    1    4    3
 [8,]    1    4    3    2
 [9,]    4    3    2    1
[10,]    3    2    1    4
[11,]    2    1    4    3
[12,]    1    4    3    2
[13,]    4    3    2    1
[14,]    3    2    1    4
[15,]    2    1    4    3
[16,]    1    4    3    2
[17,]    4    3    2    1

```

Each column is the cyclic successors of each element of `a`, with `a` across the first row; this is due to the way that R recycles its arguments in a matrix.

Next, we take the inverse "derivative" with `diffinv`, essentially the cumulative sum of each column with an additional `0` as the first row, generating the matrix

```
      [,1] [,2] [,3] [,4]
 [1,]    0    0    0    0
 [2,]    4    3    2    1
 [3,]    7    5    3    5
 [4,]    9    6    7    8
 [5,]   10   10   10   10
 [6,]   14   13   12   11
 [7,]   17   15   13   15
 [8,]   19   16   17   18
 [9,]   20   20   20   20
[10,]   24   23   22   21
[11,]   27   25   23   25
[12,]   29   26   27   28
[13,]   30   30   30   30
[14,]   34   33   32   31
[15,]   37   35   33   35
[16,]   39   36   37   38
[17,]   40   40   40   40
[18,]   44   43   42   41

```

In the first column, entry `6=4+2` is equal to `14=4 + (3+2+1+4)`, which is the cyclic successor sum (CSS) plus a leading `4`. Similarly, in the second column, entry `5=3+2` is equal to `10=3 + (4+1+2)`, and so forth.

So in column `i`, the `a[i]+2`nd entry is equal to `CSS(i)+a[i]`. Hence, we take rows indexed by `a+2`, yielding a square matrix:

```
     [,1] [,2] [,3] [,4]
[1,]   14   13   12   11
[2,]   10   10   10   10
[3,]    9    6    7    8
[4,]    7    5    3    5

```

The entries along the diagonal are equal to the cyclic successor sums plus `a`, so we extract the diagonal and subtract `a`, returning the result as the cyclic successor sums.
> 4 votes

# Answer
# Jelly, 7 bytes

```
R+"Jị⁸§

```

**Try it online!**
> 3 votes

# Answer
# Attache, 26 bytes

```
{Sum=>_[(_2+1:_)%#_]}#Iota

```

Try it online!

## Explanation

This is a fork of two functions:

* `{Sum=>_[(_2+1:_)%#_]}`
* `Iota`

What this means is, the right tine `Iota` is applied to the argument `x` and is passed as the second argument to the center tine (the first function). So this becomes, for input `x`:

```
{Sum=>_[(_2+1:_)%#_]}[x, Iota[x]]

```

Replacing those in for `_` and `_2`:

```
Sum => x[(Iota[x] + 1:x) % #x]

```

`Iota[x]` returns an array of the indices of `x`. It's equivalent to `0...#x`. `#x` is a short way of saying the size of `x`, or `Size[x]`. In essence, this function is mapping the `Sum` function over the second expression:

```
x[(Iota[x] + 1:x) % #x]

```

The outer `x[...]` bit means that `...` will generate a series of indices to be selected from `x`. The most important part of generating the indices is this:

```
Iota[x] + 1:x

```

This expression uses a bit of vectorization. To visualize this, let's suppose the input is `x := [1, 3, 4, 5]`. Then, this expression is equivalent to:

```
Iota[[1, 3, 4, 5]] + 1:[1, 3, 4, 5]
[0, 1, 2, 3] + [1:1, 1:3, 1:4, 1:5]
[0, 1, 2, 3] + [[1], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
[0 + [1], 1 + [1, 2, 3], 2 + [1, 2, 3, 4], 3 + [1, 2, 3, 4, 5]]
[[0 + 1], [1 + 1, 1 + 2, 1 + 3], [2 + 1, 2 + 2, 2 + 3, 2 + 4], [3 + 1, 3 + 2, 3 + 3, 3 + 4, 3 + 5]]
[[1], [2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 7, 8]]

```

This is a list of indices which represent the indices next `N` elements in `x` mod `#x`. To make them safe for retrieval, we take this array mod `#x`:

```
(Iota[x] + 1:x) % #x

```

This gives us the proper indices, which are then obtained from `x` and each array is summed, giving the proper results.

## Other attempts

**36 bytes:** `{Sum@_&Get=>((_2+1.._2+_)%#_)}#Iota` \- I forgot `x[...]` fully vectorizes, so that becomes:

**30 bytes:** `{Sum=>_[(_2+1.._2+_)%#_]}#Iota` \- but then I realized the `_2+` in the inner range could be factored out, which means we could save parentheses by using `:` instead of `..`, giving us the current version.
> 3 votes

# Answer
# , ~~89~~ 64 bytes

```
j=rep(x<-scan(),max(x));Map(function(u,v)sum(j[v+1:u]),x,seq(x))

```

Try it online!

Main idea to to generate a way-long-enough cycling index vector you can use to get the needed elements from the input vector.

Original version:

```
function(x,i=seq(x),j=rep(i,max(x))){for(k in i){T=c(T,sum(x[j[(k+1):(k+x[k])]]))};T[-1]}

```

Try it online!
> 3 votes

# Answer
# Pyth, ~~13~~ 11 bytes

```
.esm@Q+dkSb

```

Saved 2 bytes thanks to Mr. Xcoder.
Try it here

### Explanation

```
.esm@Q+dkSb
.e         Q   For each index k and value b in (implicit) input...
         Sb    ... get the list [1, ..., b]...
   m  +dk      ... add k to each...
    @Q         ... and index into the input...
  s            ... then take the sum.

```
> 2 votes

# Answer
# Charcoal, 12 bytes

```
ＩＥθΣＥι§θ⊕⁺κλ

```

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

```
  θ             Input array
 Ｅ              Map over elements
     ι          Current element
    Ｅ           Map over implicit range
           λ    Inner index
          κ     Outer index
         ⁺      Sum
        ⊕       Increment
       θ        Input array
      §         Cyclically index
   Σ            Sum
Ｉ               Cast to string
                Implicitly print on separate lines

```
> 2 votes

# Answer
# Julia 0.6, 63 55 53 bytes

```
A->[sum(repmat(A,v+1)[i+1:i+v])for(i,v)=enumerate(A)]

```

Try it online!

---

Older solution:

# Julia 0.6, 65 bytes

```
A->(l=length(A);[sum(A[mod1(j,l)]for j∈i+1:i+A[i])for i∈1:l])

```

Try it online!

---

Another solution. Not great by bytecount, but I like it, and it's probably more efficient than the other two, especially if the input has big numbers.

# Julia 0.6, 69 bytes

```
A->(l=length(A);[sum([A;A][i+1:i+A[i]%l])+A[i]÷l*sum(A)for i∈1:l])

```

Try it online!
> 2 votes

# Answer
# Java 8, 87 bytes

A curried void lambda taking an `int[]` list and `int` length.

```
l->s->{for(int i=-1,j,t;++i<s;System.out.println(t))for(j=t=0;j++<l[i];)t+=l[(i+j)%s];}

```

Try It Online. Note that I've shadowed `System.out` in this program in order to grab results for prettier printing.
> 2 votes

# Answer
# JavaScript ES6, 65 bytes

```
a=>a.map((x,y)=>{for(s=0,i=y;i<y+x;)s+=a[++i%a.length];return s})

```

Straightforward solution. Ungolfed:

```
a => a.map((x,y) => {
    var s = 0;
    for (i = y; i < y + x; i++) {
        s += a[i % a.length];
    }
    return s;
});

```

JavaScript's `map()` function is perfect for the job, it runs the given callback against each element and replaced it by the result of the callback. The callback receives two parameters, the first `x` is the value and the second `y` is the index. By taking the modulus `i % a.length` we can easily loop over the array, multiple times if needed.

### Test snippet

(Put the input as JSON notation)

```
let f = a=>a.map((x,y)=>{for(s=0,i=y;i<y+x;)s+=a[++i%a.length];return s})
```

```
<input id=I type="text" size=70 value="[4,3,2,1]"><button onclick="console.log(f(JSON.parse(I.value)))">Run</button>
```
> 2 votes

# Answer
## Perl 5 with `-M5.010`, 42 bytes

```
say sum+((@F,@F)x$_)[++$-..($-+$_-1)]for@F

```

Try it online!
> 1 votes

# Answer
# Canvas, 10 bytes

```
²Ｘ｛ｘ＋⁸＠］∑］

```

Try it here!

Explanation:

```
{         ] map over the items in the input
 ²X           save this loops counter on X (because of a bad design choice..)
   {    ]     map over 1..current item
    x+          add to it X
      ⁸@        and index in the input using that
         ∑    sum the map

```
> 1 votes

# Answer
# QBasic 1.1, 115 bytes

```
INPUT L
DIM A(L)
FOR I=0TO L-1
INPUT C
A(I)=C
NEXT
FOR I=0TO L-1
S=0
FOR C=I+1TO I+A(I)
S=S+A(C MOD L)
NEXT
?S
NEXT

```

First input is the length **L**, then **L** subsequent inputs are the elements in order. **L** outputs represent the resulting array, with the elements in the order they're presented.
> 1 votes

# Answer
# Perl 6, ~~50~~ 32 bytes

```
{$_>>.&{.[++$+ ^$^a X%+$_].sum}}

```

Try it online!

~~I'm new to golfing in Perl 6, so I'm sure this can be shorter.~~ Not new anymore, and back to golf this!
> 1 votes

# Answer
# Japt, 7 bytes

```
ËÆg°EÃx

```

Try it here
> 1 votes

# Answer
# JavaScript, 46 bytes

```
a=>a.map(g=(x,y)=>x--&&a[++y%a.length]+g(x,y))

```

Try it online
> 1 votes

# Answer
# APL+WIN, 37 bytes

Prompts for input:

```
+/¨v↑¨⊂[2](⍳⍴v)⌽((⍴v),⍴n)⍴n←(+/v)⍴v←⎕

```

Try it online! Courtesy of Dyalog Classic

Explanation:

```
n←(+/v)⍴v←⎕ prompts for input and creates a repeating vector of length max v

((⍴v),⍴n)⍴n converts n to a matrix of length v x length n

(⍳⍴v)⌽ rotates each row of n by the size of each element of v

⊂[2] converts each row of m to an element in a nested vector

+/¨v↑¨ selects the number of elements from each element of the nested vector according to v and sums

```
> 1 votes

# Answer
# **JavaScript, 65 bytes 3̶0̶0̶ ̶b̶y̶t̶e̶s̶**

golfed

```
n=>n.map((z,x)=>{for(s=0,i=x;i<z+x;)s+=n[++i%n.length];return s})

```

ungolfed

```
     f = n=>n.map((z,x)=>{
            for(s=0,i=x;i<z+x;)s+=n[++i%n.length];
            return s
            }
        );
console.log(f(process.argv[2].slice(1, -1).split(", ").map(x=>+x)))

```

Try it online!

(ungolfed version above) I'm new to this codegolf thing!

---

\*updated! thanks to the useful links provided in comments, I managed to reduce the size to 65 bytes!
> 1 votes

# Answer
# Ruby, 38 bytes

```
->a{w=0;a.map{|x|(a*-~x)[w+=1,x].sum}}

```

Try it online!
> 1 votes

# Answer
# Pip `-rn`, 14 bytes

```
$+g@(_+\,B)MEg

```

Takes input numbers on successive lines of stdin; gives output numbers on successive lines of stdout. Try it online!

### Explanation

```
             g  List of lines of stdin (from -r flag)
           ME   Enumerate and map this function to the (index, value) pairs:
       \,B       One-based range(value)
     _+          To each element, add the index of that value
  g@(     )      Use the resulting range to slice into the original list g
                 (cyclical indexing is built in)
$+               Sum the numbers in the slice
                Output the list of results one per line (from -n flag)

```

Or, using a worked example:

```
             g  [1 3 4 5]
           ME
       \,B      [(1,2) (1,4) (1,5) (1,6)]
     _+         [(1,2) (2,5) (3,7) (4,9)]
  g@(     )     [[3] [4 5 1] [5 1 3 4] [1 3 4 5 1]]
$+              [3 10 13 14]

```
> 1 votes

# Answer
# APL (Dyalog Classic), 12 bytes

```
+/¨⊢⍴¨⍳∘≢⌽¨⊂

```

Try it online!

uses `⎕io←1`
> 1 votes

# Answer
# Thunno 2, 6 bytes

```
ıRṅ+iS

```

Try it online!

#### Explanation

```
ıRṅ+iS  # Implicit input
ı       # Map over the input:
 R      #  [1..item]
  ṅ+    #  Plus 0-based index
    i   #  Index into input
     S  #  Sum the list
        # Implicit output

```
> 1 votes

# Answer
# Vyxal, 10 bytes

```
ėƛ÷$?$›ǓẎ∑

```

Try it Online!

#### Explanation

```
ėƛ÷$?$›ǓẎ∑  # Implicit input
ėƛ          # Enumerate (index, item) and map over:
  ÷$        #  Dump onto stack and swap
    ?$›Ǔ    #  Rotate input left by (index + 1)
        Ẏ∑  #  Take the first (item) elements and sum
            # Implicit output

```
> 1 votes

# Answer
# Cjam, 23 bytes

```
_ee{~,\)f+1$f=:+\}/;]S*

```

Try it online!
> 0 votes

# Answer
# Factor \+ `math.unicode sequences.repeating`, 51 bytes

```
[ dup [ 1 + rotate swap cycle Σ ] with map-index ]

```

Try it online!
> 0 votes

# Answer
# Arturo, 55 bytes

```
$[a][i:1map a'x[sum map i..i+x-1'y[a\[y%size a]]i:i+1]]

```

Try it

```
$[a][                  ; a function taking an argument a
  i: 1                 ; assign 1 to i
  map a' x[            ; map over a and assign current element to x
    sum                ; sum
    map i..i+x-1 'y [  ; map over i to i+x-1, the indices in a that form our desired sum; assign current elt to y
      a\[y % size a]   ; index a at y modulo the length of a
    ]                  ; end map
    i: i + 1           ; increment i
  ]                    ; end map
]                      ; end function

```
> 0 votes

# Answer
# Thunno, \\$ 15\log\_{256}(96)\approx \\$ 12.35 bytes

```
AEeAuR1++z0sAIS

```

Attempt This Online!
> 0 votes

# Answer
# Vyxal, 44 bitsv2, 5.5 bytes

```
ż~+rİṠ

```

Try it Online!

What is this goofy 10 byte nonsense I see?

## Explained

```
ż~+rİṠ
ż       # Push the range [1, len(input)]
 ~+     # And add it to the input without popping
   r    # Vectorise range with the input. This essentially generates a list of indices of the next n items after each item in the input.
    İ   # Index that list of indices into the input.
     Ṡ  # And sum each list.

```

Created with the help of Luminespire.
> 0 votes

---
Tags: code-golf, array, integer
---