Elementos que desaparecen


17

Dada una cadena Sy una lista de índices X, modifique Seliminando el elemento en cada índice de Smientras usa ese resultado como el nuevo valor de S.

Por ejemplo, dado S = 'codegolf'y X = [1, 4, 4, 0, 2],

0 1 2 3 4 5 6 7  |
c o d e g o l f  |  Remove 1
c d e g o l f    |  Remove 4
c d e g l f      |  Remove 4
c d e g f        |  Remove 0
d e g f          |  Remove 2
d e f

Su tarea es realizar este proceso, recopilar los valores de Sdespués de cada operación y mostrarlos en una nueva línea en orden. La respuesta final sería

S = 'codegolf'
X = [1, 4, 4, 0, 2]

Answer:

codegolf
cdegolf
cdeglf
cdegf
degf
def
  • Este es el así que haga su código lo más corto posible.
  • Puede suponer que los valores en Xson siempre índices válidos para S, y puede usar indexación basada en 0 o en 1.
  • La cadena solo contendrá [A-Za-z0-9]
  • Cualquiera So xpuede por vacío. Si Sestá vacío, se deduce que xtambién debe estar vacío.
  • También puede tomar Scomo una lista de caracteres en lugar de una cadena.
  • Puede imprimir el resultado o devolver una lista de cadenas. Los espacios en blanco iniciales y finales son aceptables. Cualquier forma de salida está bien siempre que sea fácil de leer.

Casos de prueba

S = 'abc', x = [0]
'abc'
'bc'

S = 'abc', x = []
'abc'

S = 'abc', x = [2, 0, 0]
'abc'
'ab'
'b'
''

S = '', x = []
''

S = 'codegolfing', x = [10, 9, 8, 3, 2, 1, 0]
'codegolfing'
'codegolfin'
'codegolfi'
'codegolf'
'codgolf'
'cogolf'
'cgolf'
'golf'
code-golf  string  array-manipulation  code-golf  string  ascii-art  code-golf  number  sequence  pi  code-golf  number  array-manipulation  code-golf  string  ascii-art  code-golf  math  number  game  code-golf  math  sequence  polynomials  recursion  code-golf  math  number  sequence  number-theory  code-golf  permutations  balanced-string  code-golf  string  ascii-art  integer  code-golf  decision-problem  hexagonal-grid  code-golf  ascii-art  kolmogorov-complexity  code-golf  number  code-golf  matrix  binary-matrix  code-golf  math  statistics  code-golf  string  polyglot  code-golf  random  lost  code-golf  date  path-finding  code-golf  string  code-golf  math  number  arithmetic  number-theory  code-golf  tetris  binary-matrix  code-golf  array-manipulation  sorting  code-golf  number  code-golf  array-manipulation  rubiks-cube  cubically  code-golf  grid  optimization  code-golf  math  function  code-golf  string  quine  code-golf  ascii-art  grid  code-golf  decision-problem  grid  simulation  code-golf  math  sequence  code-golf  path-finding  code-golf  ascii-art  grid  simulation  code-golf  number  whitespace  code-golf  sequence  code-golf  sequence  code-golf  sequence  integer  code-golf  math  game  code-golf  internet  stack-exchange-api  code-golf  sequence  code-golf  internet  stack-exchange-api  code-golf  math  factoring  code-challenge  sequence  polyglot  rosetta-stone  code-golf  string  browser  code-golf  date  code-golf  base-conversion  code-challenge  cops-and-robbers  hello-world  code-golf  cops-and-robbers  hello-world 

¿Podemos tomar Scomo una lista de personajes?
Sr. Xcoder

@ Mr.Xcoder Claro, lo agregaré en la especificación.
millas

¿Podemos imprimir como una lista de personajes?
Erik the Outgolfer

¿Podemos omitir el primer elemento (la cadena original) en la salida?
ETHproductions

@ETHproductions No, la salida debe ser primero la cadena original y luego cada cadena resultante de la eliminación de un carácter. Por lo tanto, la salida debe contener len(x)+1cadenas.
millas

Respuestas:


8

Haskell, 38 33 bytes

s#i=take i s++drop(i+1)s
scanl(#)

Directo: tome repetidamente los elementos antes y después del índice i, vuelva a unirlos y recopile los resultados.

Pruébalo en línea!

Editar: @Lynn guardó 5 bytes. ¡Gracias!


s#i=take i s++drop(i+1)sen realidad es más corto, ahorrando 5 bytes.
Lynn

1
No, ahora tienes 33 años, no olvides que el fragmento TIO tiene q=allí ^^;
Lynn

Sí, tienes razón.
nimi

8

JavaScript (ES6), 57 50 48 45 42 bytes

Toma la cadena como una matriz de caracteres individuales, genera una matriz que contiene una cadena separada por comas del original, seguida de una submatriz de cadenas separadas por comas para cada paso.

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]
  • 3 bytes guardados gracias a Arnauld sugiriendo que abusé de la especificación de salida suelta más de lo que ya era, lo que me llevó a abusar aún más para otro ahorro de 3 bytes.

Pruébalo

o.innerText=JSON.stringify((f=

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]

)([...i.value="codegolf"])(j.value=[1,4,4,0,2]));oninput=_=>o.innerText=JSON.stringify(f([...i.value])(j.value.split`,`))
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;}
<label for=i>String: </label><input id=i><label for=j>Indices: </label><input id=j><pre id=o>


Explicación

Tomamos las dos entradas a través de parámetros s(la matriz de cadenas) y a(la matriz de enteros) en sintaxis de curry, lo que significa que llamamos a la función con f(s)(a).

Construimos una nueva matriz y comenzamos con la original s. Sin embargo, como el splicemétodo que usaremos más adelante modifica una matriz, necesitamos hacer una copia de ella, lo que podemos hacer convirtiéndola en una cadena (simplemente agregue una cadena vacía).

Para generar la submatriz, pasamos por mapencima de la matriz de enteros a(donde xes el entero actual) y, para cada elemento, tomamos splice1 elemento desde s, comenzando en el índice x. Devolvemos el modificado s, nuevamente haciendo una copia convirtiéndolo en una cadena.


Debido a que cualquier forma de salida está bien siempre que sea fácil de leer , supongo que también debería ser aceptable:s=>a=>[s+'',...a.map(x=>s.splice(x,1)&&s+'')]
Arnauld

Buena, @Arnuald: no habría pensado en llegar tan lejos, incluso teniendo en cuenta esa especificación.
Shaggy

6

Japt , 6 bytes

åjV uV

¡Pruébelo en línea!

Explicación

UåjV uV   Implicit: U = array of integers, V = string
Uå        Cumulatively reduce U by
  j         removing the item at that index in the previous value,
   V        with an initial value of V.
     uV   Push V to the beginning of the result.

Alternativamente:

uQ åjV

UuQ       Push a quotation mark to the beginning of U.
    å     Cumulatively reduce by
     j      removing the item at that index in the previous value,
      V     with an initial value of V.

Esto funciona porque eliminar el elemento en el índice "no hace nada y, por lo tanto, devuelve la cadena original.


6

Cáscara , 7 bytes

G§+oh↑↓

Primero toma la cadena, luego los índices (basados ​​en 1). Pruébalo en línea!

Explicación

G§+oh↑↓
G        Scan from left by function:
           Arguments are string, say s = "abcde", and index, say i = 3.
      ↓    Drop i elements: "de"
     ↑     Take i elements
   oh      and drop the last one: "ab"
 §+        Concatenate: "abde"
         Implicitly print list of strings on separate lines.

¿Cómo uso una lista vacía de índices x?
millas

@miles Tienes que especificar el tipo, así .
Zgarb

Ya veo, gracias. No estoy muy familiarizado con Haskell o Husk.
millas

6

Python 2 , 43 bytes

s,i=input()
for i in i+[0]:print s;s.pop(i)

Pruébalo en línea!

Cualquier forma de salida está bien siempre que sea fácil de leer.

Entonces esto se imprime como listas de caracteres.


1
Bien, pero ¿por qué elegiste el abuso de notación for i in i+[0]?
Sr. Xcoder

@ Mr.Xcoder Porque así se muestra la última línea. (y la razón por
la que publiqué

No, no +[0], estoy hablando for i in i. for k in ies equivalente .
Sr. Xcoder

@ Mr.Xcoder Porque así me gusta ...
Erik the Outgolfer

Ok, solo curiosidad ... Tal vez fue un truco del que no sabía :)
Sr. Xcoder

5

Python 2 , 47 bytes

Esto podría acortarse a 43 bytes , como señaló @LuisMendo, pero esa ya es la solución de @ ErktheOutgolfer.

a,b=input();print a
for i in b:a.pop(i);print a

Pruébalo en línea!


`a`[2::5]en cambio''.join(a)
Rod

@ Rod ¿Cómo funciona eso?
Sr. Xcoder

repry la división de cadenas, funciona bien para convertir una lista de caracteres en una cadena, `a`[1::3]también se puede usar con una lista de dígitos
Rod

@ Rod Sé lo que son, no entiendo cómo ::5funciona aquí: P
Sr. Xcoder

@ Mr.Xcoder bien, luego estudie el corte de cadenas;) básicamente se necesita cada 5 ° char a partir del 2 °
Erik the Outgolfer

4

Java 8, 78 bytes

Esta es una lambda al curry, de int[]a un consumidor de StringBuildero StringBuffer. La salida se imprime a la salida estándar.

l->s->{System.out.println(s);for(int i:l)System.out.println(s.delete(i,i+1));}

Pruébalo en línea


1
Su segunda respuesta es una entrada válida. Nada le prohíbe seleccionar cuidadosamente su tipo de entrada siempre que tenga sentido. Varias veces ya tomé incluso Streams como entrada y obtuve respuestas muy agradables. En realidad, casi todos los idiomas de golf usan flujos equivalentes internamente. Entonces, al seleccionar su entrada, simplemente nivela un poco. +1 no obstante
Olivier Grégoire

Quizás tengas razón. Creo que tiendo a ser más conservador que la mayoría de estas cosas. Cambiaré a la segunda solución.
Jakob

3

05AB1E , 11 bytes

v=ā0m0yǝÏ},

Pruébalo en línea!

v           # For each index:
 =          #   Print without popping
  ā         #   Push range(1, len(a) + 1)
   0m       #   Raise each to the power of 0. 
            #   This gives a list of equal length containing all 1s
     0yǝ    #   Put a 0 at the location that we want to remove
        Ï   #   Keep only the characters that correspond to a 1 in the new list
         }, # Print the last step

La primera línea no está ahí. Ah, y no estoy seguro si puedes imprimir así.
Erik the Outgolfer

@EriktheOutgolferAny form of output is fine as long as it is easily readable
Riley

Puedo guardar algunos bytes entonces ...
Erik the Outgolfer


3

R , 46 32 bytes

function(S,X)Reduce(`[`,-X,S,,T)

Pruébalo en línea!

Toma la entrada como una lista de caracteres y Xestá basada en 1. Reducees el equivalente R de fold, la función en este caso es [cuál es el subconjunto. Se repite -Xporque la indexación negativa en R elimina el elemento y initse establece en S, con accum=TRUElo que acumulamos los resultados intermedios.

R , 80 bytes

function(S,X,g=substring)Reduce(function(s,i)paste0(g(s,0,i-1),g(s,i+1)),X,S,,T)

2-argument function, takes X 1-indexed. Takes S as a string.

Try it online!


Very smart to use Reduce here. Well done!
djhurio


3

PowerShell, 94 84 bytes

param($s,$x)$a=[Collections.Generic.list[char]]$s;$x|%{-join$a;,$a|% r*t $_};-join$a

Try it online!

Takes input $s as a string and $x as an explicit array. We then create $a based on $s as a list.

Arrays in PowerShell are fixed size (for our purposes here), so we need to use the lengthy [System.Collections.Generic.list] type in order to get access to the .removeAt() function, which does exactly what it says on the tin.

I sacrificed 10 bytes to include two -join statements to make the output pretty. OP has stated that outputting a list of chars is fine, so I could output just $a rather than -join$a, but that's really ugly in my opinion.

Saved 10 bytes thanks to briantist.


You can leave off System and just use [Collections.Generic.list[char]]. To keep it pretty without sacrificing bytes, you can put the last -join$a in the footer in TIO.
briantist

I think you can also save 3 bytes by changing $a.removeat($_) to ,$a|% r*t $_.
briantist

@briantist Thanks for those - I always forget to remove System from the class name. Sadly the last -join$a is necessary for the code, so I can't move it to the footer.
AdmBorkBork


2

05AB1E, 9 7 bytes

=svõyǝ=

Try it online!


=s        # Print original string, swap with indices.
  v       # Loop through indices...
   õyǝ    # Replace current index with empty string.

-2 thanks to idea from @ETHProductions.


This doesn't print anything if x is empty.
Riley

@Riley fixed. (#ETHProductions fixed.)
Magic Octopus Urn

1
Couldn't you just do =sv""yǝ= or something similar instead of replacing with a newline and then removing the newline?
ETHproductions

@ETHproductions õ also works :)
Magic Octopus Urn

Well I don't know 05AB1E, haha
ETHproductions

2

Retina, 58 bytes

¶\d+
¶¶1$&$*
+1`(?=.*¶¶.(.)*)(((?<-1>.)*).(.*)¶)¶.*
$2$3$4

Try it online! Explanation:

¶\d+

Match the indices (which are never on the first line, so are always preceded by a newline).

¶¶1$&$*

Double-space the indices, convert to unary, and add 1 (because zeros are hard in Retina).

+1`

Repeatedly change the first match, which is always the current value of the string.

   (?=.*¶¶.(.)*)

Retrieve the next index in $#1.

                (           .    ¶)

Capture the string, including the $#1th character and one newline.

                 ((?<-1>.)*) (.*)

Separately capture the prefix and suffix of the $#1th character of the string.

                                   ¶.*

Match the index.

$2$3$4

Replace the string with itself and the index with the prefix and suffix of the $#1th character.


2

Pyth, 8 bytes

.u.DNYEz

Demonstration

Reduce, starting with the string and iterating over the list of indices, on the deletion function.


2

PowerShell, 54 58 bytes

param($s,$x),-1+$x|%{$z=$_;$i=0;-join($s=$s|?{$z-ne$i++})}

Try it online!

Explanation

Takes input as a char array ([char[]]).

Iterates through the array of indices ($x) plus an injected first element of -1, then for each one, assigns the current element to $z, initializes $i to 0, then iterates through the array of characters ($s), returning a new array of only the characters whose index ($i) does not equal (-ne) the current index to exclude ($z). This new array is assigned back to $s, while simultaneously being returned (this happens when the assignment is done in parentheses). That returned result is -joined to form a string which is sent out to the pipeline.

Injecting -1 at the beginning ensures that the original string will be printed, since it's the first element and an index will never match -1.


1
Very clever way of pulling out the appropriate indices.
AdmBorkBork

2

q/kdb+, 27 10 bytes

Solution:

{x _\0N,y}

Examples:

q){x _\0N,y}["codegolf";1 4 4 0 2]
"codegolf"
"cdegolf"
"cdeglf"
"cdegf"
"degf"
"def"
q){x _\0N,y}["abc";0]
"abc"
"bc"
q){x _\0N,y}["abc";()]
"abc"
q){x _\0N,y}["abc";2 0 0]
"abc"
"ab"
,"b"
""    
q){x _\0N,y}["";()]
""

Explanation:

Takes advantage of the converge functionality \ as well as drop _.

{x _\0N,y}
{        } / lambda function, x and y are implicit variables
     0N,y  / join null to the front of list (y), drop null does nothing
   _\      / drop over (until result converges) printing each stage
 x         / the string (need the space as x_ could be a variable name)

Notes:

If we didn't need to print the original result, this would be 2 bytes in q:

q)_\["codegolfing";10 9 8 3 2 1 0]
"codegolfin"
"codegolfi"
"codegolf"
"codgolf"
"cogolf"
"cgolf"
"golf"

2

Perl 5, 55 bytes (54 + "-l")

sub{print($s=shift);for(@_){substr$s,$_,1,"";print$s}}

Try it online!


Nice! I came up with a very similar approach, but as a full program (using -pa) for 44 bytes: $_=<>;substr$_,shift@F,print,""while@F&&$_
Dom Hastings

Nice! Not sure you need the final &&$_ since you can assume the input is valid (the list of indices can't be longer than the string). Using the return value of print as the number of characters is quite slick.
aschepler

Ah, that's true! I didn't notice that part of the spec! I thought my answer was far too similar to yours to post separately though!
Dom Hastings

2

MATL, 8 bytes

ii"t[]@(

Indexing is 1-based.

Try it online! Or verify the test cases.

Explanation

i      % Input string. Input has to be done explicitly so that the string
       % will be displayed even if the row vector of indices is empty
i      % Input row vector of indices
"      % For each
  t    %   Duplicate current string
  []   %   Push empty array
  @    %   Push current index
  (    %   Assignment indexing: write [] to string at specified index
       % End (implicit). Display stack (implicit)

2

C# (.NET Core), 87 87 74 70 bytes

S=>I=>{for(int i=0;;S=S.Remove(I[i++],1))System.Console.WriteLine(S);}

Try it online!

Just goes to show that recursion isn't always the best solution. This is actually shorter than my original invalid answer. Still prints to STDOUT rather than returning, which is necessary because it ends with an error.

-4 bytes thanks to TheLethalCoder


Per a recent meta consensus (that I can't find) recursive lambdas in C# are disallowed unless you specify what they compile to in the byte count. Therefore, a full method is shorter in this case. I am downvoting until this is fixed, let me know when.
TheLethalCoder

@TheLethalCoder I may not agree with the consensus, but it does seem to be consensus. I've updated my answer.
Kamil Drakari

70 bytes. Use currying and move one statement into the loop to stop needing the loop braces.
TheLethalCoder

@TheLethalCoder Ah, so THAT's how you use currying in C#! I knew it was shorter for exactly two arguments, but it always ended up complaining about some part of my syntax. Thanks for the improvements
Kamil Drakari

No worries and yeah the first one must always be a Func that returns the other Func, Action, Predicate,...
TheLethalCoder



1

Gaia, 9 bytes

+⟪Seḥ+⟫⊣ṣ

I should really add a "delete at index" function...

Try it online!

Explanation

+          Add the string to the list
 ⟪Seḥ+⟫⊣   Cumulatively reduce by this block:
  S         Split around index n
   e        Dump the list
    ḥ       Remove the first char of the second part
     +      Concatenate back together
        ṣ  Join the result with newlines

1

V, 12 bytes

òdt,GÙ@-|xHx

Try it online!

This is 1-indexed, input is like:

11,10,9,4,3,2,1,
codegolfing

Explanation

ò              ' <M-r>ecursively until error
 dt,           ' (d)elete (t)o the next , (errors when no more commas)
    G          ' (G)oto the last line
     Ù         ' Duplicate it down
        |      ' Goto column ...
      @-       ' (deleted number from the short register)
         x     ' And delete the character there
          H    ' Go back home
           x   ' And delete the comma that I missed

How do I use an empty list of indices x?
miles

@miles By adding a few bytes :). Simply an empty first line will now work. Would you be OK if I took lists with a trailing comma? IE 1,2,3,. Empty list would be nothing, Singleton would be 1,
nmjcman101

Sure, you can use that input format.
miles


1

Pyth, 8 bytes

+zm=z.Dz

Test suite!

explanation

+zm=z.DzdQ    # implicit: input and iteration variable
  m      Q    # for each of the elements of the first input (the array of numbers, Q)
     .Dzd     # remove that index from the second input (the string, z)
   =z         # Store that new value in z
+z            # prepend the starting value



Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.