Stampa una stringa ondulata riga per riga


23

Sfida

Scrivi un programma o una funzione che accetta una stringa se un numero intero ncome parametri. Il programma deve stampare (o restituire) la stringa quando viene trasformata come segue:

Partendo in alto a sinistra e muovendosi verso il basso e verso destra, scrivi scome un'onda di altezza n. Quindi, dall'alto verso il basso, combina ogni riga come una stringa (senza spazi).

Esempio

Data la stringa "WATERMELON" e un'altezza di 3:

L'onda dovrebbe apparire così:

W   R   O
 A E M L N
  T   E

Quindi, combina le righe dall'alto verso il basso:

WRO
AEMLN
TE

Quindi, il tuo programma dovrebbe restituire la stringa "WROAEMLNTE"

Allo stesso modo, "WATERMELON" con altezza 4 dovrebbe produrre la seguente onda:

W     E
 A   M L
  T R   O
   E     N

Il programma dovrebbe quindi restituire la stringa "WEAMLTROEN"

Regole

Ingresso

L'input può essere preso in qualsiasi formato ragionevole. La stringa può essere in ogni caso tu preferisca. Si può presumere che0 < n <= s.length

Produzione

L'output deve essere costituito solo dalla stringa trasformata (restituita o stampata su STDOUT), oltre a eventuali nuove righe finali.

punteggio

Questo è , quindi vince la risposta più breve in byte! Non sono ammesse scappatoie standard.

Casi test

Input                        Output

programmingpuzzles, 5 ->     piermnlsomgzgapzru
codegolf, 3           ->     cgoeofdl
elephant, 4           ->     enlatehp
1234567, 3            ->     1524637
qwertyuiop, 1         ->     qwertyuiop

Possiamo assumere n> 1? Si prega di chiarire e in caso contrario aggiungere un caso di prova
Luis Mendo,

1
Puoi presumere n > 0, ma n=1è un caso valido. Aggiornerò la domanda ora.
Cowabunghole,

2
@Cowabunghole Lo so. :) Correlati significa solo che è in qualche modo simile e le risposte esistenti potrebbero essere utili per questa sfida. Lo dico solo per farli apparire alle domande collegate a destra. Correlato! = Duplicato. ;)
Kevin Cruijssen,

5
Non ho mai visto un codice di recinzione su rotaia codificato con una sola rotaia.
Sto

1
@Veskah Ah sì, il vecchio trucco double rot13.
wooshinyobject,

Risposte:


5

Buccia , 6 byte

δÖK…¢ḣ

Provalo online!

Funziona anche per n = 1.

Spiegazione

δÖK…¢ḣ  Implicit inputs, say n=4 and s="WATERMELON"
     ḣ  Range: [1,2,3,4]
    ¢   Cycle: [1,2,3,4,1,2,3,4,1,2,3,4..
   …    Rangify: [1,2,3,4,3,2,1,2,3,4,3,2..
δÖK     Sort s by this list: "WEAMLTROEN"
        Print implicitly.

La funzione di ordine superiore funziona in δquesto modo sotto il cofano. Supponiamo di avere una funzione di ordine superiore che accetta una funzione unaria e un elenco e restituisce un nuovo elenco. Ad esempio, Öaccetta una funzione e ordina un elenco utilizzandolo come chiave. Quindi δÖaccetta una funzione binaria e due liste, comprime le liste insieme, si applica Öper ordinare le coppie usando la funzione binaria come chiave e infine proietta le coppie sulla seconda coordinata. Usiamo Kcome funzione chiave, che semplicemente restituisce il suo primo argomento e ignora il secondo.


6

MATL , 16 byte

Zv3L)t?yn:)2$S}i

Provalo online! Oppure verifica tutti i casi di test .

Spiegazione

Considerate ingressi 5, 'programmingpuzzles'.

Zv     % Input, implicit: number n. Symmetric range
       % STACK: [1 2 3 4 5 4 3 2 1]
3L     % Push [1 -1+1j]. When used as an index, this means 1:end-1
       % STACK: [1 2 3 4 5 4 3 2 1], [1 -1+1j]
)      % Index. Removes last element
       % STACK: [1 2 3 4 5 4 3 2]
t      % Duplicate
       % STACK: [1 2 3 4 5 4 3 2], [1 2 3 4 5 4 3 2]
?      %   If non-empty and non-zero
       %   STACK: [1 2 3 4 5 4 3 2]
  y    %   Implict input: string s. Duplicate from below
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 'programmingpuzzles'
  n    %   Number of elements
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 18
  :    %   Range
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], [1 2 3 ··· 17 18]
  )    %   Index modularly
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2 1 2 3 4 5 4 3 2 1 2]
  2$S  %   Two-input sort: stably sorts first input as given by the second
       %   STACK: 'piermnlsomgzgapzru'
}      % Else. This branch is entered when n=1. The stack contains an empty array
       %   STACK: []
  i    %   Take input
       %   STACK: [], [], 'programmingpuzzles'
       % End, implicit
       % Display stack, implicit. Empty arrays are not displayed


5

J , 54, 29, 27 26 byte

-1 byte grazie a hoosierEE

([\:#@[$[:}:|@i:@<:@]) ::[

Provalo online!


@LuisMendo Hmm, ancora una volta mi sono perso qualcosa di importante. Grazie! Fisso.
Galen Ivanov,

1
Inizialmente l'ho perso anch'io, poi ho capito e chiesto all'OP. Ci sarebbe dovuto essere un caso di test n=1sin dall'inizio
Luis Mendo,

1
|@i:invece di [:|i:salvare un byte
hoosierEE,

@hoosierEE Sì, grazie!
Galen Ivanov,

5

R , 68 byte

function(s,n)intToUtf8(unlist(split(utf8ToInt(s),-(n:(2.9-n)-1)^2)))

Provalo online!

  • -10 byte grazie a @Giuseppe
  • -17 byte perché ero sciocco
  • -9 byte e n=1case riparati grazie a @ J.Doe
  • -3 byte grazie a @JayCe


3

05AB1E (legacy) , 11 8 byte

Σ²Lû¨¾è¼

Ispirato da @LuisMendo MATL risposta s' .
-3 byte grazie a @Adnan perché sono un idiota ..>.>

Provalo online .

Spiegazione:

Σ           # Sort the (implicit) input-string by:
 ²L         #  Create a list in the range [1, second input-integer]
            #   i.e. 5 → [1,2,3,4,5]
   û        #  Palindromize it
            #   i.e. [1,2,3,4,5] → [1,2,3,4,5,4,3,2,1]
    ¨       #  Remove the last item
            #   i.e. [1,2,3,4,5,4,3,2,1] → [1,2,3,4,5,4,3,2]
     ¾è     #  Index into it (with wraparound) using the counter_variable (default 0)
            #   i.e. counter_variable = 0 → 1
            #   i.e. counter_variable = 13 → 4
       ¼    #  And after every iteration, increase the counter_variable by 1

NOTA: counter_variableviene utilizzato, perché nella versione Python Legacy di 05AB1E, Σnon aveva un indice incorporato N, che ha nella nuova versione di riscrittura Elixir di 05AB1E. Quindi perché uso ancora la versione legacy? Perché nell'elisir la riscrittura trasforma implicitamente la stringa in un elenco di caratteri, richiedendo un ulteriore }Jper trasformarlo nuovamente in una stringa in output (e contiene anche un bug in questo momento in cui ènon funziona affatto per indicizzare nell'elenco allungato .. :S)


Non è necessaria la ¹g∍parte poiché 05AB1E utilizza l'indicizzazione ciclica per è.
Adnan,

@Adnan Ah, sono un idiota ..>.> Grazie!
Kevin Cruijssen,

2

Japt , 16 byte

¬üÏu´VÑ aV°ÃÔc q

Provalo online!

Spiegazione

 ¬ üÏ   u´ VÑ  aV° Ã Ô c q
Uq üXY{Yu--V*2 aV++} w c q    Ungolfed
                               Implicit: U = input string, V = size of wave
Uq                             Split U into chars.
   üXY{            }           Group the items in U by the following key function:
       Y                         Take the index of the item.
        u--V*2                   Find its value modulo (V-1) * 2.
               aV++              Take the absolute difference between this and (V-1).
                                 This maps e.g. indices [0,1,2,3,4,5,6,7,...] with V=3 to
                                                        [2,1,0,1,2,1,0,1,...]
                                 The items are then grouped by these values, leading to
                                 [[2,6,...],[1,3,5,7,...],[0,4,...]].
                     w         Reverse the result, giving [[0,4,...],[1,3,5,7,...],[2,6,...]].
                       c       Flatten.
                         q     Join back into a single string.

oO Questo ümetodo è nuovo?
Luis felipe De jesus Munoz,

Sì, aggiunto sabato :-)
ETHproductions

Potresti prendere l'input come un array di caratteri per salvare un byte e emetterne uno o usare il -Pflag per salvarne un altro 2.
Shaggy,

2

Gelatina , 8 byte

6 byte falliscono per l'altezza 1; due byte utilizzati per indirizzarlo ... forse è possibile trovare un 7?

ŒḄṖȯ1ṁỤị

Un collegamento diadico che accetta un numero intero positivo e un elenco di caratteri che produce un elenco di caratteri.

Provalo online!

Come?

ŒḄṖȯ1ṁỤị - Link: positive integer N; list of characters, T
ŒḄ       - bounce (implicit range of) N -> [1,2,3,...,N-1,N,N-1,...,3,2,1]
  Ṗ      - pop off the final entry         [1,2,3,...,N-1,N,N-1,...,3,2]
   ȯ1    - OR one                          if this is [] get 1 instead
     ṁ   - mould like T (trim or repeat to make this list the same length as T)
      Ụ  - grade-up (get indices ordered by value - e.g. [1,2,3,2,1,2] -> [1,5,2,4,6,3])
       ị - index into T

2

JavaScript (ES6), 75 byte

Formula più breve suggerita da @MattH (-3 byte)

Accetta input come (string)(n).

s=>n=>--n?[...s].map((c,x)=>o[x=x/n&1?n-x%n:x%n]=[o[x]]+c,o=[])&&o.join``:s

Provalo online!


JavaScript (ES7), 78 byte

Risparmiato 4 byte grazie a @ETHproductions

Accetta input come (string)(n).

s=>n=>--n?[...s].map((c,x)=>o[x=n*n-(x%(n*2)-n)**2]=[o[x]]+c,o=[])&&o.join``:s

Provalo online!


La mia soluzione è risultata piuttosto simile alla tua. È possibile salvare -3 byte calcolo dell'indice inserto di ocon x/n&1?n-x%n:x%nal posto di n*n-(x%(n*2)-n)**2.
Matt

@MattH Ben fatto. Grazie!
Arnauld,


1

MBASIC , 146 159 155 byte

1 INPUT S$,N:DIM C$(N):P=1:D=1:FOR I=1 TO LEN(S$):C$(P)=C$(P)+MID$(S$,I,1)
2 IF N>1 THEN P=P+D
3 IF P=N OR P=1 THEN D=-D
4 NEXT:FOR I=1 TO N:PRINT C$(I);:NEXT

Aggiornato per gestire n = 1

Produzione:

? programmingpuzzles, 5
piermnlsomgzgapzru

? codegolf, 3
cgoeofdl

? elephant, 4
enlatehp

? 1234567, 3
1524637

? WATERMELON, 4
WEAMLTROEN

? qwertyuiop, 1
qwertyuiop

Attualmente non supporta il caso n = 1.
wooshinyobject,

Aggiornato per gestire il caso n = 1
wooshinyobject

Salvato 4 byte pulendo i confronti.
wooshinyobject,

1

Perl 6 , 49 byte

->\n{*.comb.sort({-abs n-1-$++%(2*n-2||1)}).join}

Provalo online!

Accetta input come funzione curry.

Spiegazione:

->\n{*.comb.sort({-abs n-1-$++%(2*n-2||1)}).join}
->\n{                                           }  # Take an number
     *.comb        # Turn the string into a list of chars
           .sort({                       })   # And sort them by
                           $++    # The index of the char
                              %(2*n-2||1)  # Moduloed by 2*(n-1) or 1 if n is 0
                       n-1-       # Subtract that from n-1
                   abs            # get the absolute value
                  -               # And negate to reverse the list
                                          .join  # and join the characters

La sequenza per cui è ordinata è simile alla seguente (per n=5):

(-4 -3 -2 -1 0 -1 -2 -3 -4 -3 -2 -1 0 -1 -2 -3 -4 -3 -2 -1)

1

J , 24 byte

4 :'x\:(#x)$}:|i:<:y'::[

Provalo online!

Verbo diadico esplicito. Eseguilo come 'codegolf' f 3.

Come funziona

4 :'x\:(#x)$}:|i:<:y'::[    x: string, y: height
4 :                         Define a dyadic verb:
               i:<:y        Generate a range of -(y-1) .. y-1
            }:|             Take absolute value and remove last
       (#x)$             1) Repeat to match the string's length
    x\:                     Sort x by the decreasing order of above
                     ::[    If 1) causes `Length Error`, return the input string instead

Normalmente, la funzione esplicita richiede altri 5 byte sotto forma di n :'...'. Ma se viene aggiunta la gestione degli errori, la differenza scende a 2 byte a causa delle parentesi e dello spazio in (tacit)<space>::.


Perché tendo sempre ad usare sort up?! Il tuo verbo esplicito è ancora più corto di 3 byte. Buona decisione!
Galen Ivanov,


1

Powershell, 99 95 byte

param($s,$n)$r=,''*$n
$s|% t*y|%{$r[((1..$n+$n..1)*$s.Length|gu)[$i++*($n-gt1)]-1]+=$_}
-join$r

Script di prova:

$f = {

param($s,$n)$r=,''*$n
$s|% t*y|%{$r[((1..$n+$n..1)*$s.Length|gu)[$i++*($n-gt1)]-1]+=$_}
-join$r

}

@(
    ,("1234567", 3            ,     "1524637")
    ,("qwertyuiop", 1         ,     "qwertyuiop")
    ,("codegolf", 3           ,     "cgoeofdl")
    ,("elephant", 4           ,     "enlatehp")
    ,("programmingpuzzles", 5 ,     "piermnlsomgzgapzru")
) | % {
    $s,$n,$e = $_
    $r = &$f $s $n
    "$($r-eq$e): $r"
}

Produzione:

True: 1524637
True: qwertyuiop
True: cgoeofdl
True: enlatehp
True: piermnlsomgzgapzru

Spiegazione

Il copione:

  • crea una matrice di righe,
  • riempie le righe con i valori appropriati,
  • e restituisce le righe unite.

L'espressione ((1..$n+$n..1)*$s.Length|gu genera una sequenza simile 1,2,3,3,2,1,1,2,3,3,2,1... e rimuove i duplicati adiacenti. guè alias per Get-Unique .

  • Per $n=3la sequenza deduplicata è:1,2,3,2,1,2,3,2,1...
  • Per $n=1la sequenza deduplicata è:1

L'espressione $i++*($n-gt1) restituisce un indice nella sequenza deduplicata. =$i++se $n>1, altrimenti=0


1

Rubino , 75 65 byte

->s,h{a=['']*h;x=-k=1;s.map{|c|a[x+=k=h-x<2?-1:x<1?1:k]+=c};a*''}

Provalo online!

Prende l'input come una matrice di caratteri, restituisce una stringa

Come funziona:

  • Crea hstringhe
  • Per ogni carattere nella stringa di input, decidi in quale stringa inserirla in base al suo indice (l'indice della stringa da modificare va su he poi giù fino a 0e così via)
  • Restituisce tutte le stringhe unite


@GB non funziona per l'ultimo caso
Asone Tuhid,

1

C, 142 134 byte

8 byte salvati grazie a Jonathan Frech

Codice:

t;i;j;d;f(s,n)char*s;{for(t=strlen(s),i=0;i<n;i++)for(j=0;j+i<t;j=d+i+(n<2))d=j-i+2*~-n,putchar(s[i+j]),i>0&i<n-1&d<t&&putchar(s[d]);}

Spiegazione:

// C variable and function declaration magic
t;i;j;d;f(s,n)char*s;{
    // Iterate through each "row" of the string
    for(t=strlen(s),i=0;i<n;i++)
        // Iterate through each element on the row
        // Original index iterator here was j+=2*(n-1), which is a full "zig-zag" forward
        // The (n<2) is for the edge case of n==1, which will break the existing logic.
        for(j=0; j+i<t; j=d+i+(n<2))
            // If j+i is the "zig", d is the "zag": Original index was d=j+i+2*(n-i-1)
            // Two's complement swag here courtesy of Jonathan Frech
            d=j-i+2*~-n,
            putchar(s[i+j]),
            // Short circuit logic to write the "zag" character for the middle rows
            i>0 & i<n-1 & d<t && putchar(s[d]);
}

Provalo online!


1
Ciao e benvenuto in PPCG; bel primo golf. 134 byte (presupponendo GCC).
Jonathan Frech,

0

Carbone , 21 byte

⭆NΦη¬⌊E²﹪⁺μ⎇νι±ι∨⊗⊖θ¹

miom±io=0(mod2n-2)

 N                      First input as a number
⭆                       Map over implicit range and join
   η                    Second input
  Φ                     Filter over characters
       ²                Literal 2
      E                 Map over implicit range
          μ             Character index
             ι ι        Outer index
              ±         Negate
            ν           Inner index
           ⎇            Ternary
         ⁺              Plus
                   θ    First input
                  ⊖     Decremented
                 ⊗      Doubled
                    ¹   Literal 1
                ∨       Logical Or
        ﹪               Modulo
     ⌊                  Minimum
    ¬                   Logical Not
                        Implicitly print

0

SNOBOL4 (CSNOBOL4) , 191 byte

	S =INPUT
	N =INPUT
	A =ARRAY(N)
	A<1> =EQ(N,1) S	:S(O)
I	I =I + -1 ^ D
	S LEN(1) . X REM . S	:F(O)
	A<I> =A<I> X
	D =EQ(I,N) 1
	D =EQ(I * D,1)	:(I)
O	Y =Y + 1
	O =O A<Y>	:S(O)
	OUTPUT =O
END

Provalo online!

Prende Squindi Nsu linee separate.

Spiegazione:

	S =INPUT			;* read S
	N =INPUT			;* read N
	A =ARRAY(N)			;* create array of size N
	A<1> =EQ(N,1) S	:S(O)		;* if N = 1, set A<1> to S and jump to O
I	I =I + -1 ^ D			;* index into I by I + (-1)^D (D starts as '' == 0)
	S LEN(1) . X REM . S	:F(O)	;* extract the first character as X and set S to the
					;* remaining characters, jumping to O when S is empty
	A<I> =A<I> X			;* set A<I> to A<I> concatenated with X
	D =EQ(I,N) 1			;* if I == N, D=1
	D =EQ(I * D,1)	:(I)		;* if I == D == 1, D = 0. Goto I
O	Y =Y + 1			;* increment the counter
	O =O A<Y>	:S(O)		;* concatenate the array contents until last cell
	OUTPUT =O			;* and print
END



0

Pyth , 22 21 byte

|seMhD,V*lz+PUQP_UQzz

Accetta input come nseguito da srighe separate. Provalo online qui o verifica tutti i casi di test contemporaneamente qui .

|seMhD,V*lz+PUQP_UQzz   Implicit: Q=eval(input()), z=remaining input

             UQ         Range [0-Q)
            P           All but last from the above
                         e.g. for Q=3, yields [0,1]
               P_UQ     All but last of reversed range
                         e.g. for Q=3, yields [2,1]
           +            Concatenate the previous two results
                          e.g. for Q=3, yields [0,1,2,1]
        *lz              Repeat len(z) times
      ,V           z    Vectorised pair the above with z, truncating longer to length of shorter
                          e.g. for Q=3, z=WATERMELON, yields:
                          [[0,'W'],[1,'A'],[2,'T'],[1,'E'],[0,'R'],[1,'M'],[2,'E'],[1,'L'],[0,'O'],[1,'N']]
    hD                  Sort the above by the first element
                          Note this is a stable sort, so relative ordering between equal keys is preserved
  eM                    Take the last element of each
 s                      Concatenate into string
                          Note that if n=1, the result of the above will be 0 (sum of empty array)
|                   z   If result of above is falsey, yield z instead

Modifica: salvato un byte spostando il segno di spunta vuoto alla fine dell'elaborazione. Versione precedente: seMhD,V*lz|+PUQP_UQ]0z


0

Rosso , 153 byte

func[s n][i: v: m: 1 b: collect[foreach c s[keep/only reduce[v i c]v: v + m
if all[n > 1(i: i + 1)%(n - 1)= 1][m: -1 * m]]]foreach k sort b[prin last k]]

Provalo online!

Spiegazione:

f: func [ s n ] [                      ; s is the string, n is the height
    i: 1                               ; index of the current character in the string
    v: 1                               ; value of the "ladder"
    m: 1                               ; step (1 or -1)
    b: collect [                       ; collect the values in a block b
        foreach c s [                  ; foreach character in the string 
            keep/only reduce [ v i c ] ; keep a block of the evaluated [value index char] 
            i: i + 1                   ; increase the index
            v: v + m                   ; calculate the value 
            if all [ n > 1             ; if height is greater than 1 and
                    i % (n - 1) = 1    ; we are at a pick/bottom of the ladder
                   ]
                [ m: -1 * m ]          ; reverse the step
        ]
    ]
    foreach k sort b [ prin last k ]   ; print the characters in the sorted block of blocks
]

0

Ho due soluzioni al problema. La prima soluzione che ho fatto per prima poi ho pensato a un altro modo per farlo che pensavo potesse salvare byte, ma non è stato così l'ho incluso comunque.


Soluzione 1

PHP , 152 144 116 byte

<?php
for($i=0;$i<$n=$argv[2];$i++)
    for($j=$i;$s=$argv[1][$j];$j+=$n<2|(($f=!$f|!$i)?$i<$n-1?$n+~$i:$i:$i)*2)
        echo $s;
  • 8 byte grazie a @JoKing
  • 28 byte grazie a @Shaggy

Provalo online!


Soluzione 2

PHP , 162 byte

<?php
$s=$argv[0];
$n=$argv[1];
$l=strlen($s);
for($i=0;$i<$l;){
    for($j=0;$j<$n&&$i<$l;)
        $a[$j++].=$s[$i++];
    for($j=$n-2;$j>0&&$i<$l;)
        $a[$j--].=$s[$i++];
}
echo join($a);

Provalo online!


Non è necessario inizializzare $fe $n-1-$ipuò esserlo $n-~$i. 144 byte
Jo King,

-28 byte sui miglioramenti di @ JoKing.
Shaggy,

oop; che si interrompe quando n=1. Questo funziona per lo stesso numero di byte.
Shaggy,

Puoi anche usare tag brevi e rimuovere lo spazio dopo echoper salvare altri 5 byte
Shaggy,

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.