Snakify una stringa


35

Una stringa snakified si presenta così:

T AnE eOf ifi ing
h s x l A k e r
isI amp Sna dSt

Il tuo compito

Prendi una stringa se una dimensione n, quindi genera la stringa snakified. Gli input ThisIsAnExampleOfaSnakifiedStringe 3produrrebbero l'esempio sopra.

specificazioni

  • s conterrà solo caratteri ASCII tra i punti di codice 33 e 126 inclusi (senza spazi o newline).
  • s avrà una lunghezza compresa tra 1 e 100 caratteri.
  • nè un numero intero che rappresenta la dimensione di ciascun segmento di stringa di output. Ogni linea di caratteri (su / giù o sinistra / destra) che compongono le curve nel "serpente" è nlunga. Vedi i casi di test per esempi.
  • n sarà compreso tra 3 e 10 inclusi.
  • La stringa di output inizia sempre a puntare verso il basso.
  • Sono consentiti spazi finali su ogni riga.
  • Sono consentite anche nuove righe finali alla fine dell'output.
  • Gli spazi iniziali non sono ammessi.
  • significa vincita del codice più corto in byte.

Casi test

a 3

a

----------

Hello,World! 3

H Wor
e , l
llo d!

----------

ProgrammingPuzzlesAndCodeGolf 4

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

----------

IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot. 5

I   gramW   tStri   100Ch   gBeca   CaseW   DoesN
H   o   o   u   n   e   a   n   u   t   i   t   o
o   r   r   p   g   r   r   o   s   s   l   I   t
p   P   k   n   s   A   a   L   e   e   l   f   .
eYour   sForI   Which   cters   ThisT   FailI

----------

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 10

!        <=>?@ABCDE        `abcdefghi
"        ;        F        _        j
#        :        G        ^        k
$        9        H        ]        l
%        8        I        \        m
&        7        J        [        n
'        6        K        Z        o        ~
(        5        L        Y        p        }
)        4        M        X        q        |
*+,-./0123        NOPQRSTUVW        rstuvwxyz{

Immagino che la prossima sfida sarà quella di convertire una stringa snakified ai 2 parametri originali ...
— abligh

@abligh Non avevo altri piani, ma in realtà sembra un'idea decente. Potrebbe esserci una qualche forma di duplicato, quindi dovrò verificarlo prima. Rimanete sintonizzati!
— user81655

la sfida inversa sarebbe più divertente se il serpente può avere una forma arbitraria ...
— circa

@abligh Questo è esattamente quello che stavo pensando di fare ahah!
— user81655

@abligh Done!
— user81655

Risposte:


9

Pyth, 48 45 44 43 42 byte

=Y0juXGZX@G~+Z-!J%/HtQ4q2J~+Y%J2@zHlzm*;lz

Provalo online.

Questo approccio fa lo stesso abuso di spazio bianco finale della risposta di Ruby.


3
Cancellati 44 sono ancora 44 ... ancora.
— Arcturus,

12

Rubino, 87 byte

->s,n{p=0
a=(' '*(w=s.size)+$/)*n
w.times{|i|a[p]=s[i];p+=[w+1,1,-w-1,1][i/(n-1)%4]}
a}

Qualche piccolo abuso della regola Trailing spaces on each line are allowed.Ogni riga di output è wcomposta da caratteri lunghi, più una nuova riga, dove wè la lunghezza della stringa originale, ovvero abbastanza lunga da contenere l'intero input. Quindi c'è abbastanza spazio bianco non necessario a destra per grandi n.

Non registrato nel programma di test

f=->s,n{
  p=0                            #pointer to where the next character must be plotted to
  a=(' '*(w=s.size)+$/)*n        #w=length of input. make a string of n lines of w spaces, newline terminated
  w.times{|i|                    #for each character in the input (index i)
    a[p]=s[i]                    #copy the character to the position of the pointer
    p+=[w+1,1,-w-1,1][i/(n-1)%4] #move down,right,up,right and repeat. change direction every n-1 characters
  }
a}                               #return a

puts $/,f['a',3]

puts $/,f['Hello,World!',3]

puts $/,f['ProgrammingPuzzlesAndCodeGolf',4]

puts $/,f['IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.',5]

puts $/,f['!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',10]

7

JavaScript (ES6), 143 byte

(s,n)=>[...s].map((c,i)=>(a[x][y]=c,i/=n)&1?y++:i&2?x--:x++,a=[...Array(n--)].map(_=>[]),x=y=0)&&a.map(b=>[...b].map(c=>c||' ').join``).join`\n`

Dove \nrappresenta una newline letterale. Ungolfed:

function snakify(string, width) {
    var i;
    var result = new Array(width);
    for (i = 0; i < width; i++) result[i] = [];
    var x = 0;
    var y = 0;
    for (i = 0; i < string.length; i++) {
       result[x][y] = string[i];
       switch (i / (width - 1) & 3) {
       case 0: x++; break;
       case 1: y++; break;
       case 2: x--; break;
       case 3: y++; break;
    }
    for (i = 0; i < width; i++) {
        for (j = 0; j < r[i].length; j++) {
            if (!r[i][j]) r[i][j] = " ";
        }
        r[i] = r[i].join("");
    }
    return r.join("\n");
}

7

Pyth, 85 74 59 byte

Kl@Q0J0=Y*]d-+*@Q1K@Q1 1FNr1@Q1=XY-+*KNN1b;VK=XYJ@@Q0N=+J@[+K1 1-_K1 1).&3/N-@Q1 1;sY

=G@Q1=H@Q0KlHJ0=Y*]dt+*GKGFNr1G=XYt+*KNNb;VK=XYJ@HN=+J@[hK1t_K1).&3/NtG;sY

Klz=Ym;+*QKQVQ=XYt+*KhNhNb;VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;sY

Grazie a @FryAmTheEggman per avermi aiutato moltissimo!

Ho giocato a golf il più possibile. Provalo qui! Per qualche motivo, il ritorno a capo rende strano l'output. Potresti voler dare un'occhiata all'output a pagina intera

Spiegazione

Respira un secondo e concentrati. Questo può essere suddiviso in tre sezioni, come quasi tutti gli algoritmi "classici".

La prima sezione

È dove vengono inizializzate le variabili. Può essere diviso in due parti:

Klz=Ym;+*QKQ
Klz                Assign len(input[0]) to K. (length of input String)
   =Ym;+*QKQ       Assign an empty list to Y of length K*input[1]-input[1]-1, where input[1] is the size of the snake 
                   (thus the height of the final string)

la seconda parte :

VQ=XYt+*KhNhNb;
VQ                       For N in range(0, input[1]), where input[1] is the size of the snake 
  =                        Assign to Y. Y is implicit, it is the last variable we used.
   XYt+*KhNhNb               Y[K*N+N-1]="\n". Can be broken down in four parts :
   X                           Replace function. X <A: list> <B: int> <C: any> is A[B]=C
    Y                          A: The array we initialized in the first section.
     t+*KhNhN                  B: K*(N+1)+N+1 (N is the for loop variable)
             b                 C: Newline character ("\n")
              ;          End the loop.

La seconda sezione

Contiene la logica attuale.

VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;
VK                                         For N in range(0, K), where K is the length of the input string (see first section)
  =                                          Assign to Y. Y is implicit, it is the last variable we used.
   XYZ@zN                                    Same as in section 2. This is a replacement function. Y[Z] = input[0][N]. Z is initially 0.
         =+Z@[hK1_hK1).&3/NtQ                Again this can be broken down :
         =+Z                                   Add to Z
             [hK1_hK1)                         Array containing directions. Respectively [K+1, 1, -K-1, 1]
            @         .&3/NtQ                  Lookup in the array, on index .&3/N-@Q1 1:
                      .&3                        Bitwise AND. .& <int> <int>
                         /NtQ                    (input[1]-1)/N, where input[1] is the size of the snake
                             ;             End the loop

La terza sezione

Questa è la parte di output. Non molto interessante ...

sY    Join the array Y. Implicitly print.

BONUS

Ho scritto il programma Pyth da questo script Python.

input=["ThisIsAnExampleOfASnakifiedString", 4];
width=len(input[0]);
height=input[1];
pointer=0;
directions = [width+1,1,-width-1,1] #Respectively Down, right, up, right (left is replaced by right because of snake's nature. Doesn't go left).
output=[' ' for i in range(0, width*height+height-1)];
for N in range(1, height):
    output[width*N+N-1]="\n";
for N in range(0, len(input[0])):  
    output[pointer]=input[0][N];
    pointer+=directions[3&(N/(height-1))];
print "".join(output);

5

JavaScript (ES6), 122 byte

document.write("<pre>"+(

// --- Solution ---
s=>n=>[...s].map((c,i)=>(a[p]=c,p+=[l+1,1,-l-1,1][i/n%4|0]),p=0,a=[...(" ".repeat(l=s.length)+`
`).repeat(n--)])&&a.join``
// ----------------

)("IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.")(5))

Stesso algoritmo della risposta di @ LevelRiverSt.


4

C, 138 byte

char*h[]={"\e[B\e[D","","\e[A\e[D",""},t[999];i;main(n){system("clear");for(scanf("%s%d",t,&n),--n;t[i];++i)printf("%c%s",t[i],h[i/n%4]);}

Questo utilizza escape ANSI. Funziona nel terminale Linux.

Ungolfed:

char*h[]={"\e[B\e[D","","\e[A\e[D",""},
    /* cursor movement - h[0] moves the cursor one down and one left,
    h[2] moves the cursor one up and one left. */
t[999];i;
main(n){
    system("clear");
    for(scanf("%s%d",t,&n),--n;t[i];++i)
        printf("%c%s",t[i],h[i/n%4]);
}

1

JavaScript (ES6), 131

Algoritmo: mappare la posizione x,yin uscita sull'indice nella stringa di input, in qualche modo come questa risposta (non correlata).

Ho preso in prestito da @LevelRiverSt il trucco di mantenere la larghezza orizzontale uguale alla lunghezza di input.

a=>m=>eval('for(--m,t=y=``;y<=m;++y,t+=`\n`)for(x=0;a[x];)t+=a[2*(x-x%m)+((h=x++%(2*m))?h-m?!y&h>m?h:y<m|h>m?NaN:m+h:m-y:y)]||`.`')

Meno golf

Questa è stata la prima bozza di lavoro prima del golf

f=(a,n)=>{
  l=a.length
  m=n-1
  s=m*2 // horizontal period

  b=-~(~-l/s)*m // total horizontal len, useless in golfed version
  t=''
  for(y=0;y<n;y++)
  {
    for(x=0;x<b;x++)
    {
      k = x / m | 0
      h = x % s
      if (h ==0 )
        c=k*s+y
      else if (h == m)
        c=k*s+m-y
      else if (y == 0 && h>m)
        c=k*s+h
      else if (y == m && h<m)
        c=k*s+m+h
      else
        c=-1
      t+=a[c]||' '
    }
    t+='\n'
  }
  return t
}  

Test

F=a=>m=>eval('for(--m,t=y=``;y<=m;++y,t+=`\n`)for(x=0;a[x];)t+=a[2*(x-x%m)+((h=x++%(2*m))?h-m?!y&h>m?h:y<m|h>m?NaN:m+h:m-y:y)]||` `')

function test()
{
  var n=+N.value
  var s=S.value
  O.textContent=F(s)(n)
}  

test()
#S {width:80%}
#N {width:5%}
<input id=N value=5 type=number oninput='test()'>
<input id=S 5 oninput='test()'
value='IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.'>
<pre id=O></pre>


0

Pyth, 122 byte

=k@Q0J-@Q1 1K*4J=T*@Q1[*lkd;Vlk=Z+*%NJ/%N*J2J*/N*J2J=Y.a-+**/%N*J2J!/%NK*J2J*%NJ!/%N*J2J**!/%N*J2J/%NK*J2J XTYX@TYZ@kN;jbT

Ho creato una formula per calcolare le posizioni x, y di ciascun carattere in base alla dimensione / modulo del segmento, ma sono diventati più grandi di quanto mi aspettassi: c

Spiegazione:

=k@Q0                                                                                                                     # Initialize var with the text
     J-@Q1 1                                                                                                              # Initialize var with the segment size (minus 1)
            K*4J                                                                                                          # Initialize var with the "block" size (where the pattern start to repeat)
                =T*@Q1[*lkd;                                                                                              # Initialize output var with an empty array of strings
                            Vlk                                                                                           # Interate over the text
                               =Z+*%NJ/%N*J2J*/N*J2J                                                                      # Matemagics to calculate X position
                                                    =Y.a-+**/%N*J2J!/%NK*J2J*%NJ!/%N*J2J**!/%N*J2J/%NK*J2J                # Matemagics to calculate Y position
                                                                                                          XTYX@TYZ@kN;    # Assign the letter being iterated at x,y in the output
                                                                                                                      jbT # Join with newlines and print the output

Prova qui

Per le formule matematiche, ho usato mod per generare flag 0/1 e quindi moltiplicato per un fattore basato sull'input, ho naggiunto il foglio di calcolo ad ogni passaggio sul muggito dello snippet


Puoi spiegare Matemagics? cioè scriverli in un modo più umano-moda?
— FliiFe,

@FliiFe done c:
— Rod

0

PHP, 127 126 124 120 119 118 117 110 106 byte

Utilizza la codifica ISO-8859-1.

for(;($q=&$o[$y+=$d]||$q=~ÿ)&&~Ï^$q[$x+=!$d]=$argv[1][$a];$a++%($argv[2]-1)?:$d-=-!$y?:1)?><?=join(~õ,$o);

Esegui in questo modo ( -daggiunto solo per l'estetica):

php -r 'for(;($q=&$o[$y+=$d]||$q=~ÿ)&&~Ï^$q[$x+=!$d]=$argv[1][$a];$a++%($argv[2]-1)?:$d-=-!$y?:1)?><?=join(~õ,$o);' "Hello W0rld!" 3 2>/dev/null;echo

Ungolfed:

// Iterate over ...
for (
    ;
    // ... the characters of the input string. Prepend `0` so a 0 in the input
    // becomes truthy.
    0 . $char = $argv[1][$a];

    // Use modulo to determine the end of a stretch (where direction is
    // changed).
    // Change direction (`0` is right, `-1` is up and `1` is down). When
    // y coordinate is `0`, increment the direction, else decrement.
    $a++ % ($argv[2] - 1) ?: $direction += $y ? -1 : 1
)

    (
        // Increase or decrease y coordinate for direction -1 or 1 respectively.
        // Check whether the array index at new y coordinate is already set.
        $reference =& $output[$y += $direction] ||
        // If not, create it as a string (otherwise would be array of chars).
        // Null byte, won't be printed to prevent leading char.
        $reference = ~ÿ;

        // Increment x coordinate for direction 0. Set the output char at the
        // current coordinates to the char of the current iteration.
    ) & $reference[$x += !$direction] = $char;

// Output all lines, separated by a newline.
echo join(~õ, $output);

Ritocchi

  • Salvato un byte usando <invece di!=
  • 0Ho salvato 2 byte impostando inizialmente la stringa su, quindi non devo anteporre un altro 0(nel caso in cui il primo output in una riga fosse a 0), producendo in verità 00.
  • Salvato 4 byte utilizzando un riferimento invece di ripetere $o[$y]
  • Salvataggio di un byte utilizzando modulo anziché ==per confrontare la direzione con 1 per modificare la coordinata x
  • Ho salvato un byte rimuovendo il tipo cast nullin intper lo scostamento della stringa, poiché lo scostamento della stringa viene comunque impostato su int
  • Salvato un byte utilizzando un tag di stampa breve
  • Salvato 7 byte migliorando la logica di direzione
  • 4 byte salvati assegnando direttamente il carattere per impedire l'intermedio $c
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.