Genera; # codice


36

Relativo a: Crea un interprete; #

Nella sfida sopra menzionata il compito era quello di creare un interprete per il linguaggio esoterico ;#.

La ;#lingua

La lingua ha esattamente due comandi: ;e# (tutti gli altri caratteri sono ignorati dall'interprete):

;: Incrementa l'accumulatore

#: Modulo l'accumulatore per 127, stampa il corrispondente carattere ASCII e resetta l'accumulatore su 0.

Sfida

Dato che sono pigro ma voglio ancora testare qualche altro test, ho bisogno di un programma o di una funzione che converta il semplice testo in ;#codice.

Ingresso

L'input è una stringa, presa come argomento o tramite stdin. Conterrà solo caratteri ASCII e newline stampabili.

Produzione

L'output è il ;#programma generato ritornando o stampando su stdout. Finché il programma è valido, può contenere caratteri in eccesso diversi da #e ;poiché tutti gli altri caratteri vengono ignorati.

Esempi

Input: Hello, World!
Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

Input: ABC
Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

Input: ;#
Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

Classifica


9
Brillante! Sono contento di vedere; # sta attirando l'attenzione!
caird coinheringaahing

1
Puoi testare il tuo output qui , poiché; # + è un superset di; #.
Adám

3
L'output può contenere caratteri aggiuntivi? ;#ignora tutti gli altri caratteri, quindi il programma generato continuerebbe a funzionare.
Dennis,

2
@Benoît: il modulo è irrilevante quando si genera codice, poiché è sempre più facile generare codice che utilizza il numero minimo di ;. In secondo luogo, 127 è corretto, come indicato nella domanda collegata che contiene le specifiche del linguaggio; #.
Joey,

2
Questo non è davvero traspiling. "Genera #; codice" è un titolo migliore. Ho intenzione di cambiarlo in quello.
Mego

Risposte:



34

; # + , 40 byte

;;;;;~+++++++>~;~++++:>*(-(;~<#~):<#-*:)

Provalo online! L'input termina con un byte nullo.

Spiegazione

Il codice è diviso in due parti: generazione e iterazione.

Generazione

;;;;;~+++++++>~;~++++:>

Questo mette le costanti ;e #nella memoria in quanto tale:

;;;;;~+++++++>~;~++++:>
;;;;;                     set A to 5
     ~                    swap A and B
      +++++++             add B to A 7 times
                          (A, B) = (5*7, 5) = (35, 5)
             >            write to cell 0
              ~           swap A and B
               ;          increment A
                ~         swap A and B
                          (A, B) = (35, 6)
                 ++++     add B to A 4 times
                          (A, B) = (59, 6)
                     :    increment cell pointer
                      >   write to cell 1

Iterazione

*(-(;~<#~):<#-*:)
*                    read a character into A
 (            * )    while input is not a null byte:
  -                  flip Δ
   (     )           while A != 0
    ;                decrement
     ~               swap A and B
      <              read ";" into A
       #             output it
        ~            swap A and B
           :         decrement cell pointer
            <        read "#" into A
             #       output it
              -      flip Δ
               *     take another character from input
                :    increment cell pointer

1
Tutto questo da un linguaggio scherzoso che ho fatto quando ero annoiato. Sono lusingato.
caird coinheringaahing

@RandomUser: D è un concetto divertente con cui giocare
Conor O'Brien,

eh. Cosa succede se desidero che il programma stampi un byte null in; #?
Tuskiomi,


@ ConorO'Brien come lo inserirò nel tuo programma?
Tuskiomi,


12

Gelatina , 10 8 7 byte

O”;ẋp”#

Provalo online!

O”;ẋp”#  Main Link
O        Map over `ord` which gets the codepoint of every character
 ”;ẋ     Repeat ';' the required number of times
     ”#  '#'
    p    Cartesian Product; this puts a '#' at the end of each element in the array

Implicit Output shows as a single string

-2 byte grazie a @Emigna
-1 byte grazie a @Dennis


Potresti fare O”;ẋ;€”#invece?
Emigna

@Emigna Ah, sì, grazie. Non capisco come funzioni, ma in un certo senso lo capisco. Grazie!
HyperNeutrino,

4
;€può diventare p.
Dennis,

@Dennis Oh ora capisco come funziona. Grazie! :)
HyperNeutrino,

11

GS2 , 6 byte

■•;2•#

Provalo online!

Hexdump reversibile (xxd)

0000000: ff 07 3b 32 07 23                                ■•;2•#

Come funziona

■       Map the rest of the program over  all code points C of the input.
 •;         Push ';'.
   2        Multiply; repeat ';' C times.
    •#      Push '#'.

2
= che diamine?
Erik the Outgolfer,

1
2è il comando di moltiplicazione? GS2 è strano: P
ETHproductions

1
@EriktheOutgolfer esegue il codice per ciascuno dei punti di codice del carattere dell'input o_O
Mr. Xcoder,

@EriktheOutgolfer Sembra più fantasioso di quanto non sia. è solo una mappa e GS2 implementa le stringhe come elenchi di numeri interi.
Dennis,

@ETHproductions GS2 non è basato sui caratteri; interpreta il codice sorgente come un flusso di byte non elaborato e di solito non esiste alcuna connessione tra l'istruzione e il carattere CP-437 codificato dal byte. Nel codice byte x86_64, 2è XOR ...
Dennis,

10

Taxi, 779 byte

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[c]Switch to plan "e" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:n 1 l 3 l 3 l.Pickup a passenger going to The Underground.Go to Writer's Depot:w 1 r.[p]; is waiting at Writer's Depot.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to The Underground:n 1 r 1 l.Switch to plan "n" if no one is waiting.Pickup a passenger going to The Underground.Go to Zoom Zoom:n 3 l 2 r.Go to Writer's Depot:w.Switch to plan "p".[n]# is waiting at Writer's Depot.Go to Writer's Depot:n 3 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Switch to plan "c".[e]

Provalo online!

Ungolfed:

Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
[c]
Switch to plan "e" if no one is waiting.
Pickup a passenger going to Charboil Grill.
Go to Charboil Grill: north 1st left 3rd left 3rd left.
Pickup a passenger going to The Underground.
Go to Writer's Depot: west 1st right.
[p]
; is waiting at Writer's Depot.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Go to The Underground: north 1st right 1st left.
Switch to plan "n" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north 3rd left 2nd right.
Go to Writer's Depot: west.
Switch to plan "p".
[n]
# is waiting at Writer's Depot.
Go to Writer's Depot: north 3rd left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
Switch to plan "c".
[e]

Spiegazione:

Pick up stdin and split it into characters.
Covert each character to ASCII.
Print ";" as you count down from that ASCII to zero.
Print "#".
Pickup the next character and repeat until done.

+1 Adoro solo lingue come questa e Mornington Crescent, il codice è così bello!
Karl-Johan Sjögren,

9

05AB1E , 8 byte

Ç';×'#«J

Provalo online!

Spiegazione

Ç          # convert each input char to its ascii value
 ';×       # repeat ";" those many times
    '#«    # append a "#" to each run of semi-colons
       J   # join to string

9

Brainfuck, 43 bytes

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

Null byte terminates the program.

Explanation

+[+[<]>->++]          59 (semicolon) location 5
--[>--<+++++++]>-       35 (hash) location 7
<,[                     input location 6
    [   while input byte not 0
        <.>     print semicolon
        -       decrement input byte
    ]
    >.< print hash
,]  loop while input not null

That's impressively small for Brainf*ck.
MD XF

almost competes with the python answer. Impressive.
raddish0

7

Python 3, 39 bytes

[print(";"*ord(s)+"#")for s in input()]

Try it online!


2
for s in input():print(";"*ord(s)+"#") is one byte shorter.
ovs

1
@ovs that moment when you assume a list comprehension is shorter.
Mr. Xcoder

1
That doesn't accept a string with a newline does it?
Tim

5

><>, 22 bytes

i:0(?;\"#"o
o1-:?!\";"

Try it online, or at the fish playground

Input is STDIN, output is STDOUT. In ><>, characters and ASCII codes are the same thing, so all we need to do is read a character, print ";" and decrement the character until it's 0, then print "#" and loop until there's no more input left.


5

F#, 79 bytes

let c i=System.String.Join("#",Seq.map(fun c->String.replicate(int c)";")i)+"#"

Try it online!

Expanded

// string -> string
let convert input =
    System.String.Join(
        "#",      // join the following char seq with "#"
        input     // replicate ";" n times where n = ASCII value of char c
        |> Seq.map (fun c-> String.replicate (int c) ";") 
    ) + "#" // and add the last "#" to the output

convert takes the input string and outputs a ;# program

Usage

convert "Hello, World!" |> printfn "%s"
convert "ABC" |> printfn "%s"
convert ";#" |> printfn "%s"

4
We need more F# answer
aloisdg says Reinstate Monica

@aloisdg I'll do my best :)
Brunner


5

PowerShell, 29 27 25 bytes

$args|% t*y|%{';'*$_+'#'}

Pretty straightforward. Takes input as command-line argument. Output is a valid ;# program that prints the requested text.


It need to join result strings.
mazzy

@mazzy: From the task description: »As long as the program is valid, it may contain excess characters other than # and ; as all other characters are ignored.«
Joey

as you wish :-)
mazzy

quotation marks can be removed. $args is enough.
mazzy

Unless the argument is numeric.
Joey

4

brainfuck, 47 bytes

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

Try it online!

See also: ovs's answer, which takes a similar approach, but with a different method of generating constants and a different cell layout.


Explanation:

This challenge lines up with the brainfuck spec pretty well, which means the solution is essentially trivial. Brainfuck takes input as ASCII values, which is exactly what ;# need to output as.

The schematic for transpiling is simple: Generate the ASCII value for ; and #, print ; equal to the ASCII value of the input character, print #, repeat for every input.

+++++++[-             7
         >++++++++       * 8 = 56
         >+++++<<        * 5 = 35 (#)
       ]>+++<                  56 + 3 = 59 (;)
,[                    Input into first cell
  [>.<-]              Print ;'s equal to ASCII input
  >>.<<,              Print one #
 ]                    End on EOF

-2 Bytes Only -1 if you’re avoiding negative cells
Jo King

4

Mathematica, 49 bytes

StringRepeat[";",#]<>"#"&/@ToCharacterCode@#<>""&

Explanation

enter image description here

Converts the input string to a list of character codes, then Maps the function StringRepeat[";",#]<>"#"& over the list, then StringJoins the result with the empty string.


Why do you need the <>""?
CalculatorFeline

@CalculatorFeline Without it I would be left with a list of strings for each character. StringJoining (<>) the empty string concatenates each string.
ngenisis

Forgot about that :P
CalculatorFeline

3

Aceto, 19 bytes

Since there's an interpreter in Aceto, I thought there outta be an Aceto answer to this challenge as well. It fits neatly in a 2rd order Hilbert curve:

\n;*
'o'p
`!#'
,dpO

First of all, we read a single character (,) and duplicate and negate it to test whether it is a newline (d!, when reading a newline, an empty character is normally pushed on the stack). I then use what I think is a pretty clever trick to handle the newline case compactly:

`'\n

If the value on the stack is True (we read a newline), that code means: do (`) put a character literal on the stack ('), which is a newline: \n.

If the value on the stack is False (we didn't read a newline), that code means: don't (`) read a character literal ('). That means the next character is executed as a command. Fortunately, a backslash escapes the next command (it makes it so that it doesn't get executed), so n doesn't print a newline (which is what n usually does).

The rest of the code is straightforward; we convert the character on the stack to the integer of its unicode codepoint (o), we push a literal semicolon (';), multiply the number with the string (*, like in Python), print the result, push a literal (') #, print it too, and go back to the Origin.

Run with -F if you want to see immediate results (because buffering), but it works without, too.


3

Perl, 24 bytes

s/./";"x(ord$&)."#"/ges

Run with perl -pe.

Alternative solution:

say";"x ord,"#"for/./gs

Run with perl -nE.


3

Solace, 11 bytes

Yay, new languages.

';@jx{'#}Ep

Explanation

';           Push the code point of ';' (59).
  @j         Push the entire input as a list of code points.
    x        For each code point in the input, repeat 59 that many times.
     {  }E   For each resulting list of 59s:
      '#      Push the code point of '#' (35).
          p  Flatten and print as unicode characters.

3

Fourier, 19 bytes

$(I(`;`&j)`#`0~j&i)

Try it on FourIDE!

To run, you must enclose the input string in quotation marks.

Explanation pseudocode

While i != Input length
    temp = pop first char of Input
    While j != Char code of temp
        Print ";"
        Increment j
    End While
    Print "#"
    j = 0
    Increment i
End While


3

JavaScript, 55 54 51 50 48 bytes

s=>1+[...s].map(c=>";".repeat(Buffer(c)[0])+"#")

Try it online

  • 1 byte saved thanks to Neil.

Alternatives

If we can take input as an array of individual characters then 5 bytes can be saved.

a=>1+a.map(c=>";".repeat(Buffer(c)[0])+"#")

If we can also output as an array then 2 more bytes can be saved.

a=>a.map(c=>";".repeat(Buffer(c)[0])+"#")

\n should becomes ;;;;;;;;;;#.
Neil

Hmm ... that's strange. Guess I'll have to roll back to the longer solution, so. Thank, @Neil.
Shaggy

2
I think you could change . to [^], which would still leave it a byte shorter than map/join?
Neil

Yup, that did the job, @Neil :)
Shaggy

Just a heads up, the join() in your previous answer was unnecessary given the specification for ;#, and you can also declare that the input for your function is an array of characters, though the second suggestion is a bit of a stretch. Either way, that brings you down to at most 48 bytes.
Patrick Roberts

2

Actually, 11 bytes

O⌠';*'#o⌡MΣ

Try it online!

Explanation:

O⌠';*'#o⌡MΣ
O            convert string to list of ASCII ordinals
 ⌠';*'#o⌡M   for each ordinal:
  ';*          repeat ";" that many times
     '#o       append "#"
          Σ  concatenate

2

APL (Dyalog), 18 bytes

'#',¨⍨';'⍴¨⍨⎕UCS

Try it online!

⎕UCS Convert to Unicode code points

';'⍴¨⍨ use each code point to reshape ( = RhoR; Reshape) a semicolon

#',¨⍨ append a hash to each string


2

Ruby, 28 25 bytes

24 bytes, plus the -n command line switch to repeatedly operate on stdin.

$_.bytes{|b|$><<?;*b+?#}

3 bytes saved (and output corrected on newlines!) thanks to manatwork.


You could avoid the use of .ord by working directly with character codes: $_.bytes{|b|$><<?;*b+?#}. There is difference: this one also encodes the newline in the input. Not sure what the question owner intends to say by “It will only contain printable ASCII characters and newlines.”, but to me sounds like newlines should be encoded too.
manatwork

Your Ruby-fu exceeds mine, @manatwork - I'd forgotten about bytes. I've asked OP about newlines up top and will edit this afterwards.
Chowlett


2

Alice, 12 bytes

'#I.h%&';d&O

Try it online!

Explanation

'#    Push 35, the code point of '#'.
I     Read a code point C from STDIN. Pushes -1 at EOF.
.h%   Compute C%(C+1). For C == -1, this terminates the program due to division
      by zero. For C > -1, this just gives back C, so it does nothing.
&';   Pop C and push that many 59s (the code point of ';').
d     Push the stack depth, which is C+1.
&O    Print that many code points from the top of the stack.
      The IP wraps around to the beginning and another iteration of this
      loop processes the next character.

2

PHP, 48 bytes

for(;$c?:~$c=~ord($argn[$i++]);)echo";#"[!++$c];

2

jq, 30 characters

(26 characters code + 4 characters command line options)

explode|map(";"*.+"#")|add

Sample run:

bash-4.4$ jq -Rr 'explode|map(";"*.+"#")|add' <<< 'Hello, World!' | jq -Rrj '[scan(".*?#")|gsub("[^;]";"")|length%127]|implode'
Hello, World!

On-line test



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.