消失的元素


17

给定一个字符串S和一个索引列表XS通过删除每个索引处的元素来进行修改,并将S结果作为的新值S

例如,给定S = 'codegolf'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

您的任务是执行此过程,收集S每个操作后的值,并按顺序在换行符上显示每个值。最终的答案是

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

Answer:

codegolf
cdegolf
cdeglf
cdegf
degf
def
  • 这是因此请使代码尽可能短。
  • 您可以假定中的值X始终是的有效索引S,并且可以使用基于0或基于1的索引。
  • 该字符串将仅包含 [A-Za-z0-9]
  • 无论是Sx可能空。如果S为空,则也x必须为空。
  • 您也可以将S字符列表而不是字符串作为列表。
  • 您可以打印输出或返回字符串列表。开头和结尾的空格是可以接受的。只要易于阅读,任何形式的输出都可以。

测试用例

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 

我们可以将其S作为字符列表吗?
Xcoder先生17年

@ Mr.Xcoder当然,我会在规范中添加它。
英里

我们可以打印为字符列表吗?
暴民埃里克(Erik the Outgolfer)'17年

我们可以跳过输出中的第一项(原始字符串)吗?
ETHproductions

@ETHproductions否,输出应该首先是原始字符串,然后是删除字符产生的每个字符串。因此,输出应包含len(x)+1字符串。
英里

Answers:


8

Haskell,38 33字节

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

直截了当:反复获取索引i之前和之后的元素,将它们重新加入并收集结果。

在线尝试!

编辑:@Lynn保存5个字节。谢谢!


s#i=take i s++drop(i+1)s实际上更短,节省了5个字节。
林恩

1
不,您现在33岁了-别忘了TIO片段q=在那里^^;
林恩

是的,你是对的。
nimi

8

JavaScript(ES6),57 50 48 45 42字节

将字符串作为单个字符的数组,输出一个包含原始逗号分隔字符串的数组,然后是每个步骤的逗号分隔字符串的子数组。

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]
  • 多亏了Arnauld 建议我节省了3个字节,这比我已经滥用了宽松的输出规范,这导致我为节省另外3个字节而更加滥用它。

测试一下

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>


说明

我们以递归语法通过参数s(字符串数组)和a(整数数组)获取两个输入,这意味着我们用调用函数f(s)(a)

我们建立一个新的数组,并从原始数组开始 s。但是,splice稍后我们将使用的方法修改数组时,我们需要为其复制一个副本,方法是将其转换为字符串(只需附加一个空字符串)即可。

为了生成子map数组,我们对整数数组a(其中x是当前整数)进行遍历,对于每个元素,我们splicesindex开始,从1个元素开始x。我们返回经过修改的s,再次通过将其转换为字符串来制作其副本。


因为只要易于理解,任何形式的输出都可以,所以我认为也应该可以接受:s=>a=>[s+'',...a.map(x=>s.splice(x,1)&&s+'')]
Arnauld

不错,@ Arnuald-即使考虑到这种规格,我也不会考虑将其推到那么远。
毛茸茸的

6

Japt,6个字节

åjV uV

在线测试!

说明

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.

或者:

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.

之所以有效,是因为删除索引处的项目"不会执行任何操作,因此会返回原始字符串。


6

外壳,7个字节

G§+oh↑↓

首先获取字符串,然后获取(从1开始)索引。 在线尝试!

说明

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.

如何使用空索引列表x
英里

@miles您必须指定类型,例如
Zgarb

我明白了,谢谢。我对Haskell或Husk不太熟悉。
英里

6

Python 2,43个字节

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

在线尝试!

只要易于阅读,任何形式的输出都可以。

因此,这将打印为字符列表。


1
很好,但是您为什么选择符号滥用for i in i+[0]
Xcoder先生17年

@ Mr.Xcoder因为那样,显示了最后一行。(以及我分开发表在第一位的原因)
Egg the Outgolfer '17

不,不是+[0],我在说for i in ifor k in i等价的
Xcoder先生17年

@ Mr.Xcoder因为我喜欢那件事...
Egg the Outgolfer '17

好吧,只是好奇...也许这是我不知道的把戏:)
Xcoder先生17年

5

Python 2 2,47个字节

正如@LuisMendo指出的那样,它可以缩短为43个字节,但这已经是@ErktheOutgolfer的解决方案。

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

在线尝试!


`a`[2::5]而是''.join(a)
罗德

@Rod比工作如何?
Xcoder先生17年

repr和字符串拆分,可以很好地将字符列表转换为字符串,`a`[1::3]也可以与数字
Rod

@Rod我知道它们是什么,我不明白::5这里的工作原理:P
Xcoder先生17年

@ Mr.Xcoder好,然后研究字符串切片;)从第二个开始,基本上每5个字符都需要
外面的家伙埃里克(Erik the Outgolfer)

4

Java 8,78字节

这是一个令行禁止的λ,从int[]给消费者StringBuilderStringBuffer。输出被打印到标准输出。

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

在线试用


1
您的第二个答案是有效的输入。只要有道理,所有内容都不能禁止您仔细选择输入类型。我已经有几次甚至把Streams作为输入,并且得到了很好的答案。实际上,几乎所有高尔夫语言在内部都使用等效的流。因此,通过选择您的输入,您就可以调整一点。尽管如此,还是+1
奥利维尔·格雷戈尔(OlivierGrégoire)

或许你是对的。我认为我在这些方面比大多数人都更为保守。我将切换到第二种解决方案。
雅各布

3

05AB1E,11个字节

v=ā0m0yǝÏ},

在线尝试!

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

第一行不存在。哦,不确定是否可以那样打印。
暴民埃里克(Erik the Outgolfer)'17年

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

然后我可以保存一些字节...
Erik the Outgolfer '17


3

R46 32字节

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

在线尝试!

将输入作为字符列表,并且X从1开始。Reduce是R的等价物fold,在这种情况下,函数[是子集。重复进行,-X因为R中的负索引删除了元素,并将init其设置为Saccum=TRUE因此我们累积了中间结果。

R,80个字节

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



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.