前n个没有连续相等的二进制数字的数字


32

该序列包含以下形式的二进制数字的十进制表示形式:10101...,其中第n个项具有n位。

仅显示数字的二进制和十进制表示形式之间的关系,可能最容易解释该序列:

0       ->  0
1       ->  1
10      ->  2
101     ->  5
1010    ->  10
10101   ->  21
101010  ->  42

挑战:

取一个输入integer n,并返回序列中的前n个数字。您可以选择序列0索引或1索引。

测试用例:

n = 1   <- 1-indexed
0

n = 18
0, 1, 2, 5, 10, 21, 42, 85, 170, 341, 682, 1365, 2730, 5461, 10922, 21845, 43690, 87381

与往常一样,鼓励人们进行解释。

这是OEIS A000975


给定您自己的MATL解决方案,以相反的顺序输出结果是否可以接受?
粗野的

是的,只要已排序即可。@Shaggy
Stewie Griffin

运气不错,但是这种输出格式可以接受[85,[42,[21,[10,[5,[2,[1,0]]]]]]]吗?
长毛

Answers:


66

Python 2,36个字节

lambda n:[2**i*2/3for i in range(n)]

在线尝试!说明:2的二进制表示形式是,因此只需将其乘以2的适当幂并取整数部分即可。230.101010101...


1
太糟糕了,它是2018年1月,否则我会提名它为``最佳PPCG 2017最佳数学见解''。希望我在2019年初还记得它; p
Kevin Cruijssen

@KevinCruijssen,这是我在所有codegolf.stackexchange.com/a/51574/17360中
qwr

3
@KevinCruijssen不要忘记!
Bassdrop Cumberwubwubwub

2
@BassdropCumberwubwubwub感谢您的提醒,因为我确实完全忘记了它!它已被添加到提名中。
Kevin Cruijssen

11

05AB1E,4个字节

使用尼尔的2/3技巧保存了2个字节

Lo3÷

在线尝试!

说明

L      # push range [1 ... input]
 o     # raise 2 to the power of each
  3÷   # integer division of each by 3

05AB1E,6个字节

TRI∍ηC

在线尝试!

说明

T        # push 10
 R       # reverse it
  I∍     # extend to the lenght of the input
    η    # compute prefixes
     C   # convert each from base-2 to base-10

9

果冻... 4个字节

感谢-1个字节的英里

ḶḂḄƤ

在线尝试!

说明:

owered range, or Unength. Get [0, 1, 2, 3, ..., n-1]
 Ḃ    it. Get the last bit of each number. [0, 1, 0, 1, ...]
   Ƥ  for each Ƥrefixes [0], [0, 1], [0, 1, 0], [0, 1, 0, 1], ...
  Ḅ   convert it from inary to integer.

果冻,4字节

乔纳森·艾伦(Jonathan Allan)的版本。

Ḷ€ḂḄ

在线尝试!

owered range, or Unength.
 €    Apply for each. Automatically convert the number n
      to the range [1,2,..,n]. Get [[0],[0,1],[0,1,2],..].
  Ḃ   it. Get the last bit from each number.
      Current value: [[0],[0,1],[0,1,0],..]
   Ḅ  Convert each list from inary to integer.

基于Neil的2/3技巧的版本提供5个字节,请参阅修订历史记录。


ḶḂḄƤ为此使用了前缀快
英里

甚至不需要前缀快速- Ḷ€ḂḄ也可以。
乔纳森·艾伦

5

MATL,5个字节

:WI/k

根据尼尔的回答

说明

:       % Implicit input, n. Push range [1 2 ... n]
W       % 2 raised to that, element-wise. Gives [2 4 ...2^n] 
I       % Push 3
/       % Divide, element-wise
k       % Round down, element-wise. Implicit display

在线尝试!


MATL,9个字节

:q"@:oXBs

在线尝试!

说明

:       % Implicit input n. Range [1 2 ... n]
q       % Subtract 1, element-wise: gives [0 1 ... n-1]
"       % For each k in [0 1 ... n-1]
  @     %   Push k
  :     %   Range [1 2 ... k]
  o     %   Modulo 2, element-wise: gives [1 0 1 ...]
  XB    %   Convert from binary to decimal
  s     %   Sum. This is needed for k=0, to transform the empty array into 0
        % Implicit end. Implicit display

5

Python 2中45个 37 36字节

-3字节归功于user202729
-1字节归功于mathmandan

s=0
exec"print s;s+=s+~s%2;"*input()

在线尝试!


加倍s与加法相同s,因此我相信您可以s+=s+~s%2节省一个字节。
mathmandan

5

Python 3,68 61 54 48 43字节

c=lambda x,r=0:x and[r]+c(x-1,2*r+~r%2)or[]  

感谢user202729帮助保存19个字节,而ovs帮助保存6个字节。

在线试用


感谢-1字节。我想我不能用and or代替吗?
Manish Kundu

好的,已经做到了。
Manish Kundu

2
因为x == 0等于not xif x是一个整数,所以交换操作数(即x if c else y= y if not c else x)将节省更多字节。
user202729

您也可以删除i%2,并使用1-r%2替代
罗德

1
然后,您无需跟踪i
user202729

4

外壳,7个字节

mḋḣ↑Θݬ

在线尝试!

基于1的,因此输入n给出前n个结果。

说明

     ݬ   The infinite list [1, 0, 1, 0, 1, ...]
    Θ     Prepend a zero.
   ↑      Take the first n elements.
  ḣ       Get the prefixes of that list.
mḋ        Interpret each prefix as base 2.

4

APL(Dyalog Unicode),11 字节SBCS

假设⎕IOI ndex O rigin)为0,这在许多系统上都是默认的。匿名默认前缀功能。1个索引。

(2⊥⍴∘1 0)¨⍳

在线尝试!

ɩ0 …n−1

( 对每个应用以下默认功能

⍴∘1 0 周期性地将列表[1,0]调整为该长度

2⊥ 从base-2(二进制)转换为普通数字


4

Perlv5.10 -n,24 + 1字节

-3个字节感谢Nahuel Fouilleul

say$v=$v*2|$|--while$_--

在线尝试!

逻辑与我的Ruby版本相同,但由于perl更简洁,所以逻辑更短。出于某种奇怪的原因,print不会做分隔符(该死!),所以我不得不使用sayfrom 来使它v5.10;运行,我不确定如何给它打分,所以我暂时将其留在外面吗? ..

说明

say    # Like shouting, but milder.
  $v = $v*2 | $|-- # Next element is this element times 2 bitwise-OR
                   # with alternating 0 1 0 1..., so 0b0, 0b1, 0b10, 0b101...
                   # $. is OUTPUT_AUTOFLUSH, which is initially 0 and
                   #   setting all non-zero values seem to be treated as 1
  while $_-- # do for [input] times

for the scoring i would say: 27 + 1 (-n) = 28 bytes, because to run a perl one-liner, one should use -e and to use 5.10 you just need to use -E, which is the same length
Nahuel Fouilleul

can save 3 bytes using $|-- instead of ($.^=1)
Nahuel Fouilleul



4

C, 81 55 59 bytes

1 indexed.

i,j;f(c){for(i=j=0;i<c;)printf("%d ",i++&1?j+=j+1:(j+=j));}

Full program, less golfed:

i;j;main(c,v)char**v;{c=atoi(*++v);for(;i<c;i++)printf("%d ",i&1?j+=j+1:(j+=j));}

Try it online!

EDIT 2: I was under the assumption that functions didn't need to be reusable now that I think of it, it makes perfect sense that they would have to be reusable :P

EDIT: I was under the misconception that I had to include the entire program in the answer, turns out I only needed the function that does it. That's nice.

I'm decently sure I can shave off a few bytes here and there. I've already employed a few tricks. A large chunk of the program is dedicated to getting the argument and turning it into an int. This is my first code golf. If I'm doing anything wrong tell me :P


2
Welcome to PPCG! :) I'm not a C guy but you may be able to glean some hints from Steadybox's solution.
Shaggy

Ok that makes more sense now, I've included the entire program when all I need is a function and the rest can be done in a footer. I guess this can be significantly improved then.
Minerscale

Welcome to PPCG! You can save a byte by removing i++ and changing i&1 to i++&1. Also, although as global variables i and j are initialized to zero initially, they need to be initialized inside the function, because function submissions have to be reusable.
Steadybox

1
Even better, it's possible to save 2 more bytes, eliminating the ternary entirely.
user202729

2
50 bytes: i,j;f(c){for(i=j=0;i<c;)printf("%d ",j+=j+i++%2);} Try it online!
Steadybox

4

Haskell, 47 40 53 49 44 40 34 bytes

-4 bytes thanks to user202729
-6 bytes thanks to Laikoni

(`take`l)
l=0:[2*a+1-a`mod`2|a<-l]

Try it online!


You can replace otherwise with e.g. 1>0 (otherwise == True)
flawr

To golf it even more, you can use the guard for assigning something, e.g. like this: Try it online!
flawr

1
PS: Also check out tips for golfing in haskell as well as our haskell-chatroom of monads and men.
flawr

1
You need to make a function that returns the first n elements of the list where n is the argument.
totallyhuman

1
Yes, exactly. I can recommend to have a look at our Guide to Golfing Rules in Haskell, which tries to capture the current consensus on what is allowed and what isn't.
Laikoni

4

Ruby, 26 bytes

->n{(1..n).map{|i|2**i/3}}

Try it online!

Beats all the older ruby answers.

Explanation

1/3 in binary looks like 0.01010101..., so If you multiply it by powers of two, you get:

n| 2^n/3
-+---------
1|0.1010101...
2|01.010101...
3|010.10101...
4|0101.0101...
5|01010.101...
6|010101.01...

But Ruby floors the numbers on int division, giving me the sequence I need.


4

J, 9 bytes

[:#.\2|i.

How it works?

i. - list 0..n-1

2| - the list items mod 2

\ - all prefixes

#. - to decimal

[: - caps the fork (as I have even number (4) of verbs)

Try it online!


3

Retina, 28 bytes

)K`0
"$+"+¶<`.+
$.(*__2*$-1*

Try it online!

0-based, so input n gives the first n+1 results.

Explanation

Uses the recursion from OEIS:

a(n) = a(n-1) + 2*a(n-2) + 1

Let's go through the program:

)K`0

This is a constant stage: it discards the input and sets the working string to 0, the initial value of the sequence. The ) wraps this stage in a group. That group itself does nothing, but almost every stage (including group stages) records its result in a log, and we'll need two copies of the 0 on that log for the program to work.

"$+"+¶<`.+
$.(*__2*$-1*

There's a bunch of configuration here: "$+"+ wraps the stage in a loop. The "$+" is treated as a substitution, and $+ refers to the program's input, i.e. n. This means that the loop is run n times.

Then ¶< wraps each iteration in an output stage, which prints the stage's input with a trailing linefeed (so the first iteration prints the zero, the second iteration prints the first iteration's result and so on).

The stage itself replaces the entire working string with the substitution on the last line. That one makes use of an implicit closing parenthesis and implicit arguments for the repetition operator *, so it's actually short for:

$.($&*__2*$-1*_)

The stuff inside the parentheses can be broken up into three parts:

  • $&*_: gives a string of a(n-1) _s.
  • _: gives a single _.
  • 2*$-1*_: gives a string of 2*a(n-1) _. The $-1 refers to the penultimate result in the result log, i.e. the loop iteration before the last. That's why we needed to copies of the zero on the log to begin with, otherwise this would refer to the program's input on the first iteration.

Then $.(…) measures the length of the resulting string. In other words, we've computed a(n) = a(n-1) + 1 + 2*a(n-2) by going through unary (not really though: $.(…) is lazy and doesn't actually evaluate its content if it can determine the resulting length directly through arithmetic, so this is even quite efficient).

The result of the final loop iteration (the n+1th element of the sequence) is printed due to Retina's implicit output at the end of the program.


3

Brain-Flak, 36 bytes

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

Try it online!

Explanation:

The next number in the sequence is obtained by n*2+1 or n*2+0.

{([()]{}< Loop input times
  (
   (({}<>)<>){} Copy n to other stack; n*2
   ([{}]())  i = 1-i
  ) push n*2 + i
>)} End loop
<> Output other stack

3

Ruby 42 41 43 41 37 35 31 33 30 bytes

-2 bytes thanks to Unihedron

-3 bytes thanks to G B

->x{a=0;x.times{a-=~a+p(a)%2}}

Try it online!


Good work! I like your formula ^^
Unihedron

1
save 3 bytes: ->x{a=0;x.times{a-=~a+p(a)%2}}
G B

2

><>, 22 + 3 (-v flag) bytes

0:nao::1+2%++$1-:?!;$!

Try it online!

Explanation

The stack gets initialized with the loop counter.

0:nao                  : Push 0 to the stack, duplicate and print with a new line.
                         [7] -> [7, 0]
     ::1+              : Duplicate the stack top twice more then add 1 to it.
                         [7, 0] -> [7, 0, 0, 1]
         2%++          : Mod the stack top by 2 then add all values on the stack bar the loop counter.
                         [7, 0, 0, 1] -> [7, 1]
             $1-:?!;$! : Swap the loop counter to the top, minus 1 from it and check if zero, if zero stop the program else continue.

2

Java 8, 115 81 80 52 bytes

n->{for(int i=2;n-->0;i*=2)System.out.println(i/3);}

Port of @Neil's Python 2 answer.
1-indexed and outputted directly, each value on a separated line.

Explanation:

Try it online.

n->{                           // Method with integer parameter and no return-type
  for(int i=2;                 //  Start integer `i` at 2
      n-->0;                   //  Loop `n` times:
      i*=2)                    //    Multiply `i` by 2 after every iteration
    System.out.println(i/3);}  //   Print `i` integer-divided by 3 and a new-line

Old 80 bytes answer:

n->{String t="",r=t;for(Long i=0L;i<n;)r+=i.parseLong(t+=i++%2,2)+" ";return r;}

1-indexed input and space-delimited String output

Explanation:

Try it online.

n->{                             // Method with integer parameter and String return-type
  String t="",r=t;               //  Temp and result-Strings, both starting empty
  for(Long i=0L;i<n;)            //  Loop from 0 to `n` (exclusive)
    r+=                          //   Append the result-String with:
       i.parseLong(        ,2);  //    Binary to integer conversion
                   t+=           //     append the temp-String with:
                      i  %2      //      current index `i` modulo-2
                       ++        //      and increase `i` by one afterwards
       +" ";                     //    + a space
  return r;}                     //  Return the result-String



2

C, 47 46 bytes

a;f(n){for(a=0;n--;a+=a-~a%2)printf("%d ",a);}

The accumulator a begins with zero. At each step, we double it (a+=a) and add one if the previous least-significant bit was zero (!(a%2), or equivalently, -(~a)%2).

Test program

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    while (*++argv) {
        f(atoi(*argv));
        puts("");
    }
}

Results

$ ./153783 1 2 3 4 5 6
0 
0 1 
0 1 2 
0 1 2 5 
0 1 2 5 10 
0 1 2 5 10 21 

2

Japt, 10 9 7 6 bytes

All derived independently from other solutions.

1-indexed.

õ!²mz3

Try it


Explanation

õ        :[1,input]
 !²      :Raise 2 to the power of each
   m     :Map
    z3   :Floor divide by 3

Try it


7 byte version

õ_ou ì2

Try it

õ            :[1,input]
 _           :Pass each through a function
   o         :[0,current element)
    u        :Modulo 2 on above
      ì2     :Convert above from base-2 array to base-10

9 byte version

õ_îA¤w)n2

Try it

õ            :[1,input]
 _           :Pass each through a function
   A         :10
    ¤        :Convert to binary
     w       :Reverse
  î          :Repeat the above until it's length equals the current element
      )      :Close nested methods
       n2    :Convert from binary to base-10


1

MATL, 7 bytes

:&+oRXB

Try it online!

Explanation:

         % Implicitly grab input, n
:        % Range: 1 2 ... n

 &+      % Add the range to itself, transposed
         % 2 3 4 5 ...
         % 3 4 5 6 ...
         % 4 5 6 7 ...
         % 5 6 7 8 ...

   o     % Parity (or modulus 2)
         % 0 1 0 1 ...
         % 1 0 1 0 ...
         % 0 1 0 1 ...
         % 1 0 1 0 ...

    R    % Upper triangular matrix:
         % 0 1 0 1
         % 0 0 1 0
         % 0 0 0 1
         % 0 0 0 0

    XB   % Convert rows to decimal:
         % [5, 2, 1, 0]
         % Implicitly output

The output would be 0, 1, 2, 5 ... if P was added to the end (flip), making it 8 bytes.


1
Good idea, &+
Luis Mendo

1

Ruby -n, 32 30+1 bytes

Since we have exactly 1 line of input, $. is godly convenient!

EDIT: I'm amazed that I managed to outgolf myself, but it seems using -n which counts as 1 (by rule 2 in default special conditions, since Ruby can be run with ruby -e 'full program' (thus -n is 1) all instances of gets which is only used once can be golfed down 1 char this way; I believe this is a milestone for ruby, please speak up if you disagree with this train of thought before I repeatedly reuse it in the future)

v=0
?1.upto($_){p v=v*2|$.^=1}

Try it online!

Explanation

# while gets(); -- assumed by -n
v=0            # First element of the sequence
?1.upto($_){   # Do from "1" to "$LAST_READ_LINE" aka: Repeat [input] times
  p            # print expression
  v=v*2|$.^=1  # Next element is current element times two
               # bitwise-or 0 or 1 alternating
               # $. = lines of input read so far = 1 (initially)
}
# end           -- assumed by -n

Interesting. It's possible in 27 bytes, though.
Eric Duminil

1
Nice! Seems that we all got outgolfed by 26b though.
Unihedron

1

AWK a=0, 31 bytes

{for(;$1--;a=a*2+1-a%2)print a}

Try it online!

Uses the formula shamelessly stolen from this other Ruby answer.

While not having a=0 would work (awk treats "empty" as 0), the first element of 0 won't get printed and instead be an empty line, which while I would argue is a valid output probably won't pass, so there's a=0 which can be inserted as command line argument.


I like your formula ^^
Asone Tuhid


1

brainfuck, 40 bytes

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

Try it online!

0-indexed. Input as char code, output as unary with null bytes separating series of char code 1s. Assumes 8-bit cells unless you want to input over 255. Assumes negative cells, though this could be fixed at the expense of several bytes.

Previously, 50 bytes

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

Try it online!

Inputs as char code, outputs as char code. 1-indexed. Probably could be golfed a little.

@Unihedron points out I forgot to specify that this needs infinite sized cells, otherwise it tops out at the 8th number.


When I run it with `` (0d018) as par the test case, your code prints ` *UªUªUªUªUªUª` (0x01 02 05 0a 15 2a 55 aa 55 aa 55 aa 55 aa 55 aa 55 aa; 0d001 002 005 010 021 042 085 170 085 170 085 170 085 170 085 170 085 170) :( tio.run/##SypKzMxLK03O/…
Unihedron

Ok, seems it is a cell size problem. I think either your code should adapt to big integers or you need to specify the implementation that would run your code properly, but the default of 8-bit cells isn't enough
Unihedron

Forgot about that, thanks @Unihedron! I'll have a think about an 8-bit version, probably outputting in unary.
Jo King

Using an interpreter with 32-bit cells, it works. Though I think I might have a try at a bitinteger (8bit) version myself if you haven't by the weekend :D
Unihedron
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.