二进制二进制小数计数


19

挑战在于将零到10(含零)的数字输出到您的终端,窗口,画布或屏幕。每个输出的数字必须显示为4位宽的半字节,因此零必须显示为0000,依此类推。

您可以使用空格,逗号或回车符分隔输出的每个数字。最小的解决方案获胜,但是只要序列中没有重复的数字,数字就可以按照您喜欢的任何顺序显示。

如果不可能用逗号或空格输出(例如,标准输出仅限于二进制,或者您的解决方案是用于较早的计算机套件),则使用低级二进制语言的条目无需担心逗号或空格分隔符例如具有受限数字显示的KIM-1)。


是的,在您选择的语言中,空格,逗号,逗号然后是空格或等价的“ \ r \ n”。
Shaun Bebbers

抱歉,这看起来像是4个单独的零数字,而不是4位宽的二进制数。
Shaun Bebbers

并不是我真的确定要写这样的答案,但是除了11个必需的半字节以外,还可以输出一些其他半字节吗?
Arnauld

2
他们是蚕食,不是蚕食。
0WJYxW9FMN

不符合Commodore 64程序员参考指南的要求
Shaun Bebbers

Answers:


2

SmileBASIC,26个字节

FOR I=0TO&HA?BIN$(I,4)NEXT

15

MATL,6个字节

0:10YB

MATL Online上尝试

说明

0:10    % Create the array [0...10]
YB      % Convert this array to a binary string where each number is 
        % placed on a new row
        % Implicitly display the result


13

JavaScript,46个字节

for(i=15;i++<26;)alert(i.toString(2).slice(1))

当您只需在每个数字上加16并切下第一个二进制数字时,为什么要使用填充功能?


9

Japt,7个字节

GôA,_¤Å

在这里,我认为Japt注定要比其他所有高尔夫语言都要长...

在线测试!

说明

GôA,_¤Å  // Implicit: A = 10, G = 16
GôA      // Create the inclusive range [G...G+A].
    _    // Map each item Z to Z
     ¤   //   .toString(2)
      Å  //   .slice(1).
         // Implicit: output result of last expression

通常情况下逗号可以Japt被删除,但是这一次是因为有一个错误的:_正常手段function(Z){Z,但由于某些原因,编译器认为A_手段function(A,Z){Z


好一个。我被困在Aô_¤
Oliver


7

Bash + Unix实用程序,29 26字节

dc -e2o8927II^*8/p|fold -4

在线尝试!

这与@ DigitalTrauma / @ Dennis解决方案的长度相同,但是使用了完全不同的方法。

输出为:

1010
0010
0110
0001
1001
0101
0100
0111
0011
1000
0000

(允许任何订单。)


Bash,34个字节

echo 0{0,1}{0,1}{0,1} 10{00,01,10}

在线尝试纯Bash版本!

输出为:

0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010

7

J,6个字节

#:i.11

感谢Miles将其缩减为6个字节!


#:i.11应该也一样工作
英里

根据目前已删除评论的答案,我不确定这是否有效。
亚当

@Adám我看不到。您能解释一下为什么不成功吗?
封锁

因为它会生成一个×4布尔数组,该数组将以数字形式打印,中间有空格。但是该评论似乎暗示二进制数字中不允许有空格。
亚当

6

果冻,7 个字节

2Bṗ4ṫ6Y

在线尝试!

(如果允许半字节的尾部行,则为5个字节,2Bṗ4Y

怎么样?

按降序打印。

2Bṗ4ṫ6Y - Main link, no arguments
2B      - 2 converted to binary -> [1,0]
  ṗ4    - Cartesian 4th power -> [[1,1,1,1], [1,1,1,0], ..., [0,0,0,0]]
                            i.e.  16       , 15         ..., 0
    ṫ6  - tail from 6th item  -> [[1,0,1,0], [1,0,0,1], ..., [0,0,0,0]]
                            i.e.  10       , 9        , ..., 0
      Y - join with line feeds
        - implicit print

一种替代7- byter是2ṗ4Ịṫ6Y,所述[1,0]被替换[1,2]并且是“是微不足道的”单子(abs(z)<=1),转换2s到0秒。


6

蟒3.6,36 35个字节

i=11
while i:i-=1;print(f"{i:04b}")

-1字节感谢@JonathanAllan

Python 3.5及更早版本:

i=11
while i:i-=1;print("{:04b}".format(i))

在线尝试!


1
i=11(新行)while i:i-=1;print(f"{i:04b}"),用于35。–
乔纳森·艾伦


4

CJam,12个字节

B{G+2b1>}%N*

在线尝试!

说明

笛卡尔幂方法本来是我的选择,但已被采用。

因此,这会生成从0到10的数字,并且每个数字都会加上16,然后转换为二进制。加16可以确保生成所需的前导零,并删除多余的前导零。

B             e# Push 11
 {      }%    e# Map over "11", implicitly converted to the array [0 1 ... 10]
  G+          e# Add 16. This makes sure there will be 5 binary digits: a leading 1
              e# which will have to be removed and the remaining, valid digits
    2b        e# Convert to array of binary digits
      1>      e# Remove first digit
          N*  e# Join by newlines. Implicitly converts arrays to strings


3

果冻10%,9,8个字节

⁴r26BḊ€Y

在线尝试!

我的果冻不怎么好,所以我会接受任何提示!

这使用了Emigna的第一个算法


感谢Dennis减少了两个字节,这使我可以自己回答。:P

说明:

      Ḋ€    # Return all but the first element of each item in the list:
⁴r26        #   [16, 17, 18, ... 26]
     B      #   Converted to binary
        Y   # And joined with newlines

Ḋ€ saves a byte.
Dennis

@Dennis Ah, that makes sense. Thanks!
DJMcMayhem

⁴r27 saves another one.
Dennis


2

Jelly, 8 bytes

2Ḷṗ4ḣ11Y

Try it online!

How it works

2Ḷṗ4ḣ11Y  Main link.

2Ḷ        Unlength 2; yield [0, 1].
  ṗ4      Take the fourth Cartesian power.
    ḣ11   Head 11; discard all but the first eleven elements.
       Y  Join, separating by linefeeds.

2

RProgN, 15 Bytes

~16.aL1{2B26q}:

This has been a very good modivation to add a pad function. The entirety of ]L4\-'0'\m\., more than half the code, is to pad.

_Saved 6 bytes thanks to @ETHProductions, that's the pad function cut in half.

Explained

~16.aL1{2B26q}:
~               # Zero Space Segment
 16.            # The literal number 16
    aL          # The length of the Alphabet
      1         # The literal number 1
       {     }: # For each number between 16 and 26 inclusive
        2B      # Convert to base 2
          26q   # Get the characters between 2 and 6 inclusive.

Try it online!


length of the Alphabet Nice way to save a byte ;-)
ETHproductions

2

Retina, 36 33 bytes


%%%%
+`(^|\b)%
0$%'¶$%`1
11!`\d+

Try it online!

Explanation


%%%%

Replace the empty (non-existent) input with %%%%.

+`(^|\b)%
0$%'¶$%`1

On the first run of this stage, it will match ^% and essentially replace the text %%%% with the two lines 0%%% and 1%%%. The stage will loop until the output stops changing. On the second run, it will match \b% (since digits count as word characters and % doesn't), and replace the groups by duplicating them and adding 0 to one copy and 1 to the other: 0%%% becomes the lines 00%% and 01%% (and the same sort of thing for 1%%%). Through this loop all 16 bitstrings will be produced, linefeed separated.

11!`\d+

The first 11 matches of \d+ (a run of at least 1 digit) are retrieved. The matches are output in a linefeed-separated list.


I'm curious in understanding how this 0$%'¶$%1` line works. What do $%, `1, represent?
Kritixi Lithos

@KritixiLithos Sorry I didn't explain the specifics, it's a bit convoluted :P. $%` represents everything before the match on the same line, and $%' is everything after the match on the same line. is a literal linefeed. So basically the replacement matches the first % on a line and replaces it with 0 plus the rest of the line it was on, a newline, the beginning of the line it was on, and a 1. Of course, the beginning and end of the line it was on are untouched by the replacement because they weren't part of the match.
Business Cat

So it's not putting a copy of the line after itself, but rather inserting the end of the line, a newline, and the beginning of the line in between the beginning and end of the line that remain intact.
Business Cat

Ah thanks, that was helpful :) (I'm trying to learn Retina now)
Kritixi Lithos

In which case, I think you can use G11` as the last line of the regex instead
Kritixi Lithos

2

Ruby, 25 bytes

11.times{|n|puts"%04b"%n}

2

BF, 121 101 bytes

,....>,.<...+.>.<-..+.-.>.<..+..>.<-.+.-..>.<.+.-.+.>.<-.+..-.>.<.+...>.<.-...>.<+.-..+.>.<.-.+.-.!0

Requires a trailing newline. Makes use of ! symbol (so, check the box that says !) with this interpreter (try it online!).

Potentially 51 bytes if each operator was considered as 4 bits


You should specify (or additionally add a byte) for the ! checkbox being enabled.
Conor O'Brien

Whoops, I'm new to that and thought it encoded it in the URL. Will specify... wait, actually, I think it's already specified in the second sentence (?), will clarify that a bit
Timtech

2

C#, 96 bytes


Golfed

()=>{for(int i=0;i++<11;)System.Console.WriteLine(System.Convert.ToString(i,2).PadLeft(4,'0'));}

Ungolfed

() => {
    for( int i = 0; i++ < 1; )
        System.Console.WriteLine( System.Convert.ToString( i, 2 ).PadLeft( 4, '0' ) );
}

Full code

using System;

namespace Namespace {
    class Program {
        static void Main( string[] args ) {
            m();

            Console.ReadLine();
        }

        static void m() {
            for( Int32 i = 0; i++ < 11; )
                Console.WriteLine(
                    Convert.ToString( i, 2 ). // Converts the number to binary code
                    PadLeft( 4, '0' ) );      // Fills the number with the missing '0's
        }
    }
}

Releases

  • v1.0 - 96 bytes - Initial solution.

I like the release version you added - are you going to include RC versions as well? \o/
Shaun Bebbers

1
Going to be honest, don't know what RC means... This is how I try to post my solutions in PPCG
auhmaan

RC means 'Release Candidate' - i.e., you'd send out a few versions with minor differences and await to see which is the most stable by your RC number. So if you had version A and version B, you could have v1.0-RCa and v1.0-RCb or something.
Shaun Bebbers

1
Oh, that. No. If I make another release, I increment the Version Number right away.
auhmaan

2

C 170 120 bytes

n,i,m,k[4]={0};f(){for(m=0;m<=10;m++){n=m;i=0;for(;n;i++){k[i]=n;n/=2;}for(i=4;i>0;i--)printf("%d",k[i-1]%2);puts("");}}

Ungolfed version:

void f()
{
    int n,i,m,k[4]={0};


   for(m=0;m<=10;m++)
   {
      n=m;
      i=0;

      for(;n;i++)
      {
         k[i]=n;
         n/=2;
      }  
      for(i=4;i>0;i--)
         printf("%d",k[i-1]%2);

      puts("");        
   }
}

Can definitely be shortened!?

@Ahemone Awesome idea, Thanks!

Should work now! Try it online!


the first for loop in your golfed version should go to 4 rather than 3, but that doesn't matter because the loop can be eliminated entirely and the second for loop can start from 0. You can also just use while(n), but compacting the while loop down into a for loop saves more again. n/=2 will also save you a byte over the shift. You're also missing a terminating } on the golfed version causing an error on compilation.
Ahemone

@Ahemone Fixed the } and improved the code, 50 bytes shorter based on your idea.
Abel Tom


2

R - 23

We can use intToBin function from the R.utils package:

R.utils::intToBin(0:10)

[1] "0000" "0001" "0010" "0011" "0100" "0101" "0110" "0111" "1000" "1001" "1010"

2

C, 75 68 69 bytes

Approach 1: 75 73 74 bytes

m;p(i){putchar(i?m&i?49:48:9);}r(){for(m=11;m--;p(4),p(2),p(1),p(0))p(8);}

Try it online!


Approach 2: 68 69 bytes

m,n,o;f(){for(m=11;m--;)for(n=m,o=5;o--;n*=2)putchar(o?n&8?49:48:9);}

Try it online!


Suggest m,n;f(o) instead of m,n,o;f()
ceilingcat

1

Python 2, 44 bytes

for x in range(11):print bin(x)[2:].zfill(4)

This uses the zfill function which works like rjust except it always padds with 0 so you don't waste bytes on an argument.


Wait what, this whole time I've been wasting bytes making my own padding function? (lambda k,l:' '*(len(k)-l)+k) Wow... +1 just because of this :D
HyperNeutrino



1

stacked, 30 bytes

11:>[2 baserep'0'4 pad out]map

Try it online!

11:> is a range from 0 to 10. The rest is rather self-explanatory.

Other solutions that I've found:

11:>[bits 4 dpad''join out]map
11:>[bits 4 dpad$tostrmap]map out
11~>15+[bits behead''join out]map
16 26|>[bits behead''join out]map

1

Ruby, 38 bytes

11.times{|i|puts i.to_s(2).rjust 4,?0}

-1 byte by getting rid of the parentheses: 11.times{|i|puts i.to_s(2).rjust 4,?0}
Conor O'Brien

1

BF, 134 bytes

I'm sure this can be shortened--it's pretty much my first BF golf.

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

Try it online! Assumes a tape infinite in both directions, like the interpreter at TIO uses. An interpreter where < at the left end of the tape is a no-op would save three bytes.

Explanation

More than half of the code (the first 77 bytes, to be precise) is spent initializing the tape. The steps go like this:

++++++++++
10|

[>+>+>+++++>>>+++++>>>+++++>>>+++++[<<<]>>>-]
 0|10|10|50| 0| 0|50| 0| 0|50| 0| 0|50|

>>+>[-->>+>]<<<[<<<]>>
 0|10|11|48| 0| 1|48| 0| 1|48| 0| 1|48| 0| 1|

The cells initialized to 1 store the bits of our number plus 1: 1 represents a zero bit and 2 represents a one bit.

The initialization phase ended with the pointer on the 11. Now we use this cell to run 11 iterations of our loop:

[>          Move to the first 48
 [>>-       While we're still on a 48, move 2 cells over and decrement
  [         The cell's value now equals the bit it represents; if it's not 0:
   <<+.-    Move to the 48, increment, output, and decrement again
   >        Move to the next cell, which holds a 0
  ]         Leave the loop
  <[>]>     Pointer shenanigans to get back on the cell representing the bit
  -         Decrement again: cell is 255 for a zero bit, 0 for a one bit
  [         If cell is not 0:
   <<.>     Move to the 48, output, and move to the 0 cell
  ]
  <[>]>++   Get back on the bit's cell; increment back to original value
  >         Move to the next 48
 ]          Loop exits once we've output all four bits
            Now we increment the binary number: a one bit turns into a zero bit and
            carries; a zero bit turns into a one bit and doesn't carry
 <-         Move back to the rightmost bit cell and decrement
 [          If it is not 0, it must represent a one
  <<<-      Leave it decremented, go to the next bit cell and decrement it too
 ]          Loop exits on a bit cell that represented a zero
 ++         Increment it twice (to represent a one)
 <<[<<<]    Move back to first cell on tape
 >.         Move to 10 cell and output (newline)
 >-         Move to loop counter cell and decrement
]
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.