Kaybolan Elemanlar


17

Bir dize Sve bir dizin listesi verildiğinde X, bu sonucu yeni değeri olarak kullanırken Sher dizindeki öğeyi kaldırarak değiştirin .SS

Örneğin, verilen S = 'codegolf've 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

Göreviniz bu işlemi gerçekleştirmek, Sher işlemden sonra değerlerini toplamak ve her birini yeni bir satırda sırayla görüntülemek. Son cevap

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

Answer:

codegolf
cdegolf
cdeglf
cdegf
degf
def
  • Bu bu yüzden kodunuzu mümkün olduğunca kısa yapın.
  • İçindeki değerlerin Xher zaman için geçerli endeksler olduğunu varsayabilir Sve 0 tabanlı veya 1 tabanlı dizinleme kullanabilirsiniz.
  • Dize yalnızca [A-Za-z0-9]
  • Ya Sya xgöre boş olabilir. Eğer Sboş, öyle izler xde boş olması gerekir.
  • Ayrıca S, dize yerine karakterlerin bir listesini de alabilirsiniz .
  • Çıktıyı yazdırabilir veya bir dize listesi döndürebilirsiniz. Öncü ve sondaki boşluk kabul edilebilir. Kolayca okunabildiği sürece herhangi bir çıktı şekli iyidir.

Test Durumları

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 

SKarakterlerin bir listesini alabilir miyiz ?
Bay Xcoder

@ Mr.Xcoder Tabii, bunu spesifikasyona ekleyeceğim.
mil

Bir karakter listesi olarak yazdırabilir miyiz?
Outgolfer Erik

Çıktıdaki ilk öğeyi (orijinal dize) atlayabilir miyiz?
ETHproductions 11:17

@ETHproductions Hayır, çıktı önce orijinal dize sonra da bir karakterin silinmesinden kaynaklanan her dize olmalıdır. Bu nedenle çıktı len(x)+1dizeler içermelidir .
mil

Yanıtlar:


8

Haskell, 38 33 bayt

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

Düz ileri: elemanları indeks i'den önce ve sonra tekrar tekrar alın, tekrar birleştirin ve sonuçları toplayın.

Çevrimiçi deneyin!

Düzenleme: @Lynn 5 bayt kaydetti. Teşekkürler!


s#i=take i s++drop(i+1)saslında daha kısadır ve 5 bayt tasarruf sağlar.
Lynn

1
Hayır, şu anda 33 yaşındasınız - TIO snippet'inin q=orada olduğunu unutmayın ^ ^;
Lynn

Evet, haklısın.
nimi

8

JavaScript (ES6), 57 50 48 45 42 bayt

Dizeyi tek tek karakter dizisi olarak alır, orijinalin virgülle ayrılmış dizesini ve ardından her adım için virgülle ayrılmış dizelerin alt dizisini içeren bir dizi çıkarır.

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]
  • Arnauld sayesinde 3 bayt tasarruf etti , gevşek çıkış özelliğini zaten olduğumdan daha fazla kötüye kullandığımı düşündürdü, bu da beni 3 baytlık bir tasarruf için daha da kötüye kullanmamı sağladı.

Dene

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>


açıklama

İki girdiyi curry sözdiziminde parametreler s(dize dizisi) ve a(tamsayı dizisi) aracılığıyla alırız, yani işlev ile çağırırız f(s)(a).

Yeni bir dizi oluşturuyoruz ve orijinal ile başlıyoruz s. Bununla birlikte, splicedaha sonra kullanacağımız yöntem bir diziyi değiştirdiğinden, bir dizesini dönüştürerek bir dizeye dönüştürmemiz gerekir (sadece boş bir dize ekleyin).

Alt mapdiziyi oluşturmak için , tamsayı dizisi üzerinde a( xgeçerli tamsayı nerede ) ve her öğe için, dizinden başlayarak splice1 öğeden sbaşlıyoruz x. Değiştirilmiş solanı döndürüyoruz , yine bir dizeye dönüştürerek bir kopyasını yapıyoruz.


Çünkü çıkış herhangi bir biçimde uzun kolayca okunabilir olduğu kadar iyi , bir tane de kabul edilebilir olmalıdır olduğunu varsayalım:s=>a=>[s+'',...a.map(x=>s.splice(x,1)&&s+'')]
Arnauld

Oneyi biri, @Arnuald - O özellikleri bile verdim, o kadar ileriye götürmeyi düţünemezdim.
Shaggy

6

Japt , 6 bayt

åjV uV

Çevrimiçi test edin!

açıklama

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.

Alternatif:

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.

Bu, dizindeki öğeyi kaldırmanın "hiçbir şey yapmaması ve bu nedenle orijinal dizeyi döndürmesi nedeniyle çalışır .


6

Kabuk , 7 bayt

G§+oh↑↓

Önce dizeyi alır, sonra (1 tabanlı) endeksler. Çevrimiçi deneyin!

açıklama

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.

Boş bir indeks listesini nasıl kullanabilirim x?
mil

@miles Sen türünü belirtmek zorunda böyle .
Zgarb

Teşekkürler görüyorum. Haskell ya da Husk'a pek aşina değilim.
mil

6

Python 2 , 43 bayt

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

Çevrimiçi deneyin!

Kolayca okunabildiği sürece herhangi bir çıktı şekli iyidir.

Bu, karakter listeleri olarak yazdırılır.


1
Güzel, ama neden gösterim kötüye kullanımını seçtiniz for i in i+[0]?
Bay Xcoder

@ Mr.Xcoder Çünkü bu şekilde son satır gösterilir. (ve ilk etapta ayrı olarak yayınlamamın nedeni)
Outgolfer Erik

Hayır, değil +[0], hakkında konuşuyorum for i in i. for k in ieşdeğerdir .
Bay Xcoder

@ Mr.Xcoder Çünkü bu şekilde beğendim ...
Outgolfer Erik

Tamam, sadece merak ediyorum ... Belki de bilmediğim bir numaraydı :)
Bay Xcoder

5

Python 2 , 47 bayt

This could be shortened to 43 bytes, as @LuisMendo pointed out, but that's already @ErktheOutgolfer's solution.

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

Try it online!


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

@Rod How does than work?
Mr. Xcoder

repr and string spliting, works good to turn a list of characters into a string, `a`[1::3] can also be used with a list of digits
Rod

@Rod I know what they are, I don't understand how ::5 works here :P
Mr. Xcoder

@Mr.Xcoder well then study string slicing ;) basically it takes every 5th char starting from the 2nd
Erik the Outgolfer

4

Java 8, 78 bytes

This is a curried lambda, from int[] to a consumer of StringBuilder or StringBuffer. Output is printed to standard out.

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

Try It Online


1
Your second answer is a valid entry. Nothing forbids you to carefully select your input type as long as it makes sense. I've several times already taken even Streams as input and got very nice answers. Actually, nearly all golfing languages use streams equivalent internally. So by selecting your input, you just level a tad. +1 nonetheless
Olivier Grégoire

Maybe you're right. I think I tend to be more conservative than most about these things. I'll switch to the second solution.
Jakob

3

05AB1E, 11 bytes

v=ā0m0yǝÏ},

Try it online!

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

The first line isn't there. Oh, and not sure if you can print like that.
Erik the Outgolfer

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

I can save some bytes then...
Erik the Outgolfer


3

R, 46 32 bytes

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

Try it online!

Takes input as a list of characters and X is 1-based. Reduce is the R equivalent of fold, the function in this case is [ which is subset. Iterates over -X because negative indexing in R removes the element, and init is set to S, with accum=TRUE so we accumulate the intermediate results.

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



Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.