Iniezione da due stringhe a una stringa


13

Sfida

Scrivi un programma che applica una funzione iniettiva che accetta una coppia ordinata di stringhe come input e una stringa come output. In altre parole, ogni input deve essere mappato su un output univoco.

specifiche

  • L'input può essere qualsiasi due stringhe di lunghezza arbitraria, ma sarà composto solo da caratteri ASCII stampabili (codici [32,126] ).
  • Allo stesso modo, la stringa di output non ha limiti di lunghezza, ma deve contenere solo caratteri ASCII stampabili.
  • Se la tua lingua non è in grado di gestire stringhe di lunghezza arbitraria, il programma potrebbe semplicemente funzionare teoricamente per stringhe di qualsiasi dimensione.
  • La mappatura da input a output dovrebbe essere coerente tra le esecuzioni del programma. Altrimenti, la mappatura che usi dipende completamente da te, purché si tratti di un'iniezione.
  • L'ingresso è ordinato. Se le due stringhe di input sono diverse, dovrebbero produrre un output diverso rispetto a se fossero state scambiate. stf(s,t)f(t,s)
  • Non tutte le stringhe devono essere un possibile output.
  • Vince la risposta più breve in ogni lingua!

Casi test

I seguenti ingressi dovrebbero comportare tutti output diversi. Per evitare confusione, le stringhe sono circondate da guillemets («») e separate da spazi singoli.

"Ciao mondo"
«Lelho» «drowl»
"diverso"
"non lo stesso"

«Codice» «Golf»
«Co» «deGolf»
«CodeGolf» «»

«» «»
«» «»
«» «»
«» «»
«» «»

"a B c D e F"
"a B c D e F"
"a B c D e F"
"a B c D e F"

«\» «" »
«\\» «\" »

8
Hmm ho appena notato "Scrivi un programma che ..." - nota che per meta consenso (attualmente 46 in su, 1 in giù) "Limitare solo ai programmi richiede di specificare esplicitamente" programma completo "piuttosto che" programma "" . Spero che non intendessi provare a limitare questo, ma se lo hai fatto dovrai aggiornare il post di conseguenza e indirizzare quelli di noi che hanno già inviato funzioni come risposte.
Jonathan Allan,

4
@JonathanAllan L'intento era quello di consentire le funzioni.
negativo sette

3
Una delle stringhe può essere vuota?
Shaggy,

2
@Shaggy Sì, uno o entrambi possono.
negativo sette

1
Possiamo avere alcuni casi di test? Grazie!
ouflak,

Risposte:


17

brainfuck, 30 29 27 23 byte

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

Provalo online!

Gli ingressi sono separati da un 0x01byte.

Questo si trasforma ["foo", "bar"]in fUToUToUTUTbUTaUTrUT. Per recuperare le due stringhe originali, prendi gruppi di 3 caratteri, trova quello in cui la seconda lettera non è Ue dividi lì.


@Grimy Siamo spiacenti, frainteso "Gli ingressi sono separati da un byte 0x01".
wastl,

15

JavaScript (ES6), 14 byte

Accetta l'input come una matrice di 2 stringhe. Ispirato dalla risposta di Luis .

JSON.stringify

Provalo online!


JavaScript (ES6),  21  20 byte

Accetta input come (a)(b).

a=>b=>[a.length,a]+b

Provalo online!

Restituisce la lunghezza di a , seguito da una virgola, seguita dalla concatenazione di a e b .


Dannazione! Stavo per usare il stringifytrucco da solo!
Shaggy,

Si rompe con a="hello","" b="world"ea="hello" b="","world"
Soleil,

1
@Soleil Che darebbe ["\"hello\",\"\"","\"world\""]e ["\"hello\"","\"\",\"world\""].
Arnauld,

1
@Arnauld la protezione da barra rovesciata non sarà visibile. La funzione non verrà iniettata.
Soleil,

1
@Soleil Non capisco cosa intendi. JSON.stringify()sicuramente scappa ". Vedi una discarica esadecimale .
Arnauld,

15

jq -c, 0 byte

Provalo online!

Questo sicuramente sembra barare ...? Ma sembra rispettare le regole della sfida.

Per impostazione predefinita, jqprodurrà il suo input in un formato JSON leggibile dall'uomo. Il -cflag (compatto) indica jql'output in stile "compatto", che rimuove le nuove righe (poiché la sfida proibisce ASCII non stampabile).


1
OP consente input vuoti, quindi a = "", b = "x" fornisce lo stesso output di a = "x" b = ""
Gnudiff,

3
@Gnudiff Come? Avrebbero dato ["","x"]e ["x",""]rispettivamente
Maniglia della porta

1
Scusa, hai ragione.
Gnudiff,


5

Japt -S , 3 byte

Io ancora sento Devo mancare qualcosa qui ...

®mc

Provalo

Forse 2 byte:

mq

Provalo

O allungandolo con questo 1 byte:

U

Provalo

La prima versione associa ogni stringa dell'array ai suoi punti di codice e li emette uniti con uno spazio.

La seconda versione divide ogni stringa in un array di caratteri e li emette uniti con uno spazio.

E la terza versione, che sembra imbroglione, emette semplicemente l'ingresso con la -Qbandiera che fa il pesante sollevamento di srringifyesso.


5

Pyth , 4 byte

jNmC

Provalo online!

Ciò converte ciascuna stringa in base 256 e quindi le unisce in ordine con a ". Poiché i risultati sono ogni numero, "li separa in modo univoco e le stringhe originali possono essere recuperate con mCsdczN.


1
@AndersKaseorg suggests a 1-byter.
Kevin Cruijssen

@KevinCruijssen I've been aware of that since a few minutes after I posted this, I just prefer the spirit of this solution. Thanks for bringing it up anyway, and definitely feel free to post it yourself :)
FryAmTheEggman

I indeed like your answer more as well. :) And nah, I don't even know Pyth. If you want you can post it yourself as a separated answer (or a combined answer by editing this one), otherwise Anders Kaseorg can post it, since he's the one who mentioned it in the comment.
Kevin Cruijssen

4

T-SQL, 38 bytes

SELECT QUOTENAME(a)+QUOTENAME(b)FROM i

Input is taken from a pre-existing table i with varchar fields a and b, per our IO rules.

Uses QUOTENAME, which surrounds the strings with [] and also escapes any internal brackets. Should map to a unique output.


1
Same length on MySQL: SELECT CONCAT(QUOTE(a),QUOTE(b))FROM t Try it online
Night2

4

Zsh, 7 bytes

<<<$@:q

Try it online!

Implicitly joins the arguments on spaces. The q modifier tells zsh to quote the arguments, which crucially escapes spaces, ensuring an unescaped space unambiguously separates the two arguments.

(Without q, "a " "b" and "a" " b" would both yield "a b".)


3

MATL, 1 byte

j

The code takes an array of two strings as input, and outputs a string representation of that array.

Try it online!

Explanation

The code simply reads the input as a string, unevaluated.


1
Does this really take two strings as input? It seems like this just prints the input whatever it is.Try it online!
James

1
@DJ It just reads unevaluated input, so it reads anything. Is it a loophole? A more standard approach would be to take the evaluated input as an array and then convert to string representation. But the result would be the same as my code, so I would argue that the distinction is unobservable
Luis Mendo

3

Jelly, 2 bytes

ŒṘ

A monadic Link accepting a list of two lists of characters as its argument which yields a single list of characters.

Try it online!

How?

It's a built-in to get Python's string representation, simples.


3

Haskell, 4 bytes

show

The Haskell built-in to turn things into strings. The input is taken as a pair of strings.

Try it online!


3

05AB1E, 2 bytes

₁ö

Try it online! Interprets each string as a base-256 integer, then prints the two in the form [1, 2].


05AB1E, 1 byte (unknown validity)

â

Try it online!

Takes the cartesian product of the input with itself. Quotes in the input are not escaped, which could cause confusion. I brute-forced all combinations of up to 12 ", " and "], [" and didn’t find any collision; however, I can’t prove there aren’t any collisions for longer strings. If anybody can come up with a proof or counter-example, I’d highly appreciate it!

The trivial 0-byter fails because of quotes not being escaped: inputs (", ", empty string) and (empty string, ", ") both yield the output ["", "", ""].

The 1-byter º (mirror each input string) also fails because of this: inputs (", "" ,", empty string) and (empty string, " ,"", ") both yield the output ["", "" ,"", "" ,"", ""].


3

C# with 26 bytes (thanks to Lukas Lang, Kevin Cruijssen and Jo King)

a=>b=>$"{a.Length}.{a}{b}"

tio.run lambda


1
Please consider using tio.run
Ver Nick says Reinstate Monica

This still breaks on ("a<>","b") and ("a","<>b") - note that it is impossible to handle all cases if you're just concatenating the inputs, no matter what you put between/around them - you need to modify the strings somehow
Lukas Lang

1
Sorry, still not: ("1","11111111111") and ("11111111111","1") - what does work on the other hand (and is even shorter) is this $"{a.Length}.{a}{b}" - you can always extract a and b from this without any ambiguity (just read until the first . to get the length of a, b is then the rest
Lukas Lang

1
@LukasLang Great. Thanks for the follow ups.
Soleil

1
Many thanks @JoKing !
Soleil

2

Charcoal, 12 bytes

⪫E²⭆⪪S"⪫""λ,

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

 E²             Repeat twice
     S          Input a string
    ⪪ "         Split it on `"`s
   ⭆            Map over each piece and join
       ⪫""λ     Wrap each piece in `"`s
⪫          ,    Join the two results with a `,`
                Implicitly print




1

CSS + HTML, 55 + 20 = 75 bytes

Provide the inputs in the HTML after <code> tags. Visually injects letters one by one from each input into the output. When an input is longer than the other one, visual spaces are shown for missing letter(s) of the shorter input. Also one comma is added in HTML to force visual output uniqueness (I hope).

*{position:absolute;letter-spacing:9px}code>code{left:9px
<code>abcdefg<code>hijklmn</code>,



1

Perl 6, 6 3 bytes

&dd

Try it online!

Outputs the object representation to STDERR.


I'm not familiar enough with Perl - how would you input a string containing spaces here?
negative seven

2
@negativeseven like this
Grimmy

@negativeseven Yeah sorry, I was just using a shortcut syntax for lists of strings. You can do that in a typical fashion like ["Hello, ", "World!"]
Jo King

1

Lua, 27 bytes

print(('%q%q'):format(...))

Try it online!

Full program, take input as arguments.

Inspired by zsh answer, as it also use %q modifier to use internal safe-string engine.

Also, I can think of just

('%q%q'):format

but I'm not sure if this is acceptable answer.


I don't think the second is valid since ('%q%q'):format doesn't result in an object that can, for example, be assigned to a variable. It just causes a syntax error on its own. The colon syntax is just a shortcut for '%q%q'.format('%q%q', ...) and Lua doesn't allow partial application for functions
Jo King

@JoKing Yeah, you are right, I think.
val says Reinstate Monica

1

sed, 19 bytes

N
s/ /. /g
s/\n/: /

Try it online!

N          # append the second string into the pattern space
s/ /. /g   # prefix all spaces with ".". Now ": " will not occur in the stiring
s/\n/: /   # replace the newline with ": "


1

C (gcc), 59 bytes

Thanks to Grimy for the suggestion.

Takes an array of input strings (of which "2" is the correct number for this challenge) and prints their character values, including the trailing NUL. Technically, the %p formatter used by printf is for pointers, but it works fine for displaying hex values of arbitrary integers if you're not picky about how they look!

f(s,t)char**s,*t;{for(;t=*s++;)for(;printf("%p",*t++)^5;);}

Try it online!


Nice! Here’s a 59.
Grimmy




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.