Elemen Hilang

17

Diberikan string Sdan daftar indeks X, modifikasi Sdengan menghapus elemen pada setiap indeks Ssaat menggunakan hasil itu sebagai nilai baru S.

Misalnya, diberikan S = 'codegolf'dan 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

Tugas Anda adalah melakukan proses ini, mengumpulkan nilai Ssetelah setiap operasi, dan menampilkannya masing-masing pada baris baru secara berurutan. Jawaban akhirnya adalah

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

Answer:

codegolf
cdegolf
cdeglf
cdegf
degf
def
  • Ini jadi buat kode Anda sesingkat mungkin.
  • Anda dapat mengasumsikan bahwa nilai-nilai dalam Xselalu merupakan indeks yang valid S, dan Anda dapat menggunakan pengindeksan berbasis 0 atau 1.
  • String hanya akan berisi [A-Za-z0-9]
  • Entah Satau xmungkin dengan kosong. Jika Skosong, maka itu xjuga harus kosong.
  • Anda juga dapat mengambil Ssebagai daftar karakter, bukan string.
  • Anda dapat mencetak output atau mengembalikan daftar string. Ruang putih terkemuka dan tertinggal dapat diterima. Segala bentuk output baik-baik saja asalkan mudah dibaca.

Uji Kasus

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'
mil
sumber
Bolehkah kita mengambil Ssebagai daftar karakter?
Tn. Xcoder
@ Mr.Xcoder Tentu, saya akan menambahkannya di spec.
mil
Bisakah kita mencetak sebagai daftar karakter?
Erik the Outgolfer
Bisakah kita lewati item pertama (string asli) di output?
ETHproduksi
@ ETHproductions Tidak, output harus menjadi string asli terlebih dahulu, dan kemudian setiap string yang dihasilkan dari menghapus karakter. Jadi output harus mengandung len(x)+1string.
mil

Jawaban:

8

Haskell, 38 33 byte

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

Lurus ke depan: berulang kali ambil elemen sebelum dan sesudah indeks i, bergabung kembali dan kumpulkan hasilnya.

Cobalah online!

Sunting: @ Lynn menyimpan 5 byte. Terima kasih!

nimi
sumber
s#i=take i s++drop(i+1)ssebenarnya lebih pendek, menghemat 5 byte.
Lynn
1
Tidak, Anda berusia 33 tahun sekarang - jangan lupa bahwa cuplikan TIO q=ada di sana ^^;
Lynn
Yap, kamu benar.
nimi
8

JavaScript (ES6), 57 50 48 45 42 byte

Mengambil string sebagai larik karakter individu, menghasilkan larik yang berisi string yang dipisahkan koma dari aslinya diikuti oleh subarray string yang dipisahkan koma untuk setiap langkah.

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]
  • 3 byte yang disimpan berkat Arnauld yang menyarankan saya menyalahgunakan spesifikasi output yang longgar lebih dari yang sudah saya lakukan sebelumnya, yang membuat saya lebih menyalahgunakannya untuk penghematan 3 byte lainnya.

Menguji

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>


Penjelasan

Kami mengambil dua input melalui parameter s(array string) dan a(array integer) dalam sintaks currying, artinya kita memanggil fungsi denganf(s)(a) .

Kami membangun array baru dan memulainya dengan yang asli s. Namun, sebagaisplice metode yang akan kita gunakan nanti memodifikasi array, kita perlu membuat salinannya, yang bisa kita lakukan dengan mengubahnya menjadi string (cukup tambahkan string kosong).

Untuk menghasilkan subarray, kita mapmelewati array integer a(di mana xinteger saat ini) dan, untuk setiap elemen, kita splice1 elemen dari s, dimulai dari indeks x. Kami mengembalikan yang dimodifikasi s, kembali membuat salinannya dengan mengubahnya menjadi string.

Shaggy
sumber
Karena segala bentuk output baik-baik saja asalkan mudah dibaca , saya kira itu juga harus diterima:s=>a=>[s+'',...a.map(x=>s.splice(x,1)&&s+'')]
Arnauld
Bagus sekali, @Arnuald - Saya tidak akan berpikir untuk mendorongnya sejauh itu, bahkan mengingat spek itu.
Shaggy
6

Japt , 6 byte

åjV uV

Uji secara online!

Penjelasan

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.

Kalau tidak:

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.

Ini berfungsi karena menghapus item pada indeks "tidak melakukan apa-apa dan mengembalikan string asli.

Produksi ETH
sumber
6

Sekam , 7 byte

G§+oh↑↓

Mengambil string terlebih dahulu, lalu indeks (berbasis 1). Cobalah online!

Penjelasan

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.
Zgarb
sumber
Bagaimana cara menggunakan daftar indeks yang kosong x?
mil
@miles Anda harus menentukan jenisnya, seperti ini .
Zgarb
Begitu ya, terima kasih. Saya tidak terlalu akrab dengan Haskell atau Husk.
mil
6

Python 2 , 43 byte

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

Cobalah online!

Segala bentuk output baik-baik saja asalkan mudah dibaca.

Jadi ini dicetak sebagai daftar karakter.

Erik the Outgolfer
sumber
1
Bagus, tetapi mengapa Anda memilih penyalahgunaan notasi for i in i+[0]?
Tn. Xcoder
@ Mr.Xcoder Karena dengan cara itu baris terakhir ditampilkan. (dan alasan saya memposting secara terpisah di tempat pertama)
Erik the Outgolfer
Tidak, tidak +[0], yang saya bicarakan for i in i. for k in isetara .
Tn. Xcoder
@ Mr.Xcoder Karena saya suka seperti itu ...
Erik the Outgolfer
Ok, hanya ingin tahu ... Mungkin itu adalah tipuan yang tidak saya ketahui :)
Mr. Xcoder
5

Python 2 , 47 byte

Ini bisa disingkat menjadi 43 byte , seperti yang ditunjukkan oleh @LuisMendo, tapi itu sudah solusi dari @ ErktheOutgolfer.

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

Cobalah online!

Tuan Xcoder
sumber
`a`[2::5]sebagai gantinya''.join(a)
Rod
@Rod Bagaimana cara kerjanya?
Tn. Xcoder
reprdan pembelahan string, berfungsi baik untuk mengubah daftar karakter menjadi string, `a`[1::3]juga dapat digunakan dengan daftar digit
Rod
@Rod Saya tahu apa itu, saya tidak mengerti bagaimana cara ::5kerjanya di sini: P
Mr. Xcoder
@Mr. Xcoder, lalu pelajari irisan string;) pada dasarnya dibutuhkan setiap karakter ke-5 mulai dari tanggal 2
Erik the Outgolfer
4

Java 8, 78 byte

Ini adalah lambda kari, dari int[]ke konsumen StringBuilderatau StringBuffer. Output dicetak ke standar keluar.

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

Cobalah secara Online

Jakob
sumber
1
Jawaban kedua Anda adalah entri yang valid. Tidak ada yang melarang Anda memilih jenis input dengan hati-hati selama itu masuk akal. Saya sudah beberapa kali mengambil bahkan Streamsebagai masukan dan mendapat jawaban yang sangat bagus. Sebenarnya, hampir semua bahasa golf menggunakan stream yang setara secara internal. Jadi dengan memilih input Anda, Anda hanya level anak laki-laki. +1 tetap
Olivier Grégoire
Mungkin kau benar. Saya pikir saya cenderung lebih konservatif daripada kebanyakan hal-hal ini. Saya akan beralih ke solusi kedua.
Jakob
3

05AB1E , 11 byte

v=ā0m0yǝÏ},

Cobalah 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
Riley
sumber
Baris pertama tidak ada. Oh, dan tidak yakin apakah Anda bisa mencetak seperti itu.
Erik the Outgolfer
@EriktheOutgolferAny form of output is fine as long as it is easily readable
Riley
Saya dapat menyimpan beberapa byte kemudian ...
Erik the Outgolfer
3

Mathematica, 70 byte

(s=#;For[t=1,t<=Length@#2,Print@s;s=StringDrop[s,{#2[[t]]+1}];t++];s)&

Cobalah online!

J42161217
sumber
3

R , 46 32 byte

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

Cobalah online!

Mengambil input sebagai daftar karakter dan Xberbasis 1. Reduceadalah setara dengan R fold, fungsi dalam hal ini [adalah subset. Berulang-ulang -Xkarena pengindeksan negatif dalam R menghilangkan elemen, dan initdiatur ke S, dengan accum=TRUEdemikian kami mengakumulasikan hasil antara.

R , 80 byte

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!

Giuseppe
sumber
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.

AdmBorkBork
sumber
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

Python 2, 50 bytes

  • Takes in string and list of indices
s,i=input()
for j in i+[0]:print s;s=s[:j]+s[j+1:]

Try it online!

officialaimm
sumber
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.

Magic Octopus Urn
sumber
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.

Neil
sumber
2

Pyth, 8 bytes

.u.DNYEz

Demonstration

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

isaacg
sumber
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.

briantist
sumber
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"
streetster
sumber
2

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

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

Try it online!

aschepler
sumber
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)
Luis Mendo
sumber
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

Kamil Drakari
sumber
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

C (gcc), 99 bytes

j;f(s,a,i)char*s;int*a;{puts(s);for(j=0;j<i;j++){memmove(s+a[j],s+a[j]+1,strlen(s)-a[j]);puts(s);}}

Try it online!

Takes the string, array, and the length of the array.

betseg
sumber
91 bytes
ceilingcat
1

Pyth, 10 bytes

Rule changes saved me 1 byte:

V+E0Q .(QN

Try it online!

Pyth, 11 bytes

V+E0sQ .(QN

Try it online!

Mr. Xcoder
sumber
@miles isn't stderr output allowed by default?
Erik the Outgolfer
@Mr.Xcoder I thought stderr output was ignored in that case...
Erik the Outgolfer
@miles I will remove mine and flag it to a mod if we do not remove them. Thanks!
Mr. Xcoder
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
Business Cat
sumber
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
nmjcman101
sumber
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

Swift 3, 80 bytes

func f(l:[String],c:[Int]){var t=l;for i in c{print(t);t.remove(at:i)};print(t)}

Try it online!

Mr. Xcoder
sumber
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
KarlKastor
sumber
1

Python 2, 54

X,S=input()
for a in X:
    print S
    S=S[:a]+S[a+1:]
print S

Try It Online

Nathan Dimmer
sumber
I only see the last string in the output.
miles
I messed up... One moment...
Nathan Dimmer
1

APL, 31 30 28 bytes

{⎕←⍺⋄⍵≡⍬:⍬⋄⍺[(⍳⍴⍺)~⊃⍵]∇1↓⍵}

Try it online!

Zacharý
sumber
1

C# (Mono), 85 bytes

s=>a=>{for(int i=-2;++i<a.Count;)System.Console.WriteLine(s=i<0?s:s.Remove(a[i],1));}

Try it online!

TheLethalCoder
sumber