Ripeti l'ennesimo elemento


18

Non abbiamo avuto una domanda di per un po '(5 giorni per essere precisi), quindi andiamo per uno.

Data una stringa se un numero intero positivo n, prendi ogni nelemento th s, ripetilo nvolte e rimettilo dentro s.

Ad esempio, se n = 3e s = "Hello, World!", ogni terzo carattere è Hl r!. Quindi ripeti ogni personaggio nper produrre HHHlll rrr!!!. Quindi sostituire le lettere originali con le versioni ripetute per produrre il prodotto finale diHHHellllo, Worrrld!!!

Devi svolgere questo compito nel codice più breve possibile nella tua lingua!

Regole

  • Questo è un quindi vince il codice più breve in byte
  • nè garantito che sia inferiore alla lunghezza se maggiore di 0
  • Il primo personaggio di sè da dove nvengono presi i th personaggi, ed è sempre ripetuto nvolte
  • sconsisterà solo di ASCII stampabile (il codice punta 0x20 (space)a 0x7E (~))

Casi test

s, n => output

"Hello, World!", 3 => "HHHellllo,   Worrrld!!!"
"Code golf", 1 => "Code golf"
"abcdefghijklm", 10 => "aaaaaaaaaabcdefghijkkkkkkkkkklm"
"tesTing", 6 => "ttttttesTingggggg"
"very very very long string for you to really make sure that your program works", 4 => "vvvvery    veryyyy verrrry loooong sssstrinnnng foooor yoooou toooo reaaaally    makeeee surrrre thhhhat yyyyour    proggggram    workkkks"

Possiamo prendere l'input scome una matrice di caratteri?
Kevin Cruijssen,

2
" e rimetterlo ins " <- è un requisito rigoroso (sovrascrivere la stringa originale) o va bene solo per produrre il risultato finale?
Felix Palmen,

@KevinCruijssen Sì, puoi
caird coinheringaahing,

1
@FelixPalmen è stato semplicemente come l'ho spiegato. Puoi usare qualsiasi metodo tu voglia
caird coinheringaahing,

@cairdcoinheringaahing bene, grazie, l'ho già fatto.
Felix Palmen,

Risposte:


10

Gelatina , 3 byte

Ḣs×

L'input è preso come s, n .

Provalo online!

Come funziona

Ḣs×  Main link. Argument: s, n

Ḣ    Head; yield s.
     This pops the list, leaving [n] as the main link's argument.
 s   Split s into chunks of length n.
  ×  Multiply each chunk by [n], repeating its first element n times.

Non sono effettivamente 6 byte nella codifica UTF-8? E1 B8 A2 73 C3 97
CoDEmanX,

5
In UTF-8, sì. Tuttavia, Jelly utilizza una tabella codici personalizzata , in cui ciascuno dei caratteri che comprende occupa solo un singolo byte.
Dennis,

7

Gelatina ,  6  5 byte

-1 byte grazie a Nun che perde (usa la moltiplicazione di stringhe di Python.)

×Jm¥¦

Un programma completo, che accetta due argomenti della riga di comando, la stringa e il numero e stampa il risultato.

Provalo online!

Come?

×Jm¥¦ - Main link: list of characters, s; number, n   e.g. ['g','o','l','f','e','r'], 2
    ¦ - sparse application:
   ¥  - ...to indices: last two links as a dyad:
 J    -      range of length of s                          [1,2,3,4,5,6]
  m   -      modulo slicing by n (every nth entry)         [1,3,5]
×    - ...action: multiply  ["gg",'o',"ll",'f',"ee",'r']
      - implicit print                                 >>> ggollfeer


Sì, ho provato a xdimenticare ×; Grazie.
Jonathan Allan,

In realtà non sono 8 byte nella codifica UTF-8? C3 97 4A 6D C2 A5 C2 A6
CoDEmanX,

2
@CoDEmanX Utilizza la tabella codici
MD XF,

@MDXF grazie per il fielding!
Jonathan Allan,

4

JavaScript (ES6), 46 byte

Accetta input nella sintassi del curry (s)(n).

s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))

Casi test




3

05AB1E , 8 7 byte

-1 byte grazie a @Emigna

ôʒć²×ì?

Provalo online!

Spiegazione

ôʒć²×ì?    Arguments s, n  ("Hello, World!", 3)
ô          Split s into pieces of n  (["Hel", "lo,", ...])
 ʒ         Filter (used as foreach)
  ć          Extract head  ("Hel" -> "el", "H" ...)
   ²×ì       Repeat n times and prepend  ("el", "H" -> "HHHel" ...)
      ?      Print without newline

Salvare un byte conôʒć²×ì?
Emigna il

@Emigna grazie, sapevo che doveva esserci un modo per sbarazzarsi della chiusura}
kalsowerus,

Strano utilizzo del filtro quando non utilizza il risultato, ma in realtà fa la differenza ...
Magic Octopus Urn,

@MagicOctopusUrn, il filtro yep è ancora il migliore foreach in 05AB1E
kalsowerus,

@kalsowerus vyè un foreach, εè un altro. Stranamente, εnon funziona.
Magic Octopus Urn,

2

PowerShell , 51 byte

param($a,$n)-join($a|%{($_,("$_"*$n))[!($i++%$n)]})

Provalo online!

Accetta l'input come un chararray $ae il numero $n. Passa attraverso $ae ogni iterazione genera la lettera corrente $_o la lettera corrente moltiplicata per $n, basata su un indice in uno pseudo-ternario. L'indice sceglie tra i due in base all'incremento $ie quindi al modulo $n. Quelle lettere vengono quindi -joinrimesse insieme e la stringa viene lasciata sulla pipeline; l'output è implicito.



2

Alice , 25 byte

/
KI /!Iw?&.?t&O?&wWOI.h%

Provalo online!

Spiegazione

/         Switch to Ordinal.
I         Read first line of input (i.e. n).
/         Switch to Cardinal.
!         Convert input to its integer value and store it on the tape.
I         Read first character from input string.
w         Push current IP address onto the return address stack. This
          effectively marks the beginning of the main loop.

  ?         Retrieve n.
  &.        Duplicate current character n times (once more than we need,
            but who cares about a clean stack...).
  ?t        Retrieve n and decrement.
  &O        Output n-1 copies of the current character.
  ?         Retrieve n.
  &w        Push the current IP address onto the return address stack n
            times. This marks the beginning of a loop that is executed n 
            times.

    W         Discard one copy of the return address from the stack,
              effectively decrementing the loop counter.
    O         Output the last character. On the first iteration, this is
              the final copy of the repeated character, otherwise it's just
              the single character we read on the last iteration.
    I         Read a character for the next iteration.
    .h%       Compute c % (c+1) on that character, which is a no-op for
              for valid characters, but terminates the program at EOF when
              c becomes -1.

K         Jump to the address on top of the return address stack. As long
          as there are still copies of the address from the inner loop, we
          perform another iteration of that, otherwise we jump back to the
          beginning of the outer loop.

2

R , 82 76 75 byte

function(s,n)cat(rep(S<-el(strsplit(s,'')),c(n,rep(1,n-1))+!seq(S)),sep='')

Provalo online!

Una funzione; accetta una stringa se un numero intero ne stampa la versione ripetuta su stdout.

Spiegazione:

function(s,n){
 S <- el(strsplit(s,""))                  # characters
 r     <- c(n,rep(1,n-1))                 # [n, 1, 1,...,1], length n
 repeats <- r+!seq(S)                     # extends R to length of S
 cat(rep(S, repeats), sep="")             # print out
}

R , 55 byte

function(S,n)cat(rep(S,c(n,rep(1,n-1))+!seq(S)),sep="")

Provalo online!

Stesso algoritmo di cui sopra, ma con Sun elenco di singoli caratteri.




1

Japt , 8 byte

ËùDV*EvV

Provalo online!

Spiegazione

 Ë    ùDV*EvV
UmDE{DùDV*EvV}   Ungolfed
                 Implicit: U = s, V = n
UmDE{        }   Replace each char D and (0-)index E in U by this function:
          EvV      Take 1 if the index is divisible by V; 0 otherwise.
        V*         Multiply this by V. This gives V for every Vth index; 0 for others.
     DùD           Pad D with itself to this length. This gives V copies of D for every
                   Vth index; 1 copy of D for others.
                 Implicit: output last expression

Devo dare credito all'idea di usare qui la risposta ùdi @Shaggy . Non so che ci avrei mai pensato da solo ...


Ora capisci perché è stato così entusiasta di vedere il padding di stringhe aggiunto :) Bella soluzione. Stavo cercando di ottenere qualcosa con cui lavorare ë, per cacca e risatine, ma miseramente fallito!
Shaggy,

1

J, 17 byte

(#@]$[,1#~<:@[)#]
  • (...) # ]tutto in parentesi crea la stringa per il verbo "copia" di J. Quindi, ad esempio, se l'argomento sinistro è 3, crea la stringa 3 1 1ripetuta come necessario per uguagliare il numero di caratteri nell'arg destro ], che contiene la stringa. Vale a dire,# risolve direttamente il problema, supponendo che possiamo dargli l'argomentazione di sinistra corretta: 4dovrebbe essere 4 1 1 1ripetuto, e così via.
  • esaminando #@]$[,1#~<:@[ , vediamo che usa il verbo forma di J.$ nel mezzo - questo è il verbo principale di questa frase ...
  • A sinistra di $è #@], che indica la lunghezza# dell'arg destra ].
  • Alla destra $ è [,1#~<:@[un treno a 5 verbi. Il primo treno eseguito è ...
  • 1#~<:@[, che significa 1 copiato #~(forma passiva di copia) uno in meno <:dell'arg sinistro [. Questo risultato viene passato al fork finale:
  • [, ... significa prendere l'arg sinistro e aggiungere il risultato che abbiamo appena calcolato, che è una stringa di 1 s.

Provalo online!


]#~[^0=(|i.@#)per 14 byte
miglia

È abbastanza intelligente. I tuoi miglioramenti ai miei post sono la parte migliore di questo sito per me.
Giona


1

Perl 5, 37 , 29 +1 (-p) byte

-8 byte grazie al commento di Tom.

$n=<>;s/./"@-"%$n?$&:$&x$n/ge

Provalo online


Non riesco a pensare a un approccio migliore in questo momento, ma mi si avvicinò con un paio di idee: $n=<>;al posto del BEGINblocco e hanno nsulla prossima riga di input e sostituire $-[0]con "@-"quanto solo il primo numero viene valutata in confronto. Inoltre, se prendi input da nvia -ipuoi semplicemente usare $^Iinvece di dichiarare e usare $n, ma poiché questo non è standard potrebbe non volare ... :)
Dom Hastings

1

6502 routine codice macchina , 50 byte

A0 01 84 97 88 84 9E 84 9F B1 FB F0 20 A4 9F 91 FD C6 97 D0 10 A6 FF CA F0
05 C8 91 FD D0 F8 84 9F A5 FF 85 97 E6 9E A4 9E E6 9F D0 DC A4 9F 91 FD 60

Si tratta di una subroutine indipendente dalla posizione che prevede un puntatore alla stringa di input (stringa C terminata con 0) in $fb/$fc , un puntatore al buffer di output in $fd/ $fee il conteggio ( n) in$ff . Utilizza una semplice indicizzazione, quindi è limitato a una lunghezza di output massima di 255 caratteri (+ 0 byte) a causa dell'architettura a 8 bit.

Spiegazione (smontaggio commentato):

 .rep:
A0 01       LDY #$01            ; init counter to next repetition sequence
84 97       STY $97
88          DEY                 ; init read and write index
84 9E       STY $9E             ; (read)
84 9F       STY $9F             ; (write)
 .rep_loop:
B1 FB       LDA ($FB),Y         ; read next character
F0 20       BEQ .rep_done       ; 0 -> finished
A4 9F       LDY $9F             ; load write index
91 FD       STA ($FD),Y         ; write next character
C6 97       DEC $97             ; decrement counter to nex rep. seq.
D0 10       BNE .rep_next       ; not reached yet -> next iteration
A6 FF       LDX $FF             ; load repetition counter
 .rep_seqloop:
CA          DEX                 ; and decrement
F0 05       BEQ .rep_seqdone    ; if 0, no more repetitions
C8          INY                 ; increment write index
91 FD       STA ($FD),Y         ; write character
D0 F8       BNE .rep_seqloop    ; and repeat for this sequence
 .rep_seqdone:
84 9F       STY $9F             ; store back write index
A5 FF       LDA $FF             ; re-init counter to next ...
85 97       STA $97             ; ... repetition sequence
 .rep_next:
E6 9E       INC $9E             ; increment read index
A4 9E       LDY $9E             ; load read index
E6 9F       INC $9F             ; increment write index
D0 DC       BNE .rep_loop       ; jump back (main loop)
 .rep_done:
A4 9F       LDY $9F             ; load write index
91 FD       STA ($FD),Y         ; and write terminating0-byte there
60          RTS                 ; done.

Esempio di programma codice macchina C64 che lo utilizza :

Questo è un programma in assemblatore in stile ca65 per C64 che usa questa routine (importata come rep):

REP_IN          = $fb
REP_IN_L        = $fb
REP_IN_H        = $fc

REP_OUT         = $fd
REP_OUT_L       = $fd
REP_OUT_H       = $fe

REP_N           = $ff

.import         rep


.segment "LDADDR"
                .word   $c000

.code
                jsr     $aefd           ; consume comma
                jsr     $ad9e           ; evaluate expression
                sta     REP_IN_L        ; store string length
                jsr     $b6a3           ; free string
                ldy     #$00            ; loop over string
readloop:       cpy     REP_IN_L        ; end of string?
                beq     termstr         ; then jump to 0-terminate string
                lda     ($22),y         ; read next character
                sta     in,y            ; store in input buffer
                iny                     ; next
                bne     readloop
termstr:        lda     #$00            ; load 0 byte
                sta     in,y            ; store in input buffer

                jsr     $b79b           ; read 8bit unsigned int
                stx     REP_N           ; store in `n`
                lda     #<in            ; (
                sta     REP_IN_L        ;   store pointer to
                lda     #>in            ;   to input string
                sta     REP_IN_H        ; )
                lda     #<out           ; (
                sta     REP_OUT_L       ;   store pointer to
                lda     #>out           ;   output buffer
                sta     REP_OUT_H       ; )
                jsr     rep             ; call function

                ldy     #$00            ; output result
outloop:        lda     out,y
                beq     done
                jsr     $ffd2
                iny
                bne     outloop
done:           rts


.bss
in:             .res    $100
out:            .res    $100

Demo online

Uso: sys49152,"[s]",[n] ad essys49152,"Hello, World!",3

Importante: se il programma è stato caricato dal disco (come nella demo online), emettere newprima un comando! Ciò è necessario perché il caricamento di un programma macchina elimina alcuni puntatori BASIC C64.


1

Java 8, 100 76 byte

s->n->{int i,k=0;for(char c:s)for(i=k++%n<1?n:1;i-->0;)System.out.print(c);}

-24 byte grazie a @ OliverGrégoire .

Spiegazione:

Provalo qui.

s->n->{                    // Method with char-array and int parameters and no return-type
  int i,k=0;               //  Index-integers
  for(char c:s)            //  Loop (1) over the characters of the input array
    for(i=k++%n<1?         //   If `k` is divisible by the input `n`:
         n                 //    Change `i` to `n`
        :                  //   Else:
         1;                //    Change `i` to 1
        i-->0;)            //   Inner loop (2) from `i` down to 0
      System.out.print(c); //    And print the current character that many times
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
}                          // End of method

Spiacenti, non ho visto che c'era già un invio, quindi ho eliminato il mio. Ecco, abbreviato in 76 byte: n->s->{int i,k=0;for(char c:s)for(i=k++%n<1?n:1;i-->0;)System.out.print(c);}(con un char[], invece di String.)
Olivier Grégoire,

Come regola empirica, se devi dichiarare esattamente una stringa che verrà restituita, è più breve semplicemente stamparla.
Olivier Grégoire,

@ OlivierGrégoire Oops .. Sì, conosco quella regola empirica, ho appena dimenticato di applicarla questa volta .. E grazie per i byte salvati!
Kevin Cruijssen,

1

MATL , 10 7 byte

-3 byte grazie a Luis Mendo!

tq:ghY"

Provalo online!

Accetta input come ne quindi Scome array string / char.

    % (implicit input)
    % stack: n
t   % duplicate
    % stack: n n
q   % decrement
    % stack: n n-1
:   % range
    % stack: n [1 2 ... n-1]
g   % convert to logical (nonzero->1, zero->0)
    % stack: n [1 1 ... 1]
h   % horizontal concatenate
    % stack: [n 1 1 ... 1]
Y"  % run-length decoding, taking the string as first input and recycling 
    % the lengths [n 1 1 ... 1] as needed
    % (implicit output as string)


1

Haskell , 51 46 byte

Grazie @Laikoni per avermi salvato 5 byte!

n&s=do(m,c)<-zip[0..]s;c<$[0..(n-1)*0^mod m n]

Provalo online!

Spiegazione / Ungolfed

L'operatore c <$ [a..b]sostituisce ogni elemento dell'elenco [a,a+1...b]con c- quindi è solo un golf replicate:

do(m,c)<-zip[0..]s;                                  -- with all (m,c) in the enumerated ([(0,a),(1,b)..]) input string, replace with
                   replicate (1 + (n-1)*0^mod m n) c -- either n or 1 times the character c (note that the list begins with 0, that's where the 1+ comes from)

0

Carbone , 14 byte

Nθ⪫ES⎇﹪κθι×ιθω

Provalo online! Il collegamento è alla versione dettagliata del codice. Prende ingresso nell'ordine n, s.


0

V , 13 byte

"aDJòylÀpÀll

Provalo online!

Questa è una soluzione davvero stupida. òlhÀälÀlÀ<M-->ldovrebbe funzionare, ma non posso per la vita di me a capire perché, soprattutto perché manualmente facendo lhÀälÀlÀ<M-->lripetuto un sacco di volte fa lavoro.

hexdump:

00000000: 1822 6144 4af2 796c c070 c06c 6c         ."aDJ.yl.p.ll

Spiegazione:

<C-x>               " Decrement the number
       D            " Delete that number...
     "a             "   Into register 'a'
        J           " Remove the blank line
         ò          " Recursively...
          yl        "   Yank the letter under the cursor
            Àp      "   And paste it 'a' times
              Àl    "   Move 'a' times to the right ('l' for right)
                l   "   Move to the right one more time
                    " (implicit) end the loop

'l' for right... Immagino sia una cosa Vim? Altrimenti ... perché ?
AdmBorkBork,

2
@AdmBorkBork sì, lè giusto in vim. potrebbe essere ortogonalmente all'indietro, ma è geometricamente corretta: lè la chiave di lettera più a destra della riga centrale.
Giona,

@DJMcMayhem Right. L'ho fatto bene.
Giona,


0

Python 3 , 58 byte

Lavorando a golf giù.

So che ci sono già altre risposte a Python, ma ho pensato di pubblicare anche questo visto visto che segna abbastanza bene rispetto agli altri, nonostante sia una funzione completa e non una lambda.

Accetta input come parametri di funzione e stampa su STDOUT.

def f(s,n,i=0):
 for c in s:print(end=[c,c*n][i%n<1]);i+=1

Provalo online!

Per un byte in meno (57), ho codificato un lambda, tuttavia risposte simili sono già state inviate da altri utenti:

lambda s,n:''.join([c,c*n][i%n<1]for i,c in enumerate(s))

0

Brain-Flak (BrainHack) , 122 + 3 ( -A) = 125 byte

Sono sicuro che questo è troppo lungo, ma ho passato parecchio tempo a cercare e non sono riuscito a trovare alcun miglioramento.

([]){{}([(([{}]<>)<{({}<<>(({})<>)>())}{}{}>)<{({}<<>({}<>)>())}{}>]<>)([][()])}({}{}<>){({}{(<()>)}{}[()])}{}{({}<>)<>}<>

Provalo online!


0

05AB1E , 12 11 byte

vX‚RNIÖèy×?

Provalo online!

Spiegazione

v             # for each letter in the input string
       è      # index into
 X‚           # the list [input_int,1]
   R          # reversed
    NIÖ       # with letter_index % input_int == 0
        y×    # repeat the current letter this many times
          ?   # print

0

Mathematica, 71 byte

""<>s[[i]]~t~If[i~Mod~#2==1,#2,1]~(t=Table)~{i,Tr[1^(s=Characters@#)]}&

Provalo online!

salvato -2 byte ascoltando l'utente 202729


Credo che Mapnel corso Characterspuò essere più breve.
user202729,

@ user202729 ok! -2 byte
J42161217

0

K (oK) , 23 19 byte

Soluzione:

{,/(1|y*~y!!#x)#'x}

Provalo online!

Esempi:

> {,/(1|y*~y!!#x)#'x}["Hello, World!";3]
"HHHellllo,   Worrrld!!!"
> {,/(1|y*~y!!#x)#'x}["Code golf";1]
"Code golf"
> {,/(1|y*~y!!#x)#'x}["abcdefghijklm";10]
"aaaaaaaaaabcdefghijkkkkkkkkkklm"

Spiegazione:

{,/(1|y*~y!!#x)#'x} / the solution
{                 } / lambda function with x and y as implicit parameters
   (          )     / do everything in brackets together
            #x      / count x, #"Hello, World!" -> 13
           !        / til, !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12
         y!         / y modulo, 3!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 2 0 1 2 0 1 2 0 1 2 0
        ~           / not, ~0 1 2 0 1 2 0 1 2 0 1 2 0 -> 1 0 0 1 0 0 1 0 0 1 0 0 1
      y*            / multiply by y, 3*1 0 0 1 0 0 1 0 0 1 0 0 1 -> 3 0 0 3 0 0 3 0 0 3 0 0 3
    1|              / min of 1 and, 1|3 0 0 3 0 0 3 0 0 3 0 0 3 -> 3 1 1 3 1 1 3 1 1 3 1 1 3
                #'x / take each parallel, 1 2 3#'"abc" -> "a", "bb", "ccc"
 ,/                 / flatten the list, "a", "bb", "ccc" -> "abbccc"

Appunti:

  • -4 byte con approccio diverso

0

Excel VBA, 71 byte

Funzione di finestra immediata VBE anonima che prende input dalla gamma [A1:B1]e output alla finestra immediata VBE.

For i=1To[Len(A1)]:[C1]=i:?[Rept(Mid(A1,C1,1),B1^(Mod(C1,B1)=1))];:Next
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.