Tất cả các ký tự ASCII với số bit đã cho


30

(Tiêu đề với lời cảm ơn đến @ChasBrown)

Hộp cát

Bối cảnh

Thử thách này được lấy cảm hứng từ một câu hỏi mà tôi mới đăng trên Puzzling Stack Exchange . Xin vui lòng theo liên kết nếu bạn quan tâm đến câu hỏi ban đầu. Nếu không thì tôi sẽ không làm bạn nhàm chán với các chi tiết ở đây.

Sự thật

Mỗi ký tự ASCII tiêu chuẩn có thể in có giá trị thập phân trong khoảng từ 32 đến 126. Chúng có thể được chuyển đổi thành số nhị phân tương ứng của chúng trong phạm vi bao gồm 100000 đến 1111110. Khi bạn tính tổng các bit của các số nhị phân này, bạn sẽ luôn luôn có một số nguyên nằm trong khoảng từ 1 đến 6.

Các thách thức

Cho một số nguyên nằm trong khoảng từ 1 đến 6, bao gồm một chương trình hoặc hàm sẽ xuất ra ở bất kỳ định dạng có thể chấp nhận nào, tất cả các ký tự ASCII tiêu chuẩn có thể in được trong đó tổng các bit của giá trị nhị phân của chúng bằng với số nguyên đầu vào.

Các ví dụ / trường hợp thử nghiệm

1 -> ' @'
2 -> '!"$(0ABDHP`'
3 -> '#%&)*,1248CEFIJLQRTXabdhp'
4 -> ''+-.3569:<GKMNSUVYZ\cefijlqrtx'
5 -> '/7;=>OW[]^gkmnsuvyz|'
6 -> '?_ow{}~'

Một triển khai tham chiếu Python không có sẵn có sẵn ở đây (TIO) .

Những quy định

  1. Giả sử đầu vào sẽ luôn là một số nguyên (hoặc biểu diễn chuỗi của một số nguyên) trong khoảng từ 1 đến 6.
  2. Bạn có thể viết chương trình để hiển thị kết quả hoặc hàm để trả về chúng.
  3. Đầu ra có thể ở bất kỳ định dạng hợp lý nhưng phải nhất quán cho tất cả các đầu vào . Nếu bạn chọn xuất một chuỗi trích dẫn thì phải sử dụng cùng một loại dấu ngoặc kép cho tất cả các đầu vào.
  4. Sơ hở tiêu chuẩn bị cấm như bình thường.
  5. Đây là mã golf nên mã ngắn nhất trong mỗi ngôn ngữ sẽ thắng.

Chúng tôi có được phép trả lại / in danh sách các giá trị ascii thập phân hay chúng tôi cần có chúng ở dạng ký tự (ví dụ: 63vs ?)?
Benjamin Urquhart

1
Phải là nhân vật thực tế.
ElPedro

7
"cùng một loại dấu ngoặc kép phải được sử dụng cho tất cả các đầu vào" Python, ví dụ, sử dụng dấu ngoặc đơn ( ') cho biểu diễn chuỗi của một chuỗi theo mặc định, nhưng sử dụng dấu ngoặc kép ( ") nếu chuỗi chứa một dấu ngoặc đơn và không có dấu ngoặc kép . Không phải trường hợp cụ thể này sẽ quan trọng lắm, vì có lẽ bạn nên trả lại chuỗi thực tế thay vì đại diện của nó và bạn vẫn có thể sử dụng các trích dẫn đơn trong một chuỗi như vậy cho đầu vào, nhưng tôi cảm thấy đáng để đề cập ở đây.
Erik the Outgolfer

@EriktheOutgolfer Đồng ý. Đó là lý do tại sao tôi nghĩ rằng sẽ rất thú vị khi ném nó vào như một quy tắc bổ sung :-)
ElPedro

1
@ElPedro Tôi không chắc phải làm gì vì có lẽ nên có một số trích dẫn, vì có một khoảng trống trong ví dụ đầu tiên, nhưng các trích dẫn thông thường đều xuất hiện trong đầu ra :) Chỉnh sửa: có thể sử dụng máy chém tiếng Pháp ( « »)? : D
flawr

Câu trả lời:


29

Lắp ráp 8088, IBM PC DOS, 35 30 29 byte

Mã máy:

be81 00ad 8afc b330 b108 d0c8 12dd e2fa 3afb 7504 b40e cd10 fec0 79ea c3

Liệt kê:

BE 0081     MOV  SI, 081H   ; SI = memory address of command line string
AD          LODSW           ; AL = start ASCII value (init to 20H from space on cmd line)
8A FC       MOV  BH, AH     ; BH = target number of bits (in ASCII)
        CHR_LOOP:
B3 30       MOV  BL, '0'    ; BL = counter of bits, reset to ASCII zero
B1 08       MOV  CL, 8      ; loop through 8 bits of AL
        BIT_LOOP:
D0 C8       ROL  AL, 1      ; rotate LSB of AL into CF
12 DD       ADC  BL, CH     ; add CF to BL (CH is always 0) 
E2 FA       LOOP BIT_LOOP   ; loop to next bit
3A FB       CMP  BH, BL     ; is current char the target number of bits?
75 04       JNE  NO_DISP    ; if not, do not display
B4 0E       MOV  AH, 0EH    ; BIOS write char to screen function
CD 10       INT  10H        ; display ASCII char in AL (current char in loop)
        NO_DISP: 
FE C0       INC  AL         ; increment char to next ASCII value
79 EA       JNS  CHR_LOOP   ; if char <= 127, keep looping
C3          RET             ; return to DOS

Chương trình thực thi PC DOS độc lập, số đầu vào từ dòng lệnh. Đầu ra được hiển thị cho cửa sổ giao diện điều khiển.

enter image description here

Tải xuống và kiểm tra ABCT.COM (AsciiBitCounT).


8
Trong một khoảnh khắc tôi nghĩ rằng nó đã nói "Tải xuống và kiểm tra AT ABCT.COM", như thể bạn đã đăng ký một tên miền chỉ cho câu trả lời này.
Sparr

14

Lắp ráp CP-1610 ( Intellivision ), 20 DECLE 1 = 25 byte

Đưa N vào R0 và một con trỏ tới bộ đệm đầu ra trong R4 . Viết tất cả các ký tự khớp trong bộ đệm và đánh dấu kết thúc của kết quả bằng NUL .

                ROMW    10              ; use 10-bit ROM width
                ORG     $4800           ; map this program at $4800

                ;; ------------------------------------------------------------- ;;
                ;;  test code                                                    ;;
                ;; ------------------------------------------------------------- ;;
4800            EIS                     ; enable interrupts

4801            MVII    #$103,    R4    ; set the output buffer at $103 (8-bit RAM)
4803            MVII    #2,       R0    ; test with N = 2
4805            CALL    getChars        ; invoke our routine

4808            MVII    #$103,    R4    ; R4 = pointer into the output buffer
480A            MVII    #$215,    R5    ; R5 = backtab pointer

480C  draw      MVI@    R4,       R0    ; read R0 from the buffer
480D            SLL     R0,       2     ; R0 *= 8
480E            SLL     R0
480F            BEQ     done            ; stop if it's zero

4811            ADDI    #7-256,   R0    ; draw it in white
4815            MVO@    R0,       R5

4816            B       draw            ; go on with the next entry

4818  done      DECR    R7              ; loop forever

                ;; ------------------------------------------------------------- ;;
                ;;  routine                                                      ;;
                ;; ------------------------------------------------------------- ;;
      getChars  PROC

4819            MVII    #32,      R1    ; start with R1 = 32

481B  @loop     MOVR    R1,       R3    ; copy R1 to R3
481C            CLRR    R2              ; clear R2
481D            SETC                    ; start with the carry set

481E  @count    ADCR    R2              ; add the carry to R2
481F            SARC    R3              ; shift R3 to the right (the least
                                        ; significant bit is put in the carry)
4820            BNEQ    @count          ; loop if R3 is not zero

4822            CMPR    R2,       R0    ; if R2 is equal to R0 ...
4823            BNEQ    @next

4825            MVO@    R1,       R4    ; ... write R1 to the output buffer

4826  @next     INCR    R1              ; advance to the next character
4827            CMPI    #127,     R1    ; and loop until 127 is reached
4829            BLT     @loop

482B            MVO@    R3,       R4    ; write NUL to mark the end of the output

482C            JR      R5              ; return

                ENDP

Đầu ra cho N = 2

NB: Dấu ngoặc đơn mở trông rất giống dấu ngoặc vuông mở trong phông chữ Intellivision. Cả hai nhân vật là khác biệt, mặc dù.

output

ảnh chụp màn hình từ jzIntv


1. Mã op CP-1610 được mã hóa với giá trị 10 bit, được gọi là 'DECLE'. Thủ tục này dài 20 DECLE, bắt đầu từ $ 4809 và kết thúc ở mức $ 482C (bao gồm).


5
+1 chỉ để trở thành (a) một giải pháp cho Intellivision và (b) mã Intellivision đầu tiên tôi từng thấy.
tám bit

3
@ Eight-BitGuru Mã hóa trên Intellivision khá thú vị. Và các trò chơi homebrew ngày nay được viết bằng ROM 16 bit, giúp giải phóng toàn bộ sức mạnh (ahem ...) của CPU. :)
Arnauld

Ấn tượng! Không biết Intellivision có bộ đệm khung và bộ ký tự dựng sẵn. Vì vậy, cao cấp hơn nhiều so với Atari 2600. Hoàn thành rất tốt!
640KB

2
@gwaugh GROM (cho ROM đồ họa) chứa tất cả các ký tự ASCII có thể in và một vài hình dạng đồ họa phổ biến. Sự thật thú vị: nó cũng chứa một số mã thực thi không phù hợp với ROM chính.
Arnauld

Chắc chắn là cao cấp hơn 2600, nhưng nếu bộ nhớ phục vụ, Mattel đã không tiết lộ bất kỳ nội dung nâng cao nào ẩn trong ROM, vì vậy các nhà phát triển bên thứ ba hoặc bị giới hạn ở mã máy thẳng hoặc phải tự mình sử dụng những thứ lạ mắt . Có thể là ngày tận thế.
brhfl



8

Perl 6, 41 34 bytes

{chrs grep *.base(2)%9==$_,^95+32}

Try it online!

Anonymous code block that takes a number and returns a string of valid characters.

Explanation:

{                                }  # Anonymous code block taking a number
      grep                ,^95+32   # Filter from the range 32 to 126
           *.base(2)                # Where the binary of the digit
                    %9                # When parsed as a decimal modulo 9
                      ==$_            # Is equal to the input
 chrs                               # And convert the list of numbers to a string

It can be proven that for any number n in base b, ndigitsum(n)(modb1) (clue: remember that b(modb1)=1).

We can use this to get the digitsum of our binary number by parsing it as a decimal number and moduloing by 9, which is valid because the range of numbers we are using is guaranteed to have less than 9 bits. This is helped along by Perl 6's automatic casting of the binary string to a decimal number when used in a numeric context.


7

Jelly, 8 bytes

ØṖOB§=ʋƇ

Try it online!

ØṖ       printable ascii character list
  OB     to binary
    §    popcount
     =   equal to input?
      ʋƇ filter (implicitly output)

7

JavaScript (Node.js), 60 bytes

Using Jo King's modulo trick

n=>(g=x=>x>>7?'':Buffer(x.toString(2)%9-n?0:[x])+g(x+1))(32)

Try it online!


JavaScript (Node.js),  70  69 bytes

n=>(g=x=>x>>7?'':Buffer((h=x=>x&&x%2+h(x>>1))(x)-n?0:[x])+g(x+1))(32)

Try it online!

Commented

n => (              // n = input
  g = x =>          // g = recursive function, taking a byte x
    x >> 7 ?        //   if x = 128:
      ''            //     stop recursion and return an empty string
    :               //   else:
      Buffer(       //     create a Buffer:
        (h = x =>   //       h = recursive function taking a byte x
          x &&      //         stop if x = 0
          x % 2 +   //         otherwise, add the least significant bit
          h(x >> 1) //         and do a recursive call with floor(x / 2)
        )(x)        //       initial call to h
        - n ?       //       if the result is not equal to n:
          0         //         create an empty Buffer (coerced to an empty string)
        :           //       else:
          [x]       //         create a Buffer consisting of the character x
      ) +           //     end of Buffer()
      g(x + 1)      //     append the result of a recursive call to g with x + 1
)(32)               // initial call to g with x = 32

60 bytes using Jo's modulo trick.
Shaggy

@Shaggy Oh. That's a nice one.
Arnauld

6

Brachylog, 7 bytes

∈Ṭ&ạhḃ+

Try it online!

A predicate which functions as a generator, takes input through its output variable, and produces each character through its input variable. Because Brachylog.

           The input variable (which is an element of the output)
∈          is an element of
 Ṭ         the string containing every printable ASCII character
  &        and the input
   ạh      converted to a codepoint
     ḃ     converted to a list of binary digits
      +    sums to
           the output variable (which is the input).

5

Japt, 9 bytes

;EƶXc¤è1

Try it or test all inputs

;EƶXc¤è1     :Implicit input of integer U
;E            :Printable ASCII
  Æ           :Filter each X
   ¶          :Test U for equality with
    Xc        :  Character code of X
      ¤       :  To binary string
       è1     :  Count the 1s

5

Excel (2016 or later), 76 bytes

=CONCAT(IF(LEN(SUBSTITUTE(DEC2BIN(ROW(32:126)),0,))=A1,CHAR(ROW(32:126)),""))

Takes input from A1, outputs in whatever cell you put this formula. This is an array formula, so you need to press Ctrl+Shift+Enter to input it. The "2016 or later" is because it needs the CONCAT function (the deprecated CONCATENATE won't take an array as argument).


I like this. I'm a Lotus Notes and 123 guy so this works for me :-)
ElPedro

5

C (standard library), 74 67 bytes

i;j;k;f(n){for(i=31;i<126;k||puts(&i))for(k=n,j=++i;j;j/=2)k-=j&1;}

Using only standard library functions. Thanks go to @gastropner for improvement from 74 to 67 bytes.

Try it online!



@gastropner that is an amazing improvement! Thank you!
Krista

1
I think you need to start at index 31 in order to pick up space in the f(1) case (because the ++i skips it).
LambdaBeta

@LambdaBeta You're absolutely right, thank you!
Krista

5

R, 77 68 bytes

Approach using for loop

-9 bytes thanks to Giuseppe

n=scan();for(i in 32:126)if(sum(intToBits(i)>0)==n)cat(intToUtf8(i))

Try it online!

Previously:

R, 78 69 66 bytes

-12 bytes thanks to Giuseppe

a=32:126;cat(intToUtf8(a[colSums(sapply(a,intToBits)>0)==scan()]))

Turns the numbers 32 to 126 into a matrix of bits then sums across the rows to find which match the input number.

Try it online!


1
Use intToBits(x)>0 rather than as.single
Giuseppe

Nice, I tried |0 and got an error and just assumed the logic operators wouldn't work.
Aaron Hayman

1
66 bytes for the "previous" approach using sapply rather than matrix
Giuseppe

4

Java 10, 98 97 94 70 67 bytes

n->{for(var c='';c-->31;)if(n.bitCount(c)==n)System.out.print(c);}

-24 bytes thanks to NahuelFouilleul.

Try it online.

Explanation:

Contains an unprintable character with unicode value 127.

n->{                         // Method with Integer parameter and no return-type
  for(var c='';c-->31;)     //  Loop character `c` in the range ['~', ' '] / (127,31):
    if(n.bitCount(c)         //   If the amount of 1-bits in the two's complement binary
                             //   representation of the current characters
                    ==n)     //   equals the input:
      System.out.print(c);}  //    Print the current character

1
-24bytes using Long.bitCount
Nahuel Fouilleul

@NahuelFouilleul Ah, I always forget about that builtin in Java! Thanks a lot. And 3 more bytes can be saved by using n.bitCount. :)
Kevin Cruijssen

Yeah, Java beats JavaScript once more! I love those character challenges :P
Olivier Grégoire

4

Java 8, 131 71 bytes

-60 bytes thanks to everyone in the comments

Returns a java.util.stream.IntStream of codepoints

n->java.util.stream.IntStream.range(32,127).filter(i->n.bitCount(i)==n)

Try it online!

Using HashSet, 135 bytes. Returns a Set<Object>:

n->new java.util.HashSet(){{for(int i=31;i++<126;add(Long.toBinaryString(i).chars().map(c->c-48).sum()==n?(char)i+"":""),remove(""));}}

Try it online!



1
Static access from non-static context reeeeeee. Thanks.
Benjamin Urquhart

Long.toBinaryString(i) can be Long.toString(i,2);
Kevin Cruijssen

1
@KevinCruijssen that's what my first comment does
Expired Data

1
@KevinCruijssen You're right. Here's the fixed version: (still) 71 bytes. And yes, I saw your version which I upvoted less than 10 minutes ago ;)
Olivier Grégoire


4

Dyalog APL Extended, 24 22 bytes

ucs a⌿⍨⎕=+⌿2a32126

Try it online!

-2 bytes thanks to ngn

Alternative 22 bytes in regular Dyalog APL by ngn:

ucs 32+⍸⎕=32↓+/↑,⍳72

Try it online!


(expr)∘= -> ⎕=expr
ngn

without extended: ⎕ucs 32+⍸⎕=32↓+/↑,⍳7⍴2 (⎕io←0)
ngn


3

Gaia, 10 bytes

₵R⟪¤cbΣ=⟫⁇

Try it online!

		| implicit input, n
₵R		| push printable ascii
  ⟪	⟫⁇	| filter the list where:
   ¤cbΣ		| the sum of the code point in binary
       =	| is equal to n

3

J, 31 27 bytes

-4 bytes thanks to Galen

[:u:32+[:I.]=1#.32#:@+i.@95

Try it online!

Original Answer

a.#~&(95{.32}.])]=1#.2#:@i.@^8:

Try it online!

  • 2#:@i.@^8: produces the binary numbers 0 through 255 (2 ^ 8 is 256)
  • 1#. sums each one
  • ]= produces a binary mask showing where the sum equals the original input
  • a.#~ mask uses that binary mask to filter J's full ascii alphabet a.
  • &(95{.32}.]) but before doing so take only elements 32...126 from both the alphabet and the mask


Thanks Galen. TIL you could do i.@95
Jonah


3

K (ngn/k), 20 bytes

Solution:

`c$32+&(+/2\32+!95)=

Try it online!

Explanation:

Evaluated right-to-left:

`c$32+&(+/2\32+!95)= / the solution
                   = / equals?
       (          )  / do this together
               !95   / range 0..94
            32+      / add 32, so range 32..126
          2\         / break into base-2
        +/           / sum up
      &              / indices where true
   32+               / add 32
`c$                  / cast to character

3

6502 assembly (NES), 22 bytes

Machine code:

a0 1f a6 60 c8 98 30 fb ca 0a b0 fc d0 fb e8 d0 f1 8c 07 20 f0 ec

Assembly:

    ldy #$1f ; Y holds the current character code
NextCharacter:
    ldx $60 ; load parameter into X
    iny
    tya
    bmi (NextCharacter + 1) ; exit at char 128, #$60 is the return opcode

CountBits:
    dex
Continue:
    asl
    bcs CountBits
    bne Continue

CompareBitCount:
    inx ; fixes off-by-one error and sets Z flag if bit count matches
    bne NextCharacter
    sty $2007
    beq NextCharacter ; always branches

Full program. Tested with FCEUX 2.2.3, should work on any standard NES emulator.

Inspired by Ryan Russell's answer. Input given at CPU address $60. Outputs to the console's Picture Processing Unit memory.


2
Hello and welcome to PPCG. Is there any way to verify your solution apart from building a cartridge, i.e. an (online) emulator or specification?
Jonathan Frech

@JonathanFrech I've added a full program that can be assembled and run locally. As I understand, the NES environment is not really standardized for codegolf.
negative seven


2

PowerShell, 83 bytes

param($n)[char[]](32..126|?{([convert]::ToString($_,2)|% t*y|group)[1].count-eq$n})

Try it online!

Takes input $n, constructs a range from 32 to 126 and pulls out those numbers where |?{}: the number, converted ToString in base 2; converted toCharArray; grouped into 0s and 1s; taking the [1] index of that grouping; taking the .count thereof, and checking that it's -equal to our input $number. Those numbers are then cast as a char-array and left on the pipeline. Output is implicit, with newlines between elements.



2

Charcoal, 10 bytes

Φγ⁼Σ↨℅ι²Iθ

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

 γ          Predefined ASCII characters
Φ           Filtered by
      ι     Current character's
     ℅      ASCII code
    ↨       Converted to base
       ²    Literal 2
   Σ        Summed
  ⁼         Equals
         θ  First input
        I   Cast to integer
            Implicitly printed




Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.