Bit yüzer dizisi


22

Biraz gelen yüzen LSB için MSB bir pozisyon bu yüzen kadar her zaman hareket eden üst kabın:

0000
0001
0010
0100
1000

Bir bit en üste geldiğinde, başka bir bit yolculuğuna başlar ve diğer bit ile karşılaştığında durur:

1001
1010
1100

Bu, kap bitlerle doluncaya kadar olur:

1101
1110
1111

Meydan okuma

Bir tamsayı numarası verildiğinde , bu sayıda bit içeren bir kapsayıcı için " Bit yüzer dizisi " verilir.

  • Dizinin her terimi, seçtiğiniz herhangi bir ayırıcı ile ayrılabilir.
  • Düzenleme : Sıra, ilk termo: dan başlayarak ondalık sayı olarak gösterilmelidir 0.
  • Kap boyutu, sıfırdan büyük ve seçtiğiniz dilin sahip olduğu en büyük tamsayının bit sayısına kadar olabilir. Girişin her zaman bu gereksinime uyduğunu varsayabilirsiniz.

Örnekler

Sadece sayısal dizi gereklidir, ikili gösterimler örnek olarak gösterilmiştir:

  • For 1 :0 1

    0 -> 0
    1 -> 1
    
  • İçin 3 :0 1 2 4 5 6 7

    000 -> 0
    001 -> 1
    010 -> 2
    100 -> 4
    101 -> 5
    110 -> 6
    111 -> 7
    
  • İçin 4 :0 1 2 4 8 9 10 12 13 14 15

    0000 -> 0
    0001 -> 1
    0010 -> 2
    0100 -> 4
    1000 -> 8
    1001 -> 9
    1010 -> 10
    1100 -> 12
    1101 -> 13
    1110 -> 14
    1111 -> 15
    
  • İçin 8 :0 1 2 4 8 16 32 64 128 129 130 132 136 144 160 192 193 194 196 200 208 224 225 226 228 232 240 241 242 244 248 249 250 252 253 254 255

    00000000 -> 0
    00000001 -> 1
    00000010 -> 2
    00000100 -> 4
    00001000 -> 8
    …
    …
    …
    11111000 -> 248
    11111001 -> 249
    11111010 -> 250
    11111100 -> 252
    11111101 -> 253
    11111110 -> 254
    11111111 -> 255
    

2
Diziyi herhangi bir sırayla (yani tersine çevrilmiş) çıkartabilir miyiz, yoksa en alttan en yükseğe doğru sıralanmaları gerekir mi?
Kevin Cruijssen

1
Yüzer olarak çıktı alabilir miyiz? Örn[0.0, 1.0]
Grimmy

8
İkili gösterimi kullanarak çıktı alabilir miyiz?
Neil

Sıfır dizinli diziyi çıkartabilir miyiz? yani0 -> [0, 1]
attinat

Yanıtlar:


7

05AB1E , 10 bayt

LRL˜Íoî.¥ï

Çevrimiçi deneyin!

L                 # range [1..input]
 R                # reversed
  L               # convert each to a range: [[1..input], [1..input-1], ..., [1]]
   ˜              # flatten
    Í             # subtract 2 from each
     o            # 2**each
      î           # round up (returns a float)
       ï          # convert to integer
        .¥        # undelta

2
.0Tamsayılar için varsayılan olarak kayan noktalara izin veren bir meta-posta olduğunu düşünüyorum , ancak emin değilim. Şahsen ben genellikle ïgüzel baskı için altbilgi koymak ve bayt sayısına dahil etmeyin.
Kevin Cruijssen

7

Python 2,45 bayt

y=n=2**input()
while y:print n-y;y=y&y-1or~-y

Çevrimiçi deneyin!

2**nGirdi sırasındaki her terim eksi oluşturmak için kısa çıkıyor n. İkilik genişlemelerine bakarsak, aşağıda, ikili genişlemelerde n=51'lerin üçgenlerinin güzel bir modelini görüyoruz.

100000  32
011111  31
011110  30
011100  28
011000  24
010000  16
001111  15
001110  14
001100  12
001000  8
000111  7
000110  6
000100  4
000011  3
000010  2
000001  1

Her sayı, bir önceki sayıdan ikili genişlemede en sağ olanı kaldırılarak elde edilir, bunun 0 sayısını yapması dışında, bunun yerine 1'i çıkartacağız, bunun yerine yeni küçük bir üçgeni başlatan 1'lerin yeni bir blokunu oluşturabiliriz. Bu, en sağdaki 1'i kaldırmak için bir püf noktası y=y&y-1or~-yolduğu gibi uygulanır y&y-1ve bunun yerine bu değer 0 ise or~-yverir y-1.

Python 2,49 bayt

def f(n,x=0):1%n;print x;f(n-x%2,x+(x%2**n or 1))

Çevrimiçi deneyin!

Hatalı sonlanan, yazdıran bir işlev. Aşağıdaki daha güzel program daha uzun sürdü.

51 bayt

n=input()
x=0
while n:n-=x%2;print x;x+=x%2**n or 1

Çevrimiçi deneyin!


6

Jöle , 11 10 bayt

RUḶ’F2*ĊÄŻ

Liman içinde @Grimy 'ın 05AB1E cevap , çok emin onu upvote olun! @Grimy
sayesinde -1 bayt .

Çevrimiçi deneyin.

Açıklama:

R           # Create a list in the range [1, (implicit) argument]
 U          # Reverse it to [argument, 1]
           # Create an inner list in the range [0, N) for each value N in this list
           # Decrease each by 1
    F       # Flatten the list of lists
     2*     # Take 2 to the power each
       Ċ    # Ceil
        Ä   # Undelta (cumulative sum) the list
         Ż  # And add a leading 0
            # (after which the result is output implicitly)

2
R_2-> Ḷ’-1. olduğu tek mantıklı aralığı Gerçekten 05AB1E bunun için tek Byter olsaydı.
Grimmy

@ Grimy Ah, bunu nasıl özledim? Menzili aradım ve atlamış olmalıyım bir şekilde geçti ..>.> Teşekkürler!
Kevin Cruijssen

4

Perl 5 ( -n), 41 40 bayt

Xcali'ye -1 bayt

map{/01.*1/||say oct}glob"0b"."{0,1}"x$_

TIO

  • "{0,1}"x$_: dize "{0,1}"n kere tekrarlandı
  • "0b". : birleştirmek "0b"
  • glob : glob genleşmesi (kartezyen ürün)
  • map{... }: her eleman için
  • /01.*1/||: bir 01şey tarafından takip edildiğinde atlamak için1
  • say oct : ondalık dönüştürmek ve söylemek


4

JavaScript (ES6), 43 bayt

Şüphe durumunda, xnor yöntemini kullanın .

n=>(g=x=>x?[n-x,...g(x&--x||x)]:[])(n=1<<n)

Çevrimiçi deneyin!


JavaScript (ES6),  59 57 55  52 bayt

f=(n,x=0)=>x>>n?[]:[x,...f(n,x+=x+(x&=-x)>>n|!x||x)]

Çevrimiçi deneyin!

Nasıl?

Biz tanımlarız p(x) en yüksek gücü olarak 2 bölen x, ile p(0)=0 Kongre tarafından.

Bu fonksiyon bit bit basit bir AND ile gerçekleştirilebilir. x ve -x olarak ayarlanan en düşük biti izole etmek için 1 içinde x. Örneğin:

p(52)=52VE-52=4

kullanma p, sekans birn olarak tanımlanabilir birn(0)=0 ve:

an(k+1)={an(k)+p(an(k)),if p(an(k))0 and an(k)+p(an(k))<2nan(k)+1,otherwise

Commented

f = (                   // f is a recursive function taking:
  n,                    //   n = input
  x = 0                 //   x = current term of the sequence
) =>                    //
  x >> n ?              // if x is greater than or equal to 2**n:
    []                  //   stop recursion
  :                     // else:
    [                   //   update the sequence:
      x,                //     append the current term to the sequence
      ...f(             //     do a recursive call:
        n,              //       pass n unchanged
        x +=            //       update x:
          x + (x &= -x) //         given x' = lowest bit of x set to 1:
          >> n          //         if x + x' is greater than or equal to 2**n
          | !x          //         or x' is equal to 0: add 1 to x
          || x          //         otherwise, add x' to x
      )                 //     end of recursive call
    ]                   //   end of sequence update


3

Perl 6, 43 bytes

{0 x$_,{say :2($_);S/(0)1|0$/1$0/}...1 x$_}

Try it online!

Anonymous code block that takes a number and outputs the sequence separated by newlines. This works by starting with 0 repeated n times then replacing either 01 with 10 or the last 0 with a 1 until the number is just ones.

Or 40 bytes, using Nahuel Fouilleul's approach

{grep /010*1/|{say :2($_)},[X~] ^2 xx$_}

Try it online!


"then replacing either 01 with 10 or the last 0 with a 1 until the number is just ones" That's a genius move!
PaperBirdMaster





2

05AB1E, 13 12 bytes

Tsãʒ1ÛSO2‹}C{

-1 byte thanks to @Grimy (also take a look at his shorter approach here).

Try it online or verify all test cases.

Explanation:

T             # Push 10
 sã           # Swap to get the (implicit) input, and get the cartesian product with "10"
   ʒ          # Filter it by:
    1Û        #  Remove leading 1s
      SO      #  Get the sum of the remaining digits
        !     #  Check that the sum is either 0 or 1 by taking the factorial
              #  (NOTE: Only 1 is truthy in 05AB1E)
         }C   # After the filter: convert all remaining strings from binary to integer
           {  # And sort (reverse) them
              # (after which the result is output implicitly)

Alternate 13: oL<ʒbIj1Û1¢2‹. Doesn't look like I can get it lower.
Grimmy

1
@Grimy I just had oL<ʒbIj1ÛSO2‹ and was trying to see where my error was. :) But I'm glad to see you aren't able to find a shorter version for one of my answers for a change. ;p (inb4 you find a shorter one after all xD)
Kevin Cruijssen

1
@Grimy I have the feeling SO2‹ can be 3 bytes somehow perhaps, but I'm not seeing it and also not entirely sure.. There are some alternatives, like SO1~ or SÆ>d, but I'm unable to find a 3-byter.
Kevin Cruijssen

1
10 with a completely different approach
Grimmy

1
Your feeling was right, I just found a 3-byter: SO!. Pretty sure I have some old answers using 2‹ that could benefit from this as well.
Grimmy

2

Retina, 26 bytes

.+
*0
L$w`.(.*)
$.`*1$'1$1

Try it online! Outputs in binary. If that's not acceptable, then for 39 bytes:

.+
*0
L$w`.(.*)
$.`*1$'1$1
+`10
011
%`1

Try it online! Explanation:

.+
*0

Convert the input into a string of n zeros.

L$w`.(.*)

Match all possible non-empty substrings.

$.`*1$'1$1

For each substring, output: the prefix with 0s changed to 1s; the suffix; the match with the initial 0 changed to 1.

+`10
011
%`1

Convert from binary to decimal.



1

Charcoal, 19 bytes

I⮌E⊕θEι⁺⁻X²IθX²ιX²λ

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

    θ               Input
   ⊕                Incremented
  E                 Map over implicit range
      ι             Outer index
     E              Map over implicit range
           Iθ       Input cast to integer
               ι    Outer index
                  λ Inner index
         X²  X² X²  Power of 2
       ⁺⁻           Subtract and add
 ⮌                  Reverse outer list
I                   Cast to string
                    Implicitly print


1

Retina, 24 bytes

.+
*0
/0/+<0`(0)1|0$
1$1

Outputs in binary. Input should have a trailing newline.

Attempt at explanation:

.+              #match the entire input
*0              #replace it with that many zeroes
/0/+<0`(0)1|0$  #while the string has a 0, substitute the first match and output
1$1             #if 01 is present in the string, replace it with 10, else replace the last character with $

I tried to avoid the 3 bytes long /0/ regex option by rearranging the options, but couldn't.

Try it online!


I don't think outputting in binary is allowed. There's a comment asking if it is allowed, but it's better to assume that you can't until the asker replies
Jo King

1

C (clang), 73 bytes

o,j,y;f(x){for(o=j=0;printf("%d ",o),x;o+=y+!y,y+=y+!y)j=!j?y=0,--x:--j;}

Try it online!

for(o=j=0;printf("%d ",o),x;  o+=y+!y, y+=y+!y) 
// adds 1, 1+1=>2 , 2+2=> 4 .... sequence

 j=!j?y=0,--x:--j; 
// uses ternary instead of nested loop to decrement 'x' when 'j' go to 0

1

k4, 28 24 bytes

0,+\"j"$2 xexp,/-1+|,\!:

@Grimy's approach ported to k4

edit: -4 thanks to ngn!


1
!:'1+|!: -> |,\!:
ngn

you can remove the space after xexp
ngn

@ngn, agh |,\!: seems so obvious now that i see it!
scrawl
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.