Supprimer le caractère à l'index spécifié

33

(fortement inspiré par Element of string à l'index spécifié )

Avec une chaîne set un entier nreprésentant un index s, sortie savec le caractère à la n-th position supprimée.

L'indexation 0 et l'indexation 1 sont autorisées.

  • Pour l'indexation 0, nsera non négatif et inférieur à la longueur de s.
  • Pour 1-indexation, nsera positif et inférieur ou égal à la longueur de s.

sconsistera uniquement en caractères ASCII imprimables ( \x20-\x7E, ou  par le biais ~).

Toute entrée / sortie raisonnable est autorisée. Les failles standard s'appliquent.

Cas de test (indexé 0):

n s        output
0 "abcde"  "bcde"
1 "abcde"  "acde"
2 "a != b" "a = b"
3 "+-*/"   "+-*"
4 "1234.5" "12345"
3 "314151" "31451"

Cas de test (index 1):

n s        output
1 "abcde"  "bcde"
2 "abcde"  "acde"
3 "a != b" "a = b"
4 "+-*/"   "+-*"
5 "1234.5" "12345"
4 "314151" "31451"

C'est du , donc la réponse la plus courte en octets est gagnante.

ETHproductions
la source
9
Personne d'autre ne répond, C # gagne ... trop tard :(
TheLethalCoder
Pouvons-nous supposer que le caractère à cet idx n'apparaît qu'une seule fois?
programmer5000
1
@ programmer5000 Dernier test 3, 314151-> 31451. Je suppose que non.
TheLethalCoder
@ programmer5000 N ° Voir le dernier cas de test.
ETHproductions
2
Peut-être qu'un classement serait utile, il y a déjà beaucoup de réponses à chercher.
M. Xcoder

Réponses:

23

C #, 20 19 octets

s=>n=>s.Remove(n,1)
TheLethalCoder
la source
13

Alice , 13 12 octets

Merci à Leo pour avoir sauvegardé 1 octet.

/oI\!e]&
@ q

Essayez-le en ligne!

La première ligne de l'entrée est la chaîne, la deuxième ligne est l'index basé sur 0.

Explication

/    Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces
     diagonally up and down through the code.
I    Read the first line of input (the string).
!    Store the string on the tape, which writes the characters' code points to 
     consecutive cells (the tape is initialised to all -1s).
]    Move the tape head right. This moves it by an entire string, i.e. to the
     cell after the -1 that terminates the current string.
     The IP bounces off the bottom right corner and turns around.
]    Move the tape head right by another cell.
!    Store an implicit empty string on the tape, does nothing. It's actually
     important that we moved the tape head before this, because otherwise it
     would override the first input code point with a -1.
I    Read the second line of input (the index) as a string.
/    Reflect to W. Switch to Cardinal.
     The IP wraps around to the last column.
&]   Implicitly convert the first input to the integer value it contains
     (the index) and move the tape head that many cells to the right, i.e.
     onto the character we want to delete. Note that Ordinal and Cardinal mode
     have two independent tape heads on the same tape, so the Cardinal tape
     head is still on the first cell of the string input before we do this.
e!   Store a -1 in the cell we want to delete.
\    Reflect to SW. Switch to Ordinal.
q    Push the entire tape contents as a single string. This basically takes
     all cells which hold valid code points from left to right on the tape 
     and concatenates the corresponding characters into a single string. Since
     we wrote a -1 (which is not a valid code point) over the target character,
     this will simply push the entire input string without that character.
o    Output the result.
@    Terminate the program.
Martin Ender
la source
10

K (Kona), 1 octet

_

Je dois aimer construit. Indexation basée sur 0. Usage:

k)"abcdef" _ 3
"abcef"
Simon Major
la source
Donner un tout nouveau sens à «utiliser le bon outil pour le travail».
MD XF
1
Ha - vous voulez voir le bon outil pour le travail? codegolf.stackexchange.com/a/121700/49493
Simon Major
J'ai découvert un moyen de faire cela avec un programme encore plus court. Malheureusement, il n'y a pas assez de place dans cette boîte de commentaire pour expliquer ;-)
Mawg
8

Haskell , 28 à 24 octets

-4 octets grâce à Laikoni, cette version est indexée 1.

s#n=take(n-1)s++drop n s

Ancienne réponse:

f(s:t)0=t;f(s:t)n=s:f t(n-1)

Une fonction récursive simple qui prend la valeur, elle est indexée à 0.

Ma première fois, je jouais au code, alors ce n’est peut-être pas la solution optimale. Tant pis.

Sgt. Se terrer
la source
2
Bienvenue chez PPCG!
Martin Ender
1
Vous pourriez aussi être intéressé par la collection de conseils pour jouer au golf à Haskell .
Laikoni
7

Mathematica, 18 octets

1 indexé

#2~StringDrop~{#}&

contribution

[1, "abcde"]

merci Martin Ender

J42161217
la source
4
À mon avis, "Toute entrée / sortie raisonnable est autorisée" permet de prendre l’entrée comme si ["abcde", {1}], dans ce cas, StringDropseul fait l'affaire. Qu'est-ce que tu penses? (Vous voudrez peut-être mentionner explicitement qu'il est également indexé sur 1.) Je suis toujours heureux de voir des personnes publier des réponses Mathematica :)
Greg Martin
5

CJam, 4 bytes

q~Lt

Try it online!

Explanation

q~    e# Read and eval input (push the string and number to the stack).
  Lt  e# Set the nth element of the string to the empty string.
Business Cat
la source
5

GCC c function, 25

1-based indexing.

f(n,s){strcpy(s-1,s+=n);}

Plenty of undefined behavior here so watch out for stray velociraptors:

  • The strcpy() man page says If copying takes place between objects that overlap, the behavior is undefined. Here there clearly is overlap of the src and dest strings, but it seems to work, so either glibc is more careful or I got lucky.
  • The answer is reliant on the fact that the s+=n happens before the s-1. The standard gives no such guarantees, and in fact calls this out as undefined behaviour. Again, it seems to work as required with the gcc compiler on x86_64 Linux.

Try it online.

Digital Trauma
la source
2
In a stack-based ABI, such as x86, strcpy's arguments need to be pushed in right-to-left order, which would explain the behaviour, but you said you were using x86_64 which uses registers... maybe the compiler decided to golf the generated code and decided that computing s+=n first was golfier!
Neil
5
I love it when C answers go "this has no official reason to work, but it does anyway, so... eh."
Quentin
Holy crap. This blows mine out of the water. Very impressive!
MD XF
1
@Quentin That's one of the fun things about code-golf - you are allowed - encouraged even - to write the most awful, unsafe code that would normally be a firing offence ;-)
Digital Trauma
I'd love to know the reason for the downvote...
Digital Trauma
4

MATL, 3 bytes

&)&

Uses 1-based indexing.

Try it online! Or verify all test cases.

Explanation

&    % Specify secondary default number of inputs/outputs for next function
)    % Implicitly input string and number. Index: with & it pushes the char
     % defined by the index and the rest of the string
&    % Specify secondary default number of inputs/outputs for next function
     % Implicitly display (XD): with & it only displays the top of the stack

In the modified version with all the test cases, the code is within an infinite loop `...T until no input is found. At the end of each iteration the display function (XD) is explicitly called, and the stack is cleared (x) to ready it for the next iteration.

Luis Mendo
la source
I like the idea of generic command modifiers, they might be useful in other golfing languages.
ETHproductions
2
@ETHproductions If you need a name, I call them meta-functions, as they modify functions
Luis Mendo
@LuisMendo I think the formal name would be operators, a la mathematical operators (aka higher-order functions).
Mego
4

Vim, 7 bytes

jDk@"|x

How it works:

It expects two lines; one with the string and one with the number.

  1. Go to line two, copy the number into register
  2. Go to first line and then go to column in the register with @"|
  3. Delete the character under the cursor
jmriego
la source
Another fun solution that's almost identical is jD@"gox
DJMcMayhem
Flagging -> Closing -> Duplicate of codegolf.stackexchange.com/a/121581/61563 :P kidding, but they are remarkably similar.
MD XF
they are! Is there any prize for getting down to 7 characters first? :-P
jmriego
4

Java 8, 39 bytes

s->n->s.substring(0,n)+s.substring(n+1)

Try it here.

Java 7, 67 bytes

String c(int n,String s){return s.substring(0,n)+s.substring(n+1);}

Try it here.

Kevin Cruijssen
la source
Assuming it works, a "built in" for 46 bytes s->n->new StringBuilder(s).deleteCharAt(n)+""; though it is longer.
TheLethalCoder
@TheLethalCoder It indeed works. But it's indeed a bit longer. Oh, and always use StringBuffer instead of StringBuilder in codegolf. ;)
Kevin Cruijssen
Ah nice trick on the buffer I used it in my answer :)
TheLethalCoder
4

Haskell, 15 bytes

This requires the recently released GHC 8.4.1 (or higher). Now <>, as a function on Semigroups, is in Prelude. It is particularly useful on the function Semigroup

take<>drop.succ

Try it online!
Since tio is using an older bersion of GHC, I've imported <> in the header.

H.PWiz
la source
4

R, 40 bytes

Just goes to show the variety of ways, none of which particularly compact, you can fiddle with strings in R.

function(s,n)intToUtf8(utf8ToInt(s)[-n])
J.Doe
la source
3

05AB1E, 5 bytes

ā²ÊÏJ

Try it online!

ā     # push range(1, len(input string) + 1)
 ²Ê   # Check each for != to input index
   Ï  # Keep characters from input where this array is 1
    J # Join
Riley
la source
3

05AB1E, 6 bytes

vNÊiy?

Try it online!

Explanation

v       # for each element, index (y,N) in input1
 NÊi    # if N is not equal to input2
    y?  # print y
Emigna
la source
3

Pyth, 3 bytes

.DE

Try it here.

Takes index first.

Erik the Outgolfer
la source
3

JS (ES6), 41 32 31 bytes

y=>i=>y.slice(0,i++)+y.slice(i)

Based on this. Takes input through currying, first is string, second is index.

-9 thanks to @JohanKarlsson

-1 thanks to @ETHproductions

programmer5000
la source
3

Jelly, 3 bytes

Ṭœp

A full program taking the (1-based) index and the string (in that order) and printing the result.

As a dyadic function it returns a list of the two parts.

In fact the index may be a list of n indices, in which case it returns a list of the n-1 parts.

Try it online!, or see a test suite.

How?

Ṭœp - Main link: number i, string s                   e.g. "fish 'n chips", 6
Ṭ   - untruth - get a list with 1s at the indexes of i      000001 <-- i.e. [0,0,0,0,0,1]
 œp - partition s at truthy indexes without borders       ["fish ","n chips"]
    - implicit print                                        fish n chips

As an example of using multiple indexes:

      "fish and chips", [6,8]
Ṭ      00000101 <- i.e. [0,0,0,0,0,1,0,1]
 œp  ["fish ","n"," chips"] 
       fish n chips
Jonathan Allan
la source
3

vim, 10 7

DgJ@"|x

Takes 1-indexed input in the following format:

2
abcde
D      delete the number on the first line into register "
gJ     remove the newline while preserving whitespace on line 2
@"     run the " register as a macro - input is used as a count for...
|      the "go to nth column" command
x      delete the character at the cursor

Thanks to @DJMcMayhem for 3 bytes!

Doorknob
la source
3

Java 8, 45 41 bytes

s->n->new StringBuffer(s).deleteCharAt(n)

Saved 4 bytes thanks to @OlivierGrégoire

My first code golf answer in something other than C#, even if it isn't the shortest for Java yet.

TheLethalCoder
la source
1
1. You don't need the final ; in lambda (-1 bytes). 2. In my eyes, you don't need to return a String. I think that returning the StringBuffer without the +""would be perfectly valid (-3 bytes). Example? BigInteger is a representation of an unbounded int, in this case StringBuffer/StringBuilder are representations of mutable Strings.
Olivier Grégoire
@OlivierGrégoire Thanks :) I've never actually used Java before so all improvements are welcome
TheLethalCoder
2

Python 3, 24 bytes

lambda n,a:a[:n]+a[n+1:]

Try it online!

Leaky Nun
la source
Dam you beat me to it!
Notts90
1
I think, that this is valid for python 2 too
Dead Possum
2

JavaScript (ES6), 39 34 33 bytes

n=>s=>s.replace(/./g,c=>n--?c:"")
  • 5 6 bytes saved thanks to Arnauld.
Shaggy
la source
2

brainfuck, 14 bytes

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

Try it online!

Reads zero-based one-byte index immediately followed by the string.

eush77
la source
Aw, you beat me to it :/ I had the exact same solution. +1
daniero
2

Befunge-98, 35 27 25 bytes

-4 bytes thanks to @eush77

&#;1-:!#v_~,;
_@#:~;#~<;,

Try it online!

1-indexed, note that the input has a trailing null-byte.

ovs
la source
2

PHP, 41 bytes, 35 bytes excluding ?php

<?php $argv[1][$argv[2]]='';echo$argv[1];

0-indexed

TIO

M.E
la source
I'm actually really surprised this works; is the [$argv[2]] index implicitly creating a range? Also, IIRC you can leave the <?php off, because the PHP interpreter has a mode which doesn't need it, and because we don't normally penalise for that sort of indication in a file of what the language is.
@ais523 Basically yes. From docs: "Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose." php.net/manual/en/language.types.string.php
M.E
2

R, 48 47 bytes

(1 byte saved through use of el() thanks to Giuseppe)

function(s,n)cat(el(strsplit(s,""))[-n],sep="")

Split the string into its individual characters, remove the nth and then concatenate again.

There may well be a better solution, strsplit() is quite unwieldy as it returns a list.

user2390246
la source
won't work on TIO: pryr::f([function body]) saves a few bytes and using el(strsplit(s,"")) saves a byte but also doesn't work on TIO for some reason.
Giuseppe
@Giuseppe Thanks! I would feel a bit dirty making use of pryr::f since surely it should be preceded by install.packages("pryr") but maybe that's me being too precious!
user2390246
function(s,n)intToUtf8(utf8ToInt(s)[-n]) for 40 bytes.
J.Doe
@J.Doe good spot! That's a very different approach so you should post it as your own answer.
user2390246
Another sub-47 is function(s,n)sub(sub(0,n,"(.{0})."),"\\1",s) for 44.
J.Doe