冗余布尔


19

介绍

传统上,布尔值是一位;truefalse10。前导零将是多余的。例如,001表示与相同000011

32位布尔

给定一个true / falsey值,将等效的32位布尔值作为字符串输出。(或作为数字,如果由于某种原因您的语言支持前导零。)

您的程序不必对每种真假类型都有效,而只需要对您的编程语言最有效。

示例输入/输出

Input >> Output

truthy >> 00000000000000000000000000000001
falsey >> 00000000000000000000000000000000

这是,因此最低字节获胜!


6
我们需要处理任何可能的true或false值,还是布尔值?
xnor

如果我的语言支持类型并且具有布尔值,我可以将1的(int)用作真实值吗?
LiefdeWen

@LiefdeWen当然
引力

1
不再重复,因为对于每个答案/语言,真实/虚假输入可以有所不同。
重力1998年

我不知道为什么,但是
-V. Courtois

Answers:



9

x86-16机器码(DOS),16个字节

B4 02          mov  ah,  2
B2 30          mov  dl, '0'
B9 1F 00       mov  cx, 31

            PrintZeros:
CD 21          int  0x21
E2 FC          loop PrintZeros

00 CA          add  dl, bl
CD 21          int  0x21
C3             ret

上面的函数在BL寄存器(的低字节)中接收一个布尔值(0 ==伪,1 ==真BX),并将“冗余布尔”字符串打印到标准输出。

它通过调用中断(0x21)进行DOS函数调用(通过设置AH为2进行选择)来工作,该函数将单个字符(输入DL)打印到标准输出中。

首先,将ASCII字符“ 0”装入DL,将计数器(CX)设置为31,然后循环打印“冗余”字节。然后,将输入布尔值添加到DL(如果BL为false,则添加0将DL保持BLASCII'0 '不变;如果为true,DL则将其递增为ASCII'1 '),并打印最后一个字节。

该函数不返回值。

对于一种不会真正使用字符串的语言来说,这相当不错。


完整程序,21字节

如果要使其成为完整程序,则仅需要5个字节。而不是将输入传递给寄存器,而是在调用应用程序时从命令行上传递的参数中读取输入。参数0解释为false,完全缺少参数也解释为false。大于0的参数将被解释为真实。

只需将以下代码汇编为COM程序,然后在命令行上执行即可。

B4 02            mov   ah,  2
B2 30            mov   dl, '0'
B9 1F 00         mov   cx, 31

               PrintZeros:
CD 21            int   0x21
E2 FC            loop  PrintZeros

3A 16 82 00      cmp   dl, BYTE PTR [0x82]  ; compare to 2nd arg, at offset 0x82 in PSP
D6               salc                       ; equivalent to sbb al, al
28 C2            sub   dl, al
CD 21            int   0x21
C3               ret                        ; you can simply 'ret' to end a COM program

样本输出:

C:\>bool.com
00000000000000000000000000000000
C:\>bool.com 0
00000000000000000000000000000000
C:\>bool.com 1
00000000000000000000000000000001 
C:\>bool.com 2
00000000000000000000000000000001
C:\>bool.com 7
00000000000000000000000000000001

它是如何工作的?好吧,这基本上是同一回事,直到您深入CMP说明为止。这会将命令行参数与DL寄存器的值(您记得,它包含ASCII'0')进行比较。在COM程序中,代码字节以偏移量0x100加载。之前是程序段前缀(PSP),其中包含有关DOS程序状态的信息。具体来说,在偏移量0x82处,您会找到在调用程序时在命令行上指定的第一个(实际上是第二个,因为第一个是空格)参数。因此,我们只是将此字节与ASCII'0'进行比较。

比较会设置这些标志,然后如果两个值相等,则该SALC指令(奔腾之前的未公开操作码,等效于sbb al, al,但只有1个字节而不是2个字节)将设置AL为0;如果两个值不同,则设置为-1。显然,当我们从减去ALDL,这将导致ASCII'0'或'1'适当。

(请注意,具有讽刺意味的是,如果在命令行中传递前导0的参数,则将其破坏,因为它仅查找第一个字符。因此01将被视为false。:-)



7

Javascript,23个字节

a=>'0'.repeat(31)+ +!!a

!!a 将a强制转换为布尔值,一元加号将其转换为int值。


a=>'0'.repeat(31)+(+a)短一个字节。
Kritixi Lithos'7

@Cowsquack无法在字符串,空数组,NaN,函数和其他值(其中强制转换为数字不会导致0或1)上失败
SuperStormer

还空对象,数组,无穷大和未定义
SuperStormer

1
...但现在...Your program doesn't have to work for every truthy/falsy type, only what your programming language work best for.
edc65

1
a=>'0'.repeat(31)+~~a确实使用true,false,1,0
edc65 '17

6

V,8字节

32é0Àñl

在线尝试!

说明:

32é0            " Insert 32 '0's
    Àñ          " Arg1 times...
      <C-a>     "   Increment the number under the cursor
           l    "   Move one char to the right. This will break the loop since there is 
                "   no more room on this line



4

ArnoldC,369字节

IT'S SHOWTIME
HEY CHRISTMAS TREE A
YOU SET US UP 0
GET YOUR ASS TO MARS A
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
BECAUSE I'M GOING TO SAY PLEASE A
TALK TO THE HAND "00000000000000000000000000000001"
BULLSHIT
TALK TO THE HAND "00000000000000000000000000000000"
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

在线尝试!


2
欢迎来到PPCG!
斯蒂芬,

4

Brainfuck61 60 36字节

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

我敢肯定,有一种聪明的方法可以使指针不走动太多。

我是对的。曾经有。感谢@Graviton给我这个主意!

下一步:更快地获得值32和48!

在线尝试!

++++        - Increment 1st slot by 4
[           - Loop until 4 becomes 0
    >++++   - Add 4 to 2nd slot
    <-      - Decrement loop
]           - At this point, we point to slot 1 and slot 2 contains 16, which is the Greatest Common Divisor of 48 (value 0 in ASCII) and 32 (final length of answer)
>           - Point to value 16 (slot 2)
[           - Start loop to get our target values 32 and 48
    >++     - Point to slot 3 and multiply 16 by 2 = 32
    >+++    - Point to slot 4 and multiply 16 by 3 = 48
    <<-     - Decrement the loop so that slot 2 becomes 0
]           - We now point slot 2
>-          - Move to slot 3 and remove one so we can spam (output) 31 zeroes
[           - Start outputting until slot 3 is empty
    >.      - Move to slot 4 where our ASCII value for 0 is
    <-      - Decrement the loop so that slot 3 becomes 0
]           - We are now at slot 3 and it is empty.
,.          - We can now gather input from the user and output it.

第一次高尔夫很有趣!

现在太晚了。我什至在做什么


多亏了熵,我将其缩短了1个字节,以得到16号。
RaphaëlCôté17年

只是为了好玩,这里有一个60字节的版本:(>-[-[-<]>>+<]>--<<-[>+<-----]>--->[-<.>],.输入为0或1)在线尝试!
Graviton

好吧,非常感谢@Graviton。您使我意识到,在我不得不将ASCII值降至0时,我付出了太多的努力。
拉斐尔·科特

3

Scala,32个字节

抱歉,我被迫用32个字节来完成它> _ <

var s=t
for(u<-0 to 30)s="0"+s
s

它被一个以t参数为函数的函数包围(因为string对于伪造的或真实的,可以为“ 0”或“ 1”),然后s将其返回。

在线尝试!

有效响应:Scala,46个字节

与我的Java响应相同,我应该为参数采用布尔值。所以:

var s=if(t)"1"else"0"
for(u<-0 to 30)s="0"+s
s

在线尝试!


3

Braingolf10 8字节

#␟>[0_]N

在线尝试!

是一个单位分隔符,ASCII 0x1F或31。找不到要粘贴到TIO中的实际字符,因此TIO改为使用# 1-,这会将空格(32)减为31。

说明

#␟>[0_]N  Implicit input from commandline args
#␟        Push unit separator (31)
   >       Move top item to bottom of stack
    [..]   Loop, runs 31 times
     0_    Print 0
        N  Boolean conversion, truthy values become 1, falsey values become 0
           Implicit output of top of stack

这是tio链接,其中包含0x1F字符TIO
PunPun1000

@ PunPun1000哦,谢谢!我将更新帖子
Skidsdev '17

2

八度,23字节

@(x)[48+[!(1:31),x],'']

在线尝试!

这比我尝试过的所有方法都短printf。不过,由于我是在手机上这样做的,所以我可能会错过一些东西。

只有一个字节长

@(x)[dec2bin(0,31),x+48]

如果我可以将1/0作为字符串,则可能是18个字节。

@(x)[48+!(1:31),x]

在线尝试!




2

Ruby,21个字节

是的,那个空间需要在那儿..:/

->x{"%032b"%(x ?1:0)}

在Ruby中的一切,除了falsenil是truthy; 在线尝试!






1

C,26个字节

1bluestone解决方案几乎相同的想法,但是在C中它更短,并且对于任何整数输入都可以正常工作:

f(a){printf("%032i",!!a);}

当然,正如所有好的C-golf答案一样,它包括一些隐式类型的变量/函数... !!运算符是将任何真实值转换为1C 的最短方法(通过双重否定,!定义为返回1或)。0).

测试:

#include <stdio.h>
f(a){printf("%032i",!!a);}
int main() {
    f(0), printf("\n");
    f(1), printf("\n");
    f(2), printf("\n");
    f(-1), printf("\n");
}


1

PHP, 28 bytes

<?=str_pad($argv[1],32,0,0);

Save as bool.php and run:

$ php bool.php 0
00000000000000000000000000000000
$ php bool.php 1
00000000000000000000000000000001

3 bytes shorter: printf('%032d',$argv[1]); (requires the -r flag).
user63956

1

Ly, 20 15 13 bytes

65*1+[0u1-]nu

EDIT: Saved 5 bytes thanks to ovs.
EDIT: Saved another 2 bytes by printing 0 as a number rather than a character.


Would 65*1+["0"o1-]nu work?
ovs

1

Octave,16 11 bytes

@(x)x(1:32)

Try it online!

A function handle that takes "00000000000000000000000000000001" as truthy and "00000000000000000000000000000000\0" as falsey.

Explanation:

In Octave an array is considered as falsey if at least one of its elements is zero. The 33th element of the second string is a character with the ASCII value of 0 so it can be considered as falsey.


1

Java, 40 chars, 40 bytes

This takes string as parameter, which is not correct (falsy/truthy java value is forced by OP to be represented by a boolean).

c->{for(int i=0;++i<32;c=0+c);return c;}

Try It Online!

Valid response : Java, 60 chars, 60 bytes

c->{String k="";for(k+=c?1:0;k.length()<32;k=0+k);return k;}

Try It Online!

I know there is already a Java answer which is shorter than this one, but still :)


Yes, the return statement is part of your code, so part of your byte-count. But your answer doesn't fulfill the rules: you must get a boolean as input. "Truthy/falsy" is translated in Java as either true or false, and nothing else. So you can't get a String as input parameter.
Olivier Grégoire

I see. I'll modify it soon enough. Thanks.
V. Courtois

1
You don't need to put the final semicolon (;). Also, you can shorten your code like this: c->{String k="";for(;k.length()<31;)k+=0;return k+=c?1:0;}. The k+=c?1:0 is to shorten k+(c?1:0).
Olivier Grégoire

@OlivierGrégoire Thanks but why isn't the final semicolon mandatory?
V. Courtois

1
It is mandatory, in the code, but not in the snippet. In the TIO, the footer can simply start with ;. A statement requires a semicolon. A lambda is not a statement.
Olivier Grégoire

1

Japt, 13 11 bytes

?1:0 ¤i31ç0

Explanation:

?1:0 ¤i31ç0
?              // If the input is a truthy, return:
 1             //   1
  :0           //   Else, 0
     ¤         // Convert to a base-2 string
      i        // Insert at index 0:
       31ç0    //   A string filled with 0s, length 31

Saved a byte using a base-2 conversion built-in!

To insert the string of 0s in front of the 1/0, I need to cast the 1 and 0 into a string. The typical way of doing that would be 1s  (3 bytes). But because we're only converting 1s and 0s, I can use the base-2 built-in (2 bytes).


Input can be in the form of an integer or string.

0 and "" are falsy in Japt.

Try it online!

Test suite


1

C# (.NET Core), 29 bytes

a=>new string('0',31)+(a?1:0)

OP said 1/0 can be used for truthy/falsey, so can make a an int and it becomes

a=>new string('0',31)+a

C# doesn't really have truthy/falsey though so I will not use this answer.

Try it online!


1
I don't think the second one is valid. Integers are neither truthy nor falsey in C#, only bools are.
Skidsdev

@Mayube I did ask and OP said its okay, but I kinda agree with you so will edit.
LiefdeWen

1
Annoyingly Padleft comes in at the same byte count here.
TheLethalCoder

@TheLethalCoder Started with PadLeft as well :)
LiefdeWen

2
Not sure if this is possible, but interpolated strings can be quite useful here: b=>$"{(b?1:0):D32}" 19 bytes
auhmaan

1

MY, 10 9 bytes

𝕫BṄiℑpέ←←

Try it online!

Explanation (codepage [with reasoning behind the character]/hex code):

𝕫: 1A - Push an integer from STDIN (lowercase integers)
B: 0B - Push 11 (B is 11 in hex)
Ṅ: 36 - Pop n; push the nth prime, 11th prime is 31 (Ṅ-th)
i: 49 - Pop n; push [1,...,n] (index/iota)
ℑ: 34 - Pop n; push imag(n) (ℑmaginary part, applied to each element, which gives 0 for real numbers)
p: 60 - Pop n; push stringified n (0=>"0" ... 35=>"Z", the b in base upside down)
έ: 56 - Pop n; push n joined by "" (έmpty string)
←: 26 - Pop n; output n with no newline (out←in)
←: 26 - Pop n; output n with no newline (out←in)

I can't believe that this is possible without any two-argument commands whatsoever!

Edit: Saved 1 byte by using primes instead of arithmetic to get 31.


0

APL, 11 bytes

⍕¯32↑1↑1\⍨⊢

How?

1\⍨⊢ - repeat 1 input times - return empty array on falsy value

1↑ - take the first item

¯32↑ - align right with 31 zeros

- format as string


Simply ⍕¯32↑⊢ should work
Kritixi Lithos

1
@Cowsquack & Uriel Neither works as they include spaces. You need ∊⍕¨¯32↑⎕ or something.
Adám

0

J, 11 bytes

(31#'0'),":

Try it online!

how?

31 zeros
00...000  append     turn the 0 or 1 input into string
(31#'0')    ,       ":

note: in J, booleans are 0 or 1, also known as "the iverson convention," after ken iverson, creator of J and APL


I understand that 1 and 0 are booleans in J, but you're just appending the input to 31 0s. Shouldn't there be some form of boolean validation?
Oliver

@Oliver The problem specifies "Given a truthy/falsey value..." so no, I don't think you should be validating... Also, note that ": is required for this to work -- it changes a boolean to a string.
Jonah
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.