Stampa i caratteri mancanti


18

Sfida semplice ispirata dalla popolarità del mio precedente testo invisibile di stampa e stampa vere e proprie sfide di testo invisibile e la stessa sfida di stringa diversa lunghezza .

Data una stringa composta solo da caratteri stampabili ( 0x20 to 0x7E), stampa tutti i caratteri stampabili non presenti nella stringa.

Ingresso

Una stringa o matrice di caratteri, composta solo da caratteri ASCII stampabili

Produzione

Ogni carattere ASCII stampabile non presente nella stringa di input, in qualsiasi ordine.

Casi test

Input:  "Hello, World!"
Output: ""#$%&'()*+-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVXYZ[\]^_`abcfghijkmnpqstuvwxyz{|}~"
========
Input:  "Hi!"
Output: " "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghjklmnopqrstuvwxyz{|}~"
========
Input:  ""
Output: " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
========
Input:  " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
Output: ""

punteggio

Si tratta di code-golf quindi vince il minor numero di byte in ogni lingua


Se restituiamo un array, possiamo includere elementi vuoti al posto dei caratteri usati?
Shaggy,

@Shaggy certo, va bene
Skidsdev

@Rod non perdere i miei piani D:
Skidsdev

L'output può essere un oggetto Set di stringhe di caratteri? set( 'a', 'b', 'c' )
Brad Gilbert b2gills

1
@MikhailV solo se la tua lingua non è in grado di generare caratteri ASCII
Skidsdev

Risposte:


11

GS2 , 2 byte

ç7

Provalo online!

Come funziona

    (implicit) Push the sting of all characters in STDIN on the stack.
ç   Push the string of all printable ASCII characters.
 7  Perform symmetric set difference.
    (implicit) Print the result to STDOUT.

6

Perl 6 , 29 byte

{[~] keys (' '..'~')∖.comb}

Si noti che il risultato è casuale perché i Set non sono ordinati.

Provalo

Allargato:

{
  [~]        # reduce using string concatenation
             # (shorter than 「join '',」)

  keys       # get the keys from the Set object resulting from the following

  (' '..'~') # Range of printable characters
            # Set minus (this is not \ )
  .comb      # split the input into individual characters
}

Esiste anche una versione ASCII di (-), ma richiederebbe uno spazio prima che non venga analizzato come una chiamata di subroutine.



5

Japt , 14 byte

Ho#_dÃf@bX ¥J

Provalo online!

Salvato 4 byte grazie a Shaggy e obarakon


1
Non c'è bisogno della bandiera (vedi la risposta al mio commento sulla domanda). Sostituisci 127con #per salvare un byte e rimuovi Uper salvarne un altro.
Shaggy,

1
È possibile utilizzare ¦e riorganizzare gli argomenti per salvare alcuni byte. Inoltre, 127 possono essere abbreviati TIO
Oliver


1
No, ci lavori, Tom - come hai detto prima, devo imparare a postare più velocemente! : D
Shaggy,

1
Una versione da 10 byte ma purtroppo non competitiva: ethproductions.github.io/japt/…
Shaggy

4

Haskell, 32 byte

f x=[y|y<-[' '..'~'],all(/=y)x] 

Provalo online!

Funzione di libreria noiosa per la differenza impostata:

Haskell, 31 byte

import Data.List
([' '..'~']\\)

4

MATL , 5 byte

6Y2X~

Provalo online!

Grazie a Luis Mendo per il golf a 8 byte di sconto!

Spiegazione:

   X~   % The symmetric set difference
6Y2     % Between all printable ASCII
        % And the input string (implicit)
        % Implicitly display

La differenza del set simmetrico fornirà tutti gli elementi presenti esattamente in uno dei due set di input. (ma non entrambi) Questo darà sempre la risposta giusta, poiché il set di input sarà sempre un sottoinsieme del secondo set (tutto ASCII stampabile).

Versione originale:

32:126tGom~)c

Spiegazione:

32:126          % Push the range 32-126
      t         % Duplicate it on the stack
       G        % Push the input
        o       % Convert it to character points
         m      % Is member (0 for each char that isn't in input, 1 for each char that is)
          ~     % Logical NOT
           )    % Take the truthy elements of this array from the previous array (All Printable ASCII)
            c   % Display as a string

3

Brachylog , 5 byte

ẹ;Ṭ↔x

Provalo online!

Spiegazione

ẹ          Split the input string into a list of chars
 ;Ṭ↔x      Exterminate the chars from the string Ṭ of printable ASCII chars

3

JavaScript (ES6), 74 byte

Sono sicuro che c'è un modo più breve per farlo!

s=>[...Array(95)].map((_,y)=>s.includes(c=String.fromCharCode(y+32))?"":c)

Provalo

let f=
s=>[...Array(95)].map((_,y)=>s.includes(c=String.fromCharCode(y+32))?"":c)
oninput=_=>o.innerText=f(i.value).join``
o.innerText=f(i.value="Hello, World!").join``
<input id=i><pre id=o>


1
Dovrebbe essere Array(95)quello di includere i dispersi~
Malivil,

È sempre stato lì, @Malivil? }Avrei potuto giurare che l'ultimo personaggio era quando l'ho scritto. Risolto ora, grazie.
Shaggy,

Non riesco a credere che C # sia più corto di JavaScript per questo, soprattutto perché devo includere i miei usi.
TheLethalCoder

1
@TheLethalCoder, String.fromCharCodeè un idiota, ecco perché! : D
Shaggy,

@Shaggy Non lo so, stavo solo guardando il tuo codice per vedere come funzionava e ho digitato letteralmente ogni simbolo sulla mia tastiera e ~ho notato che non ha cambiato nulla ma che era nelle specifiche. Inoltre, la parte "Provalo" deve essere aggiornata.
Malivil,

3

bash ,47 43 40 byte

printf %x {32..126}|xxd -r -p|tr -d "$1"

Provalo online!

Genera intervallo hexa, inverte il dump esadecimale in carattere e rimuove i caratteri presenti nel primo parametro.


3

Ottava, 22 20 byte

Grazie a @Luis Mendo risparmiato 2 byte.

@(s)setxor(32:'~',s)

Provalo online!

Altra risposta:

@(s)setdiff(' ':'~',s)

Provalo online!


1
@(s)setxor(' ':'~',s)salva 1 byte
Luis Mendo

@LuisMendo Very nice! Ma penso che sia una cosa diversa. Ti suggerisco di pubblicarlo come una nuova risposta :)
rahnema1

1
No, è davvero solo un piccolo miglioramento. Sarò felice che tu lo pubblichi se vuoi. BTW @(s)setxor(32:'~',s)sembra funzionare troppo --- e lo stesso commento per quello :-)
Luis Mendo

1
@LuisMendo Grazie, sono d'accordo perché (Luis) ha detto.
rahnema1

2

PHP, 42 byte

Input come array

Uscita come stringa

<?=join(array_diff(range(" ","~"),$_GET));

Provalo online!

PHP, 53 byte

Inserisci come stringa

Uscita come stringa

<?=join(array_diff(range(" ","~"),str_split($argn)));

sostituire <?=joincon print_rper un output come array

Provalo online!


Forse dovresti creare una versione golf di PHP: P
CalculatorFeline

@CalculatorFeline Sono sicuro che esiste ma non è proprio buono
Jörg Hülsermann

Forse dovresti farne una buona. Passaggio 1: tag di avvio automatico.
CalculatorFeline

@CalculatorFeline Ho cercato il link per te. github.com/barkermn01/PGP-php-CodeGolf Non ho interesse a
crearne

1
@CalculatorFeline Rendere PHP un linguaggio golfistico distrugge ciò che è divertente giocare a golf con PHP (almeno per me): devi bilanciare costantemente le funzioni di chiamata (che spesso hanno nomi lunghi), usando loop, diversi metodi di input e così via. Step 1: automatic starting tagbene php -r... ma ad esempio in questo esempio non paga perché echoè più lungo di <?=.
Christoph,

2

CJam , 8 byte

'␡,32>q^

Dov'è un carattere di eliminazione letterale.

Provalo online!

'␡,       e# The range of all characters up to ~.
   32>    e# Slice it to be the range of all characters from space to ~.
      q^  e# Symmetric set difference with the input.

Proprio come una nota, -funziona invece di ^.
Esolanging Fruit

2

Perl, 39 byte

s!.*!"pack(c95,32..126)=~y/$_//dr"!ee

Corri con perl -pe.


Ricevo il messaggio di errore 'Bareword trovato dove l'operatore si aspettava alla (eval 1) linea 2, vicino a "y / Hello World! // dr"' quando eseguo questo ...
Chris

Full-riga di comando: echo 'Hello World!' | perl -pe 's!.*!"pack(c95,32..126)=~y/$_//dr"!ee'. Questo funziona per me su Perl v5.14 e v5.24.
Grimmy,

È Perl v5.10 che non funziona ... Deve essere stata apportata una modifica tra 5.10 e 5.14.
Chris,

2

Brainfuck , 120 byte

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

Provalo online!

avvolto:

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

Ha spiegato:

+[+[>+<+<]>]>-         initialize what we will now consider cell 0 to 95
[[>>]+[<<]>>-]         initialize cells 2 4 etc 95*2 to 1; end on cell 0 at 0
,[                     main input loop (for each char of input)
  <+++++[>------<-]>-  subtract 31 from the input
  [>[>>]+[<<]>-]       lay a trail of (input minus 31) ones in the empty spaces
  >[>>]<[-]<[-<<]>     use the trail to clear the appropriate "print" flag
,]                     keep reading input until it ends
++++++++[->++++<]>     initialize the cell directly before flag 1 to 32
[                      we'll let the accumulator overflow; no harm done
  >[-<.>]              print the accumulator if the flag is still set
  <[->>+<<]>>+         shift over the accumulator and increment it
]


2

Rubino, 23 18 17 byte

->s{[*' '..?~]-s}

Utilizza una funzione lambda come da commenti di @ sethrin.

Versione precedente:

[*' '..?~]-s.chars

(' '..'~').to_a-s.chars

Non sdeve essere letto da STDIN o fornito come argomento di funzione? La sfida specifica anche che l'input può essere dato come una matrice di caratteri. La conversione in lambda di stabby e il rilascio charsoffrono una soluzione a 16 byte.
Canhascodez,

Non ero davvero sicuro di come affrontare l'input, dato che non era stato esplicitamente specificato. Ci sono alcune altre risposte che presuppongono l'esistenza dell'input in una variabile. Esiste una convenzione codegolf? Non lo faccio molto.
Mark Thomas,

@sethrin Con un stabby lambda non sarebbero 20 caratteri? ->(s){[*' '..?~]-s)}
Mark Thomas,

Tutte le parentesi nella tua lambda sono opzionali. Ma potrei aver contato male un byte. Altre lingue accettano input in modo implicito o sono stdinassociate a una variabile globale. In Ruby $<è una scorciatoia per stdinma i lambda tendono ad essere più brevi. Le convenzioni su input e output sono qui . Anche io non faccio così tanto, quindi se le regole non sono ciò che penso fammi sapere.
Canhascodez,

2

APL, 13 byte

⍞~⍨⎕UCS31+⍳95

semplice:

       31+⍳95  ⍝ A vector 32 .. 126
   ⎕UCS        ⍝ as characters
 ~⍨            ⍝ without
⍞              ⍝ those read from character input.

1

R , 50 byte

function(s)intToUtf8(setdiff(32:126,utf8ToInt(s)))

returns an anonymous function. Converts the input string to integers, computes the set difference between the printable range and the input values, and then converts them back to a string and returns it.

Provalo online!


1

PHP, 53 bytes

for($k=31;$k++<126;)~strstr($argn,$k)?:print chr($k);
# or
for($k=31;$k++<126;)echo~strstr($argn,$k)?"":chr($k);

Run as pipe with -r.


I have left no more playground
Jörg Hülsermann

@JörgHülsermann You do. You just have to share it.
Titus

1

C#, 74 71 bytes

using System.Linq;s=>new int[95].Select((n,i)=>(char)(i+32)).Except(s);

Old version with creating a range for 74 bytes:

using System.Linq;s=>Enumerable.Range(32,95).Select(n=>(char)n).Except(s);

1

05AB1E, 5 4 bytes

-1 thanks to Emigna

žQsK

Try it online!

žQ   # Push all printable characters
  s  # Swap input to the top
   K # Push a with no b's (remove input characters from all printable character)

@FrodCube Oops... I forgot to update the link. It should work now. TIO (empty input)
Riley

1

V, 20 bytes

òiÎflax
òcH ¬ ~@"<

Try it online!

Hexdump:

00000000: f269 ce66 1b6c 6178 0af2 6348 20ac 207e  .i.f.lax..cH . ~
00000010: 1b40 223c                                .@"<

1

C (gcc), 75 72 70 68 50 bytes

i;f(s){for(i=31;++i<127;strchr(s,i)?:putchar(i));}

Try it online!


Can you use || to make this work on "standard" C?
Neil

@Neil Yes || also works. Isn't ?: part of "standard" C?
cleblanc

I always thought it was a gcc extension.
Neil

@Neil That's correct. ?: is a GNU extension. It works as well in clang and tcc though.
Dennis

1

Jelly, 8 bytes

Really, 8 bytes? Please, tell me I missed something!

32r126Ọḟ

Try it online!

How?

32r126Ọḟ - Main link: list of characters s
32r126   - inclusive range from 32 to 126 = [32,33,...,125,126]
      Ọ  - cast ordinals to characters = list of printable characters
       ḟ - filter discard if in s

Alternatively

“ ~‘r/Ọḟ - Main link
“ ~‘     - code-page indexes = [32,126]
    r/   - reduce by inclusive range = [32,33,...,125,126]
      Ọ  - cast from ordinals to characters = list of printable characters
       ḟ - filter discard if in s

Since this challenge a new atom which yields all printable ASCII characters, ØṖ, has been introduced making the following work for 3 bytes:

ØṖḟ

No you didn't miss anything.
Erik the Outgolfer

1

Charcoal, 18 15 10 8 bytes

Fγ¿¬№θιι

Try it online! Link is to verbose version of code. Edit: Saved 3 bytes by ranging over characters instead of integers. Saved a further 5 bytes when I discovered the undocumented γ variable which holds the printable ASCII characters. Saved a further 2 bytes when @ASCII-only fixed predefined inputs in verbose mode (the answer is still valid as it stands, it's only the try it online link that wouldn't have worked at the time).


8 bytes (unless preinitialized inputs weren't working back then)
ASCII-only

@ASCII-only They weren't working in verbose mode... they would probably have worked in succinct mode, but I like the verbose links.
Neil

0

Mathematica, 35 bytes

20~CharacterRange~126~Complement~#&

Anonymous function. Takes a list of characters as input and returns a list of characters as output.


0

Lua, 78 bytes

s=io.read()for i=32,126 do c=string.char(i)io.write(s:find(c,1,1)and""or c)end

0

shortC, 33 bytes

i;AOi=31;++i<'~';strchr(*@,i)?:Pi

Conversions made in this program:

  • A -> int main(int argc, char **argv) {
  • O -> for(
  • @ -> argv
  • P -> putchar
  • Auto-inserted closing ));}

The resulting program looks like:

i;int main(int argc, char **argv){for(i=31;++i<'~';strchr(*argv,i)?:putchar(i));}

Try it online!


0

Pyth, 17 bytes

Vr32 127I!}CNzpCN

The naive approach.

Explanation:

Vr32 127I!}CNzpCN
Vr32 127             For N in [32, 127[
           CN        Get the ASCII character for the code N
        I!}  z       If it is in the input string...
              pCN    ...then print it

Test it online!


0

Clojure, 60 or 49 bytes

#(apply str(sort(apply disj(set(map char(range 32 127)))%)))

These "apply"s are killing me :/ Oh, if returning a list is fine then this is a bit shorter.

#(sort(apply disj(set(map char(range 32 127)))%))
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.