Scambia, elimina e ripeti


24

introduzione

Osserviamo la seguente stringa:

ABCDEFGHIJKLMNOP

Se scambiamo le estremità della stringa , che sono queste:

ABCDEFGHIJKLMNOP
^^            ^^

Otteniamo il seguente risultato:

BACDEFGHIJKLMNPO

Successivamente, eliminiamo le estremità della stringa, che in questo caso sono Be O. Il risultato è:

ACDEFGHIJKLMNP

Se ripetiamo il processo, otteniamo il seguente elenco:

N     Result

2     ADEFGHIJKLMP
3     AEFGHIJKLP
4     AFGHIJKP
5     AGHIJP
6     AHIP
7     AP

Puoi vedere che per N = 5 , il risultato è AGHIJP. A N = 7 , la lunghezza della stringa è inferiore a 3 , quindi N> 7 è considerato non valido in questo caso.

L'obiettivo

Data una stringa S con almeno lunghezza 4 e il numero di ripetizioni N > 0, genera il risultato finale. Puoi presumere che N sia sempre valido .

Casi test

Input                               >  Output

N = 3, S = ABCDEFGHIJKLMNOP         >  AEFGHIJKLP
N = 1, S = Hello                    >  Hlo
N = 2, S = 123321                   >  11

Questo è , quindi vince l'invio con il minor numero di byte! Per semplicità, puoi presumere che la stringa conterrà solo caratteri alfanumerici .


Domanda: Va bene prendere N all'unario con qualcosa come 'il personaggio del conteggio? Ad esempio ''123321:?
daavko,


È possibile utilizzare il formato @Adnan Unary per N, ma può essere una stringa, con virgolette? Voglio dire, per N=3prendere '111'(al contrario di 111)
Luis Mendo,

@LuisMendo Sì, puoi usarlo
Adnan,

Mi sembra che saltiamo 1 e rimuoviamo N: è consentito come risposta o il codice deve scambiare elimina e ripeti?
Alex Carlsen,

Risposte:


5

MATL , 8 9 12 13 byte

th"P[]2(

Gli input sono: prima Ncome stringa unaria con virgolette (consentita dalla sfida); secondo Scome una stringa con virgolette (le virgolette nelle stringhe sono consentite per impostazione predefinita); separati da una interruzione di riga.

Funziona capovolgendo la stringa, rimuovendo il suo secondo elemento e ripetendo per un totale di 2*Nvolte.

Provalo online!

th       % implicitly take first input (N) as a unary string. Concatenate horizontally
         % with itself: gives a string of 2*N ones
"        % for each (i.e., repeat 2*N times)
  P      %   flip string. Take S implicitly as input the first time
  []     %   empty array (used as new contents)
  2      %   2 (used as index)
  (      %   assign [] to position 2 of string; that is, remove second element
         % implicitly end for each
         % implicitly display

Spiegazione? : P
Addison Crump,

@VotoToClose Sicuro :-) Ho dovuto correre. L'ho appena aggiunto
Luis Mendo,

18

Retina , 44 20 byte

Cancellato 44 è ancora regolare 44 :(

+`'(\w).(.*).\B
$1$2

Presuppone l'inserimento nel seguente formato (con carattere di conteggio unario:) ':
{number of repeats}{string}
Ad esempio: '''''''ABCDEFGHIJKLMNOP
non c'è spazio tra il numero di ripetizioni e la stringa.

Grazie @ MartinBüttner per la rasatura di 24 byte!

Provalo online!



@ MartinBüttner Aha! Quindi questo era il tuo piano psicologico: p
Adnan,

9
@Adnan ¯ \ _ (ツ) _ / ¯
Martin Ender,

Cancellati 44 sembrano cancellati 11 ...
CocoaBean,


9

Mathematica, 29 byte

La mia prima risposta!

#~Delete~{{2},{-2}}&~Nest~##&

Il punto cruciale di Mathematica senza staffe! Gli input di funzione sono un elenco (di caratteri o altro) e un numero.


1
Benvenuti in PPCG! : D Bella prima risposta.
Addison Crump,

9

Labirinto , 40 byte

<
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

L'input è Nseguito dalla stringa, separata da qualsiasi carattere non numerico.

Provalo online!

Questo è stato scritto in collaborazione con Sp3000 (il che significa che non potrei essere disturbato a capire un algoritmo, quindi ha iniziato a lavorarci su, ha trovato una soluzione da 118 byte ma non poteva essere disturbato a giocare a golf, quindi ho fatto il golf. .. yay per il lavoro di squadra).

Spiegazione

Primer normale di Sp (come al solito leggermente modificato):

  • Labyrinth è un linguaggio 2D basato su stack con due stack, principale e ausiliario. Praticamente tutto accade nello stack principale, ma puoi spostare i valori sull'altro, ad esempio per invertirli o salvarli per dopo.
  • Le pile sono senza fondo e piene di zeri, quindi spuntare da una pila vuota non è un errore.
  • L'esecuzione inizia dal primo carattere valido (qui in alto a sinistra). Ad ogni giunzione, dove ci sono due o più possibili percorsi che il puntatore dell'istruzione (IP) deve prendere, la parte superiore dello stack viene controllata per determinare dove andare dopo. Il negativo è girare a sinistra, zero è andare avanti e il positivo è girare a destra. Sebbene ciò intendesse rendere il codice simile a passaggi tortuosi e tortuosi, non c'è nulla che ti impedisca di creare "stanze" in cui queste condizioni sono controllate in ogni cella. Questi possono produrre comportamenti abbastanza imprevedibili, ma sono ottimi per il golf.
  • Il codice sorgente (e quindi il layout del labirinto) può essere modificato in fase di esecuzione utilizzando il <>^vquale sposta ciclicamente una riga o colonna o la griglia.
  • " sono vietati.

Eccoci qui.

Il codice inizia sul <, che è un trucco da golf che ho usato alcune volte quando ho iniziato con un lungo pezzo di codice lineare. Sposta ciclicamente la prima riga a sinistra, con l'IP su di essa , quindi l'origine appare così:

              <
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

Ma ora l'IP non può spostarsi da nessuna parte, quindi esegue <nuovamente. Questo continua fino a quando non raggiungiamo questo stato:

    <
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

A questo punto, l'IP può lasciare la cella e iniziare a eseguire la seconda riga a partire da ?. Quindi ecco il codice lineare suddiviso:

?   # Read the first integer on STDIN, i.e. N.
:}  # Duplicate it and move one copy over to the auxiliary stack.
,   # Read the separator character.
,.  # Read the first character of the input string and directly print it.

L'IP ora entra in questa stanza 3x2, che in realtà è due anelli 2x2 strettamente compressi (sovrapposti) in senso orario. Il primo ciclo legge e scarta i N-1caratteri da STDIN.

;   # Discard the top of the stack. On the first iteration, this is the
    # separator we've already read. On subsequent iterations this will be
    # one of the N-1 characters from the input string.
(   # Decrement N. If this hits zero, we leave the loop, otherwise we continue.
,   # Read the next character from STDIN to be discarded.

Ora entriamo nel secondo ciclo che legge il resto della stringa di input. Siamo in grado di rilevare EOF perché ,tornerà -1in quel caso, facendo girare l'IP a sinistra.

,   # Read a character. Exit the loop if EOF.
(   # Decrement it.

Tale decremento non è effettivamente utile, ma possiamo annullarlo in un secondo momento gratuitamente e qui ci consente di sovrapporre i due loop.

Se prendiamo l' 5 ABCDEFGHIJKLMNOPinput come esempio, lo stack si presenta così:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' -1  |  5 ... ] Auxiliary

Si noti che questi corrispondono effettivamente ai caratteri di input FGHIJKLMNOP(perché li abbiamo decrementati) e che in realtà non vogliamo stampare il primo di questi (abbiamo scartato solo i N-1caratteri, ma vogliamo saltare N).

Ora c'è un breve bit lineare che prepara lo stack per il ciclo successivo:

;   # Discard the -1.
=   # Swap the tops of the stacks, i.e. N with the last character. 
    # By putting the last character on the auxiliary stack, we ensure that
    # it doesn't get discarded in the next loop.
}   # Move N over to the auxiliary stack as well.

Le pile ora sembrano:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N'  |  5 'O' ... ] Auxiliary

Entriamo in un altro loop 2x2 in senso orario. Questo scarta i migliori Npersonaggi dallo stack principale:

;   # Discard the top of the main stack.
{   # Pull N over from the auxiliary stack.
(   # Decrement it. It it's 0 we leave the loop.
}   # Push N back to the auxiliary stack.

Quando usciamo dal loop si =scambia di nuovo quello 0e l'ultimo carattere della stringa di input. Ora le pile sembrano così:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'O'  |  ... ] Auxiliary

Vogliamo stampare il contenuto dello stack principale (tranne l'elemento inferiore e tutti incrementati di 1), da sinistra . Ciò significa che dobbiamo trasferirlo nello stack ausiliario. Ecco cosa fa il prossimo ciclo 2x2 (in senso orario):

{   # Pull an element over from the auxiliary stack. This is necessary so we
    # have a 0 on top of the stack when entering the loop, to prevent the IP
    # from turning right immediately.
}   # Move the top of the main stack back to the auxiliary stack. If this was the
    # bottom of the stack, exit the loop.
)   # Increment the current character.
}   # Move it over to the auxiliary stack.

Stack ora:

Main [ ...  |  'F' 'G' 'H' 'I' 'J' 'P] ... ] Auxiliary

Spostiamo il primo di quelli (quello che non vogliamo stampare) nella pila principale con {. E ora entriamo nell'ultimo ciclo 2x2 (in senso antiorario ), che stampa il resto:

{   # Pull another character over from the auxiliary stack. Exit the loop
    # if that's the zero at the bottom of the stack.
.   # Print the character.

Finalmente terminiamo il programma con @.


6

JavaScript (ES6), 39 byte

(s,n)=>s[0]+s.slice(++n,-n)+s.slice(-1)

Risulta che ho appena reinventato la risposta di @ Sp3000.


6

Gelatina, 8 byte

Ḣ1¦UðḤ}¡

Provalo online!

Come funziona

Ḣ1¦UðḤ}¡  Main link. Left input: S (string). Right input: N (deletions)

Ḣ         Pop the first element of S.
          This return the element and modifies S.
 1¦       Apply the result to the first index.
          This replaces the first character of the popped S with the popped char.
   U      Upend/reverse the resulting string.
    ð     Convert the preceding chain into a (dyadic) link.
     Ḥ}   Apply double to the right input.
          This yields 2N.
       ¡  Repeat the link 2N times.

5

Gelatina , 10 byte

Ḣ;ṪjḊṖ$Ɠ¡F

Immettere il numero tramite STDIN e la stringa tramite arg della riga di comando . Grazie a @Dennis per molti suggerimenti / aiuto per far funzionare tutto questo (Jelly mi sfugge ancora).

Provalo online!

Ḣ;Ṫ               Pop first and last chars of string and concatenate
   j              Join by...
       Ɠ¡           Execute n times...
    ḊṖ$               Drop first, drop last of string ($ combines the two monadically)
         F        Flatten to filter out empty lists, since Jelly's j is weird

Domanda onesta, come funzionano i 10 byte? Non è questo in UTF-8 (e non dovrebbe essere di almeno 16 byte perché ḢṪḊṖƓ¡tutti usano più di 1 byte) o usi qualche tipo di tabella di codici carattere per la leggibilità?
AutomatedChaos,

1
@AutomatedChaos Quest'ultimo :) (fare clic sul collegamento in cui la parola "byte" si trova nell'intestazione). Jelly utilizza una tabella codici personalizzata, simile a lingue come APL.
Sp3000,

4

Pyth, 13 byte

++hz:zhQ_hQez

Spiegazione:

              - autoassign z = input()
              - autoassign Q = eval(input())
    :zhQ_hQ   -  z[Q+1:-(Q+1)]
++hz       ez - z[0]+^+z[-1]

Provalo qui


4

Vitsy, 12 9 (codice) + 1 (newline per la dichiarazione di funzione) = 10 byte

\ O /

Prevede input nello stack come stringa seguita dal numero.

2*\[vXvr]
2*         Multiply by 2.
  \[    ]  Do the stuff in the brackets that many times. (input num * 2)
    v      Take the top item off the stack and save it as a local variable.
     X     Remove the top item of the stack.
      v    Push the temporary variable back onto the stack.
       r   Reverse the stack.

Che puoi chiamare con:

'String' r <number> 1m Z
2*\[vXvr]

Questa è una funzione che lascia la stringa risultante nello stack. L'ho fornito come programma nel collegamento TryItOnline.

TryItOnline!


@Adnan fisso - che mi posti in stretta vicinanza alle Pyth. D:
Addison Crump,

Ma ancora un byte avanti: D
Adnan,

@Adnan Potrei cavarmela dicendo che si aspettano oggetti nello stack piuttosto che input? O è un no-no?
Addison Crump,

Non sono sicuro di quale sia la politica per questo, ma se riesci a trovare un meta post sugli oggetti già in pila, va bene :)
Adnan,

@Adnan C'è un meta post sugli elementi che sono già sul nastro per lingue come Brainfuck. Te lo chiederò in meta (perché in realtà è molto importante per Vitsy.: D)
Addison Crump

4

Python 2, 49 48 byte

g=lambda s,n:n and g(s[0]+s[2:-2]+s[-1],n-1)or s

Provalo qui con i testcase!

Semplice soluzione ricorsiva. Rimuove il secondo e l'ultimo secondo elemento dalla stringa di input e si chiama con questo e n-1fino a quando n=0.

modifica: sentirsi un po 'stupido, guardando l'altra soluzione Python . Immagino che mi piaccia troppo la ricorsione ...


4

C, 96 byte

i;main(c,v,p)char**v,*p;{i=atoi(v[2])+1;c=strlen(p=v[1]);printf("%c%.*s%s",*p,c-2*i,p+i,p+c-1);}

Ungolfed

i; /* Param 2, the number of chars to remove */

main(c,v,p)char**v,*p;
{
    i=atoi(v[2])+1; /* convert param 2 to integer */
    c=strlen(p=v[1]); /* Length of the input */
    printf("%c%.*s%s",*p, /* Print the first char... */
        c-2*i, /* a number of characters equal to the length minus twice the input... */
        p+i, /* skip the "removed" chars... */
        p+c-1); /* Print the last character of the string */
}

3

Rubino, 29 byte

->s,n{s[0]+s[n+1...~n]+s[-1]}

Molto semplice.

~trucco rubato dalla risposta di Sp , che salva un byte s[n+1..-2-n]. (Funziona perché ~nè -1-nnel complemento a due, e quindi ...è una gamma esclusiva.)


3

Perl, 36 32 + 1 = 33 byte

for$i(1..<>){s;\B.(.+).(.);$1$2;}

Richiede -pflag e accetta input su due righe, con numeri di iterazioni alla fine:

$ perl -pe'for$i(1..<>){s;\B.(.+).(.);$1$2;}' <<< $'ABCDEFGHIJKLMNOP\n4'
AFGHIJKP

Ungolfed?

for $i ( 1..<> ) {
  s;
  \B.(.+).(.);$1$2;x
}

3

CJam, 12 byte

q~{VW@)t(t}*

Provalo online!

Come funziona

q~            Read and evaluate all input. This pushes S (string) and N (integer).
  {       }*  Do the following N times:
   VW           Push 0 and -1.
     @          Rotate S on top of them.
      )         Pop the last character of S.
       t        Set the item at index -1 to that character.
        (       Pop the first character of S.
         t      Set the item at index 0 to that character.

3

Ottava, 28 byte

@(S,N)S([1,N+2:end-N-1,end])

Indicizza la stringa, omettendo S(2:N+1) e S(end-N:end-1).

Esempio eseguito su ideone .


3

Ruggine, 135 byte

Bene, questa è una lunghezza piuttosto terribile.

fn f(s:&str,n:usize)->String{let s=s.as_bytes();s[..1].iter().chain(&s[n+1..s.len()-n-1]).chain(s.last()).map(|d|*d as char).collect()}

Pretty-stampati:

fn f(s: &str, n: usize) -> String {
    let s = s.as_bytes();
    s[..1].iter()
          .chain(&s[n+1..s.len()-n-1])
          .chain(s.last())
          .map(|d| *d as char)
          .collect()
}

È possibile ridurlo a 104 byte se si consentono le stringhe secondarie anziché le stringhe appropriate.

fn f(s:&[u8],n:usize)->Vec<u8>{let mut r=vec![s[0]];r.extend(&s[n+1..s.len()-n-1]);r.extend(s.last());r}

Pretty-stampati:

fn f(s: &[u8], n: usize) -> Vec<u8> {
    let mut r = vec![s[0]];
    r.extend(&s[n+1..s.len()-n-1]);
    r.extend(s.last());
    r
 }

Curioso se qualcuno può fare di meglio.


3

mSL - 137 byte

c {
%l = $len($1)
return $mid($+($mid($1,2,1),$left($1,1),$right($left($1,-2),-2),$right($1,1),$mid($1,$calc(%l -1),1)),2,$calc(%l -2))
}

Spiegazione:

%l = $len($1) otterrà la lunghezza della stringa di input e la salverà nella variabile chiamata l

$right(<input>,<length>) e $left(<input>,<length> può essere usato per restituire rispettabilmente la parte più a sinistra o a destra della stringa originale. $ left restituisce sempre il testo a partire dalla parte sinistra, mentre $ right restituisce sempre il testo a partire dalla parte destra. Se la lunghezza specificata è un numero negativo, $ sinistra e $ destra restituiscono l'intero testo meno quel numero di caratteri dai rispettivi lati.

$mid(<string>,<start>,[length])viene utilizzato per ottenere una sottostringa dal centro della stringa. Inizio è l'inizio della sottostringa da sinistra. Un valore negativo indica un inizio da destra. In entrambi i casi, è possibile specificare una lunghezza opzionale. Una lunghezza negativa può essere utilizzata per rimuovere tanti caratteri dalla fine. Quindi l'ho usato per recuperare il secondo carattere e il secondo ultimo carattere usando la lunghezza della stringa di input.

$calc(<input>) viene utilizzato per eseguire calcoli matematici


1
Benvenuti in PPCG! In genere è una buona idea aggiungere alcune annotazioni o una spiegazione del codice.
Zach Gates,

@ZachGates Grazie! Lo ricorderò per la prossima volta!
Denny,

2

A partire da un linguaggio ancora senza titolo (così nuovo non competitivo), 9 byte

hD_RQ:Q|J

Puoi trovare il codice sorgente qui , la lingua è completamente instabile (prima prova del test), quindi non aspettarti che funzioni in futuro (commit 7)

Questo è un linguaggio basato su stack con funzioni che aggiungono e rimuovono oggetti dallo stack. Attualmente ci sono 2 comandi di manipolazione dello stack: D(duplica la parte superiore dello stack N volte) eR (ruota le prime N voci sulla pila)

Spiegazione:

          - autoassign Q = eval_or_not(input()) (string)
h         - imp_eval_input()+1
 D        - duplicate(^)
  _       - neg(^)
   R      - rotate(^)
    Q:    - Q[^:^]
      Q|  - Q[0], Q[-1]
        J - "".join(all)

2

CJam, 14 byte

l(o)\l~_W*@<>o

Provalo qui.

Spiegazione

l   e# Read the input string.
(o  e# Pull off the first character and print it.
)\  e# Pull off the last character and swap with the rest of the string.
l~  e# Read the second line of the input and evaluate it (N).
_   e# Duplicate.
W*  e# Multiply by -1 to get -N.
@   e# Pull up the string.
<   e# Discard the last N characters.
>   e# Discard the first N characters.
o   e# Output what's left. The last character of the input is now still on the
    e# stack and is automatically printed at the end of the program.

2

Vim, 27 byte

o0lxehx <ESC>"ay0ddA@a<ESC>B"bdWx@b

L'input dovrebbe essere nel modulo STRING N nella prima riga senza altri caratteri.

Spiegazione:

#Write a macro to do one round of the swap and delete and save to register a
o0lxehx <ESC>"ay0dd

#Append register a to N and save in register B so it will run @a N times.
A@a<ESC>B"bdWx

# Actually run the macro
@b

2

Brainfuck, 130 byte

La mia prima voce PPCG!

Ovviamente non vincerò, ma ehi.

Accetta input come: 4ABCDEFGHIJKL, con il primo carattere N.

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

Provalo su questo meraviglioso sito.

Limitato a N minore o uguale a 9, perché i numeri a due cifre sono un dolore nel calcio.

EDIT: l'ho succhiato e ho aggiunto il supporto per i numeri a due cifre. Tampone con zero per cifre singole.

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

Benvenuti in PPCG! Questa è un'ottima prima risposta! :)
Adnan,

@AandN grazie! Ho cercato per un po 'una sfida che potesse essere ragionevolmente facilmente risolta in BF, che è una delle mie nuove lingue preferite: D
vasilescur

2

Perl, 27 byte

Includi +1 per -p

Correre come perl -p sdr.pl

Input dato su STDIN, prima riga della stringa, seconda riga il conteggio Presuppone che la stringa contenga solo caratteri "word"

sdr.pl:

eval's%\B.(.*).\B%$1%;'x<>

1

PHP, 60 byte

Questa soluzione imposta in modo iterativo i caratteri dalla stringa di input a una stringa vuota per indice. Sto manipolando direttamente la stringa di input per evitare un lungo return.

function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";};

Fondamentalmente in memoria $wappare come questo quando fatto:

Addr 0 1 2 3 4
     H   l   o
     ^   ^   ^
>Result: Hlo

Esegui in questo modo:

php -r '$f = function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";}; $f($argv[1],$argv[2]);echo"$argv[1]\n";' Hello 1

PHP 4.1 (50 byte): <?for(;$I;)$W[$I--]=$W[strlen($W)-$I-2]="";echo$W;. Si aspetta i valori sui tasti We I, su POST / GET / COOKIE ... Un esempio potrebbe esserehttp://example.com/a.php?W=MyString&I=5
Ismael Miguel,

1
Sì, non voglio fare risposte che richiedono register globalspiù. Grazie per il suggerimento :)
Circa il

1

Piloni , 16 byte.

i:At,{\,v\,v,A}c

Come funziona:

i    # Get command line input.
:At  # Set A equal to the top of the stack.
,    # Pop the stack.
{    # Start a for loop.
 \   # Swap the top two elements of the stack.
  ,  # Pop the stack.
   v # Reverse the stack.
 \   # Swap the top two elements of the stack.
  ,  # Pop the stack.
   v # Reverse the stack.
 ,   # Switch to loop iterations.
 A   # Iterate A times.
}    # End the for loop.
c    # Print the stack as a string

1

CJam, 15 byte

r(\)\{(;);}ri*\

Sono sicuro che è possibile giocare a golf ulteriormente ...


1

Jolf, 13 byte

ΆFi liγhj_γgi

Una traduzione della risposta JavaScript.

Spiegazione:

ΆFi liγhj_γgi
Ά             ternary add
 Fi            i[0],
   `li         i sliced
      γhj       γ = j + 1
         _γ     to -γ
           gi  and the last of i

Provalo qui!

Una versione post-domanda più interessante:

 ΆFi]ihjYgi

1

Scherzi a parte, 17 byte

,#,`p@pXod@dXq`nΣ

Accetta input come s \n n.

Provalo online!

Spiegazione:

,#,`p@pXod@dXq`nΣ
,#                 push a list of characters in s
  ,`          `n   do the following n times:
    p@pXo          pop 2 characters off the front, discard the second, put the first back
         d@dXq     pop 2 characters off the back, discard the second, put the first back
                Σ  join

1

C #, 129 byte

Dato che in pratica saltiamo 1 e rimuoviamo N e lo scenario invertito

string o(string i,int n){var s=i.ToList();int x=0;while(x<2){s.RemoveRange(1,n);s.Reverse();x++;}return new string(s.ToArray());}

ungolfed

string o(string i, int n)
{
    var s = i.ToList();
    int x = 0;
    while (x < 2) //Repeat the following twice
    {
        s.RemoveRange(1, n); //remove n at index 1
        s.Reverse(); //Reverse the list
        x++;
    }
    return new string(s.ToArray());
}

In che modo è possibile ridurre la lunghezza dello script usando questo per il loop: for (int x = 0xi <2; i ++)
t-clausen.dk

1

Java, 144 byte

static String y(int i,String s){return i==0?s:y(i-1,new StringBuffer(s).replace(1,2,"").replace(s.length()-3,s.length()-2,"").toString());}
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.