39
\$\begingroup\$

(Title with thanks to @ChasBrown)

Sandbox

The Background

This challenge is inspired by a question that I recently posted on Puzzling Stack Exchange. Please feel free to follow the link if you are interested in the original question. If not then I won't bore you with the details here.

The Facts

Every printable standard ASCII character has a decimal value between 32 and 126 inclusive. These can be converted to their corresponding binary numbers in the range 100000 to 1111110 inclusive. When you sum the bits of these binary numbers you will always end up with an integer between 1 and 6 inclusive.

The Challenge

Given an integer between 1 and 6 inclusive as input, write a program or function which will output in any acceptable format all of the printable standard ASCII characters where the sum of the bits of their binary value is equal to the input integer.

The Examples/Test Cases

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

An ungolfed Python reference implementation is available here (TIO).

The Rules

  1. Assume the input will always be an integer (or string representation of an integer) between 1 and 6 inclusive.
  2. You may write a program to display the results or a function to return them.
  3. Output may be in any reasonable format but must be consistent for all inputs. If you choose to output a quoted string then the same type of quotes must be used for all inputs.
  4. Standard loopholes prohibited as usual.
  5. This is code golf so shortest code in each language wins.
\$\endgroup\$
9
  • \$\begingroup\$ Are we allowed to return/print a list of the decimal ascii values or do we need to have them in the form of characters (eg. 63 vs ?)? \$\endgroup\$ Apr 23, 2019 at 19:27
  • 1
    \$\begingroup\$ Must be the actual characters. \$\endgroup\$
    – ElPedro
    Apr 23, 2019 at 19:29
  • 8
    \$\begingroup\$ "the same type of quotes must be used for all inputs" Python, for example, uses single quotes (') for the string representation of a string by default, but uses double quotes (") if the string contain a single quote and no double quotes. Not that this specific case will matter much, as you're probably better off returning the actual string instead of its representation, and you can still use single quotes in such a string for input anyway, but I feel it's worth mentioning here. \$\endgroup\$ Apr 23, 2019 at 19:59
  • \$\begingroup\$ @EriktheOutgolfer Agreed. That is why I thought it might be interesting just to throw that in as an extra rule :-) \$\endgroup\$
    – ElPedro
    Apr 23, 2019 at 23:03
  • 1
    \$\begingroup\$ @ElPedro I wasn't sure what to do as it is probably a good idea to have some quotes, as there is a space in the first example, but the usual quotes both appear in the output:) Edit: maybe use french guillemets (« »)? :D \$\endgroup\$
    – flawr
    Apr 24, 2019 at 13:11

62 Answers 62

30
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 29 25 bytes

Machine code:

00000000: be81 00ad b330 b108 d0c8 12dd e2fa 3adc  .....0........:.
00000010: 7502 cd29 fec0 79ec c3                   u..)..y..

Listing:

BE 0081     MOV  SI, 081H   ; SI = memory address of command line string
AD          LODSW           ; AL = start ASCII value (is 20H from space on cmd line)
                            ; AH = 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 DC       CMP  BL, AH     ; is current char the target number of bits?
75 02       JNE  NO_DISP    ; if not, do not display
CD 10       INT  29H        ; display ASCII char in AL (current char in loop)
        NO_DISP: 
FE C0       INC  AL         ; increment char to next ASCII value
79 EC       JNS  CHR_LOOP   ; if char <= 127, keep looping
C3          RET             ; return to DOS

Standalone PC DOS executable program, input number from command line. Output is displayed to console window.

enter image description here

\$\endgroup\$
1
  • 9
    \$\begingroup\$ For a moment I thought it said "Download and test AT ABCT.COM", as if you had registered a domain just for this answer. \$\endgroup\$
    – Sparr
    Apr 24, 2019 at 1:16
14
\$\begingroup\$

CP-1610 assembly (Intellivision), 20 DECLEs1 = 25 bytes

Takes \$N\$ in R0 and a pointer to the output buffer in R4. Writes all matching characters in the buffer and marks the end of the results with 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

Output for N=2

NB: The opening parenthesis looks a lot like an opening square bracket in the Intellivision font. Both characters are distinct, though.

output

screenshot from jzIntv


1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 20 DECLEs long, starting at $4819 and ending at $482C (included).

\$\endgroup\$
5
  • 5
    \$\begingroup\$ +1 just for being (a) a solution for the Intellivision, and (b) the first Intellivision code I've ever seen. \$\endgroup\$ Apr 24, 2019 at 8:11
  • 3
    \$\begingroup\$ @Eight-BitGuru Coding on the Intellivision is pretty fun. And today's homebrew games are written in 16-bit ROM, which unlocks the full power (ahem...) of the CPU. :) \$\endgroup\$
    – Arnauld
    Apr 24, 2019 at 8:23
  • \$\begingroup\$ Impressive! Had no idea the Intellivision had a frame buffer and a built in character set. So much more advanced than the Atari 2600 for sure. Very nicely done! \$\endgroup\$
    – 640KB
    Apr 24, 2019 at 14:04
  • 2
    \$\begingroup\$ @gwaugh The GROM (for Graphics ROM) contains all printable ASCII characters and a few common graphical shapes. Fun fact: it also contains some executable code that did not fit in the main ROM. \$\endgroup\$
    – Arnauld
    Apr 24, 2019 at 14:09
  • \$\begingroup\$ Definitely more advanced than the 2600, but if memory serves, Mattel didn’t reveal any of the advanced stuff hiding out in ROM, so third-party devs were either limited to straight machine code or had to suss out the fancy stuff on their own. Might be apocryphal. \$\endgroup\$
    – brhfl
    Apr 25, 2019 at 23:40
12
\$\begingroup\$

Python 2, 62 bytes

lambda n:[chr(i)for i in range(32,127)if bin(i).count('1')==n]

Try it online!

\$\endgroup\$
1
  • 3
    \$\begingroup\$ sum(map(int,bin(i)[2:]))==n can become bin(i).count('1')==n to save 7 bytes. \$\endgroup\$
    – mypetlion
    May 1, 2019 at 22:14
10
\$\begingroup\$

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\$, \$n \equiv \text{digitsum}(n) \pmod{b-1}\$ (clue: remember that \$b \pmod{b-1}=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.

\$\endgroup\$
9
\$\begingroup\$

05AB1E, 8 bytes

žQʒÇbSOQ

Try it online!

Explanation

žQ        # push the printable ascii characters
  ʒ       # filter, keep elements whose
   Ç      # character code
    b     # converted to binary
     SO   # has a digit sum
       Q  # equal to the input
\$\endgroup\$
7
\$\begingroup\$

Jelly, 8 bytes

ØṖOB§=ʋƇ

Try it online!

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

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).
\$\endgroup\$
7
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ 60 bytes using Jo's modulo trick. \$\endgroup\$
    – Shaggy
    Apr 25, 2019 at 12:01
  • \$\begingroup\$ @Shaggy Oh. That's a nice one. \$\endgroup\$
    – Arnauld
    Apr 25, 2019 at 13:09
6
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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).

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I like this. I'm a Lotus Notes and 123 guy so this works for me :-) \$\endgroup\$
    – ElPedro
    Apr 23, 2019 at 23:21
5
\$\begingroup\$

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!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 67 bytes \$\endgroup\$
    – gastropner
    Apr 24, 2019 at 14:06
  • \$\begingroup\$ @gastropner that is an amazing improvement! Thank you! \$\endgroup\$
    – Krista
    Apr 24, 2019 at 14:16
  • 1
    \$\begingroup\$ 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). \$\endgroup\$
    – LambdaBeta
    Apr 24, 2019 at 18:16
  • \$\begingroup\$ @LambdaBeta You're absolutely right, thank you! \$\endgroup\$
    – Krista
    Apr 25, 2019 at 11:28
5
\$\begingroup\$

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!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Use intToBits(x)>0 rather than as.single \$\endgroup\$
    – Giuseppe
    Apr 24, 2019 at 11:14
  • \$\begingroup\$ Nice, I tried |0 and got an error and just assumed the logic operators wouldn't work. \$\endgroup\$ Apr 24, 2019 at 11:26
  • 1
    \$\begingroup\$ 66 bytes for the "previous" approach using sapply rather than matrix \$\endgroup\$
    – Giuseppe
    Apr 26, 2019 at 18:48
4
\$\begingroup\$

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
\$\endgroup\$
3
  • 1
    \$\begingroup\$ -24bytes using Long.bitCount \$\endgroup\$ Apr 24, 2019 at 9:28
  • \$\begingroup\$ @NahuelFouilleul Ah, I always forget about that builtin in Java! Thanks a lot. And 3 more bytes can be saved by using n.bitCount. :) \$\endgroup\$ Apr 24, 2019 at 11:09
  • \$\begingroup\$ Yeah, Java beats JavaScript once more! I love those character challenges :P \$\endgroup\$ Apr 24, 2019 at 12:20
4
\$\begingroup\$

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!

\$\endgroup\$
12
  • \$\begingroup\$ 128 bytes \$\endgroup\$ Apr 23, 2019 at 23:32
  • 1
    \$\begingroup\$ Static access from non-static context reeeeeee. Thanks. \$\endgroup\$ Apr 23, 2019 at 23:33
  • \$\begingroup\$ Long.toBinaryString(i) can be Long.toString(i,2); \$\endgroup\$ Apr 24, 2019 at 6:32
  • 1
    \$\begingroup\$ @KevinCruijssen that's what my first comment does \$\endgroup\$ Apr 24, 2019 at 7:06
  • 1
    \$\begingroup\$ @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 ;) \$\endgroup\$ Apr 24, 2019 at 11:55
4
\$\begingroup\$

C# (Visual C# Interactive Compiler), 86 bytes

n=>Enumerable.Range(32,95).Where(x=>"0123456".Sum(g=>x>>g-48&1)==n).Select(x=>(char)x)

Thanks to @ExpiredData for giving me the idea to use Sum()! When I get back to my PC, I will replace the string "0123456" with unprintables, saving three bytes.

Try it online!

\$\endgroup\$
2
4
\$\begingroup\$

Dyalog APL Extended, 24 22 bytes

⎕ucs a⌿⍨⎕=+⌿2⊤a←32…126

Try it online!

-2 bytes thanks to ngn

Alternative 22 bytes in regular Dyalog APL by ngn:

⎕ucs 32+⍸⎕=32↓+/↑,⍳7⍴2

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ (expr)∘= -> ⎕=expr \$\endgroup\$
    – ngn
    May 8, 2019 at 10:38
  • \$\begingroup\$ without extended: ⎕ucs 32+⍸⎕=32↓+/↑,⍳7⍴2 (⎕io←0) \$\endgroup\$
    – ngn
    May 8, 2019 at 10:45
4
\$\begingroup\$

Factor, 52 bytes

[ 32 126 [a,b] [ bit-count = ] with filter >string ]

Try it online!

  • 32 126 [a,b] Create a range of printable ascii values
  • [ bit-count = ] with filter Select values with the bit count indicated by the input
  • >string Convert the result from a sequence of code points to a printable string
\$\endgroup\$
4
\$\begingroup\$

J, 31 27 23 bytes

((=1#.#:)u:@#])32+i.@95

-2 thanks to south

Attempt This Online!

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
\$\endgroup\$
4
  • \$\begingroup\$ [:u:32+[:I.]=1#.32#:@+i.@95 for 27 bytes \$\endgroup\$ Apr 24, 2019 at 9:05
  • \$\begingroup\$ Thanks Galen. TIL you could do i.@95 \$\endgroup\$
    – Jonah
    Apr 24, 2019 at 14:57
  • 1
    \$\begingroup\$ 25 bytes \$\endgroup\$
    – south
    Jun 19, 2023 at 5:38
  • \$\begingroup\$ @south Thanks. I shaved an additional 2 off using your idea. \$\endgroup\$
    – Jonah
    Jun 19, 2023 at 22:11
3
\$\begingroup\$

Python 2, 69 bytes

lambda n:[chr(i)for i in range(32,127)if sum(map(int,bin(i)[2:]))==n]

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ That's exactly what I got when I golfed my ref implementation. +1 \$\endgroup\$
    – ElPedro
    Apr 23, 2019 at 19:22
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Ruby, 48 bytes

->n{(' '..?~).select{|x|x.ord.digits(2).sum==n}}

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Perl 5 -a, 50 43 bytes

@NahuelFouilleul saves 7 bytes

map{$_=chr;unpack('B*')%9-"@F"||say}32..126

Try it online!

\$\endgroup\$
3
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ `c$32+&32_(+/!7#2)= or `c$(31<)#&(+/!7#2)= brings it to 19. \$\endgroup\$
    – zgrep
    Sep 28, 2023 at 22:05
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ Apr 28, 2019 at 21:03
  • \$\begingroup\$ @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. \$\endgroup\$ Apr 29, 2019 at 9:30
3
\$\begingroup\$

VBA, 146 bytes

Sub Main()
n=3
For i=32 To 127
b=CStr(Application.WorksheetFunction.Dec2Bin(i))
If Len(b)-Len(Replace(b,"1",""))=n Then MsgBox Chr(i)
Next
End Sub

I wonder if somehow it could be done using Excel alone, I am not a excel formula pro....

\$\endgroup\$
3
  • \$\begingroup\$ =IF(LEN(DEC2BIN(32))-LEN(SUBSTITUTE(DEC2BIN(32),"1",""))=A1,CHAR(32),"") Checks against the value in cell A1 and displays the character if the binary sum matches. It needs to be repeated 95 times, one for each ASCII value that we need to check, so it comes out at around 7100 bytes - not very golfy but at least it can be done! \$\endgroup\$
    – ElPedro
    Apr 12, 2021 at 7:14
  • \$\begingroup\$ @ElPedro - thanks to the Let() command, this can actually be compacted into a really satisfying Excel answer at 86 bytes \$\endgroup\$ Jan 7, 2022 at 17:34
  • \$\begingroup\$ You can get this down to 91 bytes if you convert this to an immediate window function, use [...] evaluation, take input from A1 and output to the VBE debug window - x=[Dec2Bin(ROW(1:126))]:For i=32To 126:?IIf(Len(Replace(x(i,1),0,""))=[A1],Chr(i),"");:Next - Check out Tips for Golfing in VBA for more info \$\endgroup\$ Jan 7, 2022 at 17:56
3
\$\begingroup\$

Nibbles, 5 bytes

|_~`^+`@ 2

That's 10 nibbles each encoded as half a byte in the binary form.

Translation:

|          filter
 _         printables (since stdin is empty)
 ~         not
  `^       xor
    +      sum
     `@2   to base 2
        $  filter var (implicit)
    @      first input arg (implicit)

It uses not of the xor to set itself up for implicit args (instead of == which wouldn't be able to use any)

Usage:

nibbles <filename>.nbl <input number>

Nibbles isn't on TIO yet...

\$\endgroup\$
3
\$\begingroup\$

Python 3.10, 58 bytes

lambda n:(chr(i)for i in range(32,127)if i.bit_count()==n)

Attempt This Online!

It's kind of like Lynn's answer.
Just it uses the .bit_count introduced in Python3.10, so its shorter

More info about .bit_count here: https://docs.python.org/3/library/stdtypes.html

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I really like the idea of going through old questions and finding where new functions can shave a few bytes off! +1 from me. \$\endgroup\$
    – ElPedro
    Sep 8, 2022 at 15:14
3
\$\begingroup\$

Kotlin, 60 bytes

{n->(32..127).filter{n==it.countOneBits()}.map{it.toChar()}}

Note:
For the moment Kotlin's STDOUT in ATO is always empty.
And TIO doesn't support countOneBits().

More information about how to count bytes for a Kotlin answer: https://codegolf.stackexchange.com/a/202985/112099

Attempt This Online!

\$\endgroup\$
1
  • \$\begingroup\$ you can use this ATO link just dropping the fun main \$\endgroup\$
    – naffetS
    Sep 10, 2022 at 19:29
3
\$\begingroup\$

MATL, 10 bytes

6Y2tB!si=)

Try it online!

Explanation

6Y2        % All ASCII Chars
   t       % dup
    B      % convert each to binary
     !     % transpose
      s    % sum
       i=  % equal to the input?
         ) % Keep truthy elements
\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 70 bytes

FromCharacterCode/@Select[32~Range~126,s=#;Tr@IntegerDigits[#,2]==s&]&

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.