Semplice rendering markdown


20

Esistono diversi modi per creare intestazioni sui post sulla rete Stack Exchange. Il formato più comunemente usato 1 su PPCG sembra essere:

# Level one header
## Level two header
### Level three header

Nota lo spazio dopo i segni di hash. Inoltre, si noti che i segni di hash finali non sono inclusi.

Sfida:

Prendi una stringa (possibilmente multilinea) come input e genera la stringa nel seguente formato:

  • Se l'intestazione è di livello 1, quindi emettere ogni lettera 4 per 4 volte
  • Se l'intestazione è di livello 2, quindi emettere ogni lettera 3 per 3 volte
  • Se l'intestazione è di livello 3, quindi emettere ogni lettera 2 per 2 volte
  • Se una riga non è un'intestazione, la emette così com'è.

Illustrare:

--- Level 1 ---
# Hello
--- Output---
HHHHeeeelllllllloooo    
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo

--- Level 2 ---
## A B C def
--- Output ---
AAA   BBB   CCC   dddeeefff
AAA   BBB   CCC   dddeeefff
AAA   BBB   CCC   dddeeefff

--- Level 3 ---
### PPCG!
--- Output---
PPPPCCGG!!
PPPPCCGG!!

Semplice come quella!


Regole:

  • È necessario supportare l'input su più righe. L'uso di \necc. Per newline è OK.
    • Non ci saranno righe contenenti solo un #seguito da un singolo spazio
  • L'output deve essere presentato su più righe. Non è possibile eseguire l'output \nanziché letteralmente nuove righe.
    • Gli spazi finali e le nuove righe sono OK.

Casi test:

Input e output sono separati da una riga di ....

# This is a text
with two different
### headers!
........................................................    
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
with two different
hheeaaddeerrss!!
hheeaaddeerrss!!

This input has
## trailing hash marks ##
#and a hash mark without a space after it.
........................................................    
This input has
tttrrraaaiiillliiinnnggg   hhhaaassshhh   mmmaaarrrkkksss   ######
tttrrraaaiiillliiinnnggg   hhhaaassshhh   mmmaaarrrkkksss   ######
tttrrraaaiiillliiinnnggg   hhhaaassshhh   mmmaaarrrkkksss   ######
#and hash marks without a space after it.

# This ## is ### strange
#### ###
........................................................
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
#### ###

Multiple


### newlines! # 
:)
........................................................    
Multiple


nneewwlliinneess!!  ##
nneewwlliinneess!!  ##
:)

Line with only a hash mark:
#
### ^ Like that!
........................................................    
Line with only a hash mark:
#
^^  LLiikkee  tthhaatt!!
^^  LLiikkee  tthhaatt!!

1: non ho verificato, ma penso sia vero.


Possiamo prendere l'input come array di stringhe?
Ian H.

Risposte:


7

Impilato , 51 50 byte

Salvato 1 byte grazie a @RickHitchcock - golf regex

['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]

Provalo online!

Funzione anonima che accetta input dallo stack e lo lascia nello stack.

Spiegazione

['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]
[                                            mrepl]   perform multiline replacement
 '^(##?#?) (.+)'                                     regex matching headers
                [                        ]3/         on each match:
                 \#'                                   count number of hashes
                    5\-                                5 - (^)
                       @k                              set k to number of repetitions
                          CS                           convert the header to a char string
                             k*                        repeat each char `k` times
                               k rep                   repeat said string `k` times
                                     LF#`              join by linefeeds

3

JavaScript (ES6), 111 105 byte

6 byte salvati grazie a @Shaggy

s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>`
${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim())

Corrisponde a 1-3 hash all'inizio della stringa o preceduto da una nuova riga, quindi ripete ogni carattere della partita insieme alla corrispondenza stessa, in base alla lunghezza degli hash.

Casi test:


2

Retina , 125 104 byte

m(`(?<=^# .*).
$0$0$0$0
(?<=^## .*).
$0$0$0
(?<=^### .*).
$0$0
^# 
$%'¶$%'¶$%'¶
^## 
$%'¶$%'¶
^### 
$%'¶

Provalo online

Risparmiato 21 byte grazie a Neil.


Salvare 3 byte utilizzando %)sul terzo stadio che consente di rimuovere i messaggi di posta %elettronica sui primi due livelli. Inoltre uno normalmente mette il Gdopo la (s (di cui ora ne avrai bisogno due) nell'intestazione.
Neil,

Meglio ancora, è possibile utilizzare m)o m(che ora salva 9 byte perché è quindi possibile rimuovere tutti gli altri m.
Neil,

L'intestazione si è rivelata superflua. Inoltre, ho salvato altri 12 byte: provalo online!
Neil,

Oh, sì, ero abituato a usare l'intestazione per più casi di test.
mbomb007,

2

MATL , 43 42 40 byte

1 byte rimosso grazie a Rick Hitchcock !

`j[]y'^##?#? 'XXgn:(2M4:QP&mt~+t&Y"0YcDT

Ciò genera uno spazio finale in ciascuna riga (consentito dalla sfida) e termina con un errore (consentito per impostazione predefinita) dopo aver prodotto l'output.

Provalo online!

Spiegazione

`            % Do...while loop
  j          %   Input a line as unevaluated string
  []         %   Push empty array
  y          %   Duplicate from below: push input line again
  '^##?#? '  %   Push string for regexp pattern
  XX         %   Regexp. Returns cell array with the matched substrings
  g          %   Get cell array contents: a string, possibly empty
  n          %   Length, say k. This is the title level plus 1, or 0 if no title
  :(         %   Assign the empty array to the first k entries in the input line
             %   This removing those entries from the input
  2M         %   Push k again
  4:QP       %   [1 2 3 4], add 1 , flip: pushes [5 4 3 2]
  &m         %   Push index of k in that array, or 0 if not present. This gives
             %   4 for k=2 (title level 1), 3 for k=3 (tile level 2), 2 for k=2
             %   (title level 1), and 0 for k=0 (no title). The entry 5 in the
             %   array is only used as placeholder to get the desired result.
  t~+        %   Duplicate, negate, add. This transforms 0 into 1
  t&Y"       %   Repeat each character that many times in the two dimensions
  0Yc        %   Postpend a column of char 0 (displayed as space). This is 
             %   needed in case the input line was empty, as MATL doesn't
             %   display empty lines
  D          %   Display now. This is needed because the program will end with
             %   an error, and so implicit display won't apply
  T          %   True. This is used as loop condition, to make the loop infinite
             % End (implicit)

Mi chiedevo quale fosse il modo migliore per farlo in MATLAB ... Il prodotto Kronecker era ovviamente il modo migliore per farlo :) Bello!
Stewie Griffin,

@StewieGriffin Quando ho visto la sfida ho pensato subito al prodotto Kronecker. Ma ho appena trovato un modo che è più breve di 2 byte usando repelem( Y"in MATL). kronè ancora probabilmente il modo più breve in MATLAB
Luis Mendo il


1

Carbone , 46 byte

FN«Sι≔⊕⌕E³…⁺×#κι⁴### θF⎇θ✂ι⁻⁵θLι¹ι«G↓→↑⊕θκ→»D⎚

Provalo online! Il collegamento è alla versione dettagliata del codice. Il carbone non fa realmente l'input di array di stringhe, quindi ho dovuto aggiungere la lunghezza dell'array come input. Spiegazione:

FN«Sι

Passa il numero appropriato di stringhe di input.

≔⊕⌕E³…⁺×#κι⁴### θ

Crea un array di stringhe prendendo l'input e aggiungendo il prefisso fino a 2 #, quindi troncandolo alla lunghezza 4, quindi prova a trovare ###l'array, quindi converti in 1-indicizzazione. Ciò si traduce in un numero inferiore di uno allo zoom della lettera.

F⎇θ✂ι⁻⁵θLι¹ι«

Se lo zoom della lettera è 1, passa sopra l'intera stringa altrimenti passa sopra il suffisso appropriato (che è irragionevolmente difficile da estrarre in carbone).

G↓→↑⊕θκ→

Disegna un poligono riempito con la lettera che termina nell'angolo in alto a destra, quindi spostati a destra pronto per la lettera successiva.

»D⎚

Stampa l'output e ripristina pronto per la stringa di input successiva.


1

SOGL V0.12 , 31 28 byte

¶Θ{■^##?#? øβlF⁄κ6κ5%:GI*∑∙P

Provalo qui! - codice aggiuntivo aggiunto perché il codice è una funzione e accetta input nello stack (SOGL non può accettare input multilinea altrimenti: /) - inputs.value”- invia quella stringa, - valuta come JS, F- chiama quella funzione

Spiegazione:

¶Θ                            split on newlines
  {                           for each item
   ■^##?#?                      push "^##?#? "
           øβ                   replace that as regex with nothing
             l                  get the new strings length
              F⁄                get the original strings length
                κ               and subtract from the original length the new strings length
                 6κ             from 6 subtract that
                   5%           and modulo that by 5 - `6κ5%` together transforms 0;2;3;4 - the match length to 1;4;3;2 - the size
                     :          duplicate that number
                      G         and get the modified string ontop
                       I        rotate it clockwise - e.g. "hello" -> [["h"],["e"],["l"],["l"],["o"]]
                        *       multiply horizontally by one copy of the size numbers - e.g. 2: [["hh"],["ee"],["ll"],["ll"],["oo"]]
                         ∑      join that array together - "hheelllloo"
                          ∙     and multiply vertiaclly by the other copy of the size number: ["hheelllloo","hheelllloo"]
                           P    print, implicitly joining by newlines

0

Proton , 130 byte

x=>for l:x.split("\n"){L=l.find(" ")print(L>3or L+len(l.lstrip("\#"))-len(l)?l:"\n".join(["".join(c*(5-L)for c:l[L+1to])]*(5-L)))}

Provalo online!


Penso che non ti sia permesso di ricevere e restituire un elenco di righe, le regole sono piuttosto rigide: devi supportare input su più righe. , L'output deve essere presentato su più righe. Non puoi generare \ n invece di newline letterali. .
Mr. Xcoder,

@ Mr.Xcoder Whoops, mio ​​cattivo. Fissaggio.
HyperNeutrino,

Nota: va bene se l'input ha \n, ma l'output dovrebbe essere mostrato con nuove righe letterali.
Stewie Griffin,

@ mbomb007 Whoops, ho dimenticato di inserire il file 5-. Siamo spiacenti
HyperNeutrino il

@ mbomb007 riparato
HyperNeutrino

0

Python 3 , 147 byte

def f(x):
	for l in x.split("\n"):L=l.find(" ");print(L>3or L+len(l.lstrip("#"))-len(l)and l or"\n".join(["".join(c*(5-L)for c in l[L+1:])]*(5-L)))

Provalo online!

-1 byte grazie a Mr. Xcoder


@ mbomb007 Whoops, ho dimenticato di inserire il file 5-. Siamo spiacenti
HyperNeutrino il

0

C # (.NET Core) , 268 + 18 byte

n=>{var r="";for(int l=0,c;l<n.Length;l++){var m=n[l];var s=m.Split(' ');var y=s[0];if(!y.All(x=>x==35)|y.Length>3|s.Length<2)r+=m+'\n';else for(int i=0,k=y.Length;i<5-k;i++){for(c=1;c<m.Length-k;)r+=new string(m.Substring(k,m.Length-k)[c++],5-k);r+='\n';}}return r;};

Provalo online!


0

Python 3 , 131 byte

from re import*
print(sub("^(#+) (.*?)$",lambda x:((sub('(.)',r'\1'*(5-len(x[1])),x[2])+'\n')*(5-len(x[1])))[:-1],input(),flags=M))

Provalo online!

Ho usato Python 3 per usarlo []con regex.


0

PHP, 122 + 1 byte

for($y=$z=" "==$s[$i=strspn($s=$argn,"#")]&&$i?5-$i++:1+$i=0;$y--;print"
")for($k=$i;~$c=$s[$k++];)echo str_pad($c,$z,$c);

Esegui come pipe con -nR(funzionerà su una riga di input dopo l'altra) o provalo online .


0

J , 55 byte

([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)]

Non so come far funzionare TIO con J regex, quindi non posso fornire un link funzionante.

Ecco come testarlo nell'interprete J (testato con J804)

   f=.([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)]
   txt=.'# Hello'; '## A B C def'; '### PPCG!'; '#and a hash mark without a space after it.'; '##### ###'
   ; f each txt

HHHHeeeelllllllloooo                      
HHHHeeeelllllllloooo                      
HHHHeeeelllllllloooo                      
HHHHeeeelllllllloooo                      
AAA   BBB   CCC   dddeeefff               
AAA   BBB   CCC   dddeeefff               
AAA   BBB   CCC   dddeeefff               
PPPPCCGG!!                                
PPPPCCGG!!                                
#and a hash mark without a space after it.
##### ###

Simulo una stringa multilinea attraverso un elenco di stringhe inscatolate.


0

Python 2 , 126 124 117 byte

while 1:l=raw_input();i=l.find(' ');v=5-i*(l[:i]in'###');exec"print[l,''.join(c*v for c in l[i+1:])][v<5];"*(v>4or v)

Provalo online!

o

while 1:l=raw_input();i=l.find(' ');t=''<l[:i]in'###';exec"print[l,''.join(c*(5-i)for c in l[i+1:])][t];"*(t<1or 5-i)

Provalo online!


0

JavaScript, 112 byte

x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join`
`)(5-n.length))


Non penso che funzioni per #### ##.
Rick Hitchcock,

@RickHitchcock fixed
tsh

0

C # 4,5 158 byte

Dove i è l'input sotto forma di una stringa.

int l,m,t,s=0;while(i[s]=='#'){s++;};t=s>0?4-s+1:1;for(l=0;l<t;l++){foreach(char c in i.Skip(s>0?s+1:0))for(m=0;m<t;m++)Console.Write(c);Console.WriteLine();}
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.