Swap, delete and repeat

Introduction

Let's observe the following string:

ABCDEFGHIJKLMNOP

If we swap the ends of the string, which are these:

ABCDEFGHIJKLMNOP
^^            ^^

We get the following result:

BACDEFGHIJKLMNPO

After that, we delete the ends of the string, which in this case are B and O. The result is:

ACDEFGHIJKLMNP

If we repeat the process, we get the following list:

N     Result

3     AEFGHIJKLP
4     AFGHIJKP
5     AGHIJP
6     AHIP
7     AP

You can see that for N = 5, the result is AGHIJP. At N = 7, the length of the string is smaller than 3, so N > 7 is considered invalid in this case.

Given a string S with at least length 4 and the number of repetitions N > 0, output the final result. You can assume that N is always valid.

Test cases

Input                               >  Output

N = 3, S = ABCDEFGHIJKLMNOP         >  AEFGHIJKLP
N = 1, S = Hello                    >  Hlo
N = 2, S = 123321                   >  11

This is , so the submission with the least amount of bytes wins! For the simplicity, you can assume that the string will only contain alphanumeric characters.

• Question: Is it okay to take N in unary with something like ' as the counting character? For example: ''123321? Commented Feb 19, 2016 at 13:24
• @daavko Yes, unary is acceptable by default Commented Feb 19, 2016 at 13:39
• @Adnan Unary format can be used for N, but can it be a string, with quotes? I mean, for N=3 take '111' (as opposed to 111) Commented Feb 19, 2016 at 15:21
• @LuisMendo Yes, you may use that Commented Feb 19, 2016 at 15:23
• It looks to me like we skip 1 and remove N - is this allowed as an answer or does the code need to swap delete and repeat? Commented Feb 22, 2016 at 13:14

Retina, 44 20 bytes

Crossed out 44 is still regular 44 :(

+'(\w).(.*).\B
$1$2

Assumes input in following format (in unary - counting character: '):
{number of repeats}{string}
For example: '''''''ABCDEFGHIJKLMNOP
There is no space between number of repeats and the string.

Thanks @MartinBüttner for shaving off 24 bytes!

Try it online!

• Commented Feb 19, 2016 at 13:56
• @MartinBüttner Aha! So this was your psychological masterplan :p Commented Feb 19, 2016 at 14:05
• @Adnan ¯\_(ツ)_/¯ Commented Feb 19, 2016 at 14:07
• Crossed out 44 looks like crossed out 11... Commented Feb 19, 2016 at 19:52

Python 2, 31 bytes

lambda s,n:s[0]+s[n+1:~n]+s[-1]

I think this works?

• It's also valid python 3. Commented Feb 20, 2016 at 15:30

Labyrinth, 40 bytes

<
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

Input is N followed by the string, separated by any non-numeric character.

Try it online!

This was written in collaboration with Sp3000 (which means I couldn't be bothered to figure out an algorithm, so he started working on it, came up with 118 byte solution but couldn't be bothered golfing it, so I did the golfing... yay for teamwork).

Explanation

Sp's usual primer (as usual slightly modified):

• Labyrinth is a stack-based 2D language with two stacks, main and auxiliary. Pretty much everything happens on the main stack, but you can shift values over to the other one, e.g. to reverse them or save them for later.
• The stacks are bottomless and filled with zeroes, so popping from an empty stack is not an error.
• Execution starts from the first valid character (here the top left). At each junction, where there are two or more possible paths for the instruction pointer (IP) to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right. While this was meant to make the code look like winding, twisty passages, there's nothing stopping you from making "rooms" where these conditions are checked in every cell. Those can yield quite unpredictable behaviour, but are great for golfing.
• The source code (and therefore the layout of the labyrinth) can be modified at runtime using <>^v which cyclically shifts a row or column or the grid.
• " are no-ops.

Here we go.

The code starts on the <, which is a golfing trick I've used a few times when starting with a long piece of linear code. It shifts the first row cyclically to the left, with the IP on it, so the source then looks like this:

<
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

But now the IP can't move anywhere, so it executes the < again. This continues until we reach this state:

<
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

At this point, the IP can leave the cell and begin executing the second line starting from the ?. So here's the linear code broken down:

?   # Read the first integer on STDIN, i.e. N.
:}  # Duplicate it and move one copy over to the auxiliary stack.
,   # Read the separator character.
,.  # Read the first character of the input string and directly print it.

The IP now enters this 3x2 room, which is actually two tightly-compressed (overlapping) 2x2 clockwise loops. The first loop reads and discards N-1 characters from STDIN.

;   # Discard the top of the stack. On the first iteration, this is the
# separator we've already read. On subsequent iterations this will be
# one of the N-1 characters from the input string.
(   # Decrement N. If this hits zero, we leave the loop, otherwise we continue.
,   # Read the next character from STDIN to be discarded.

Now we enter the second loop which reads the remainder of the input string. We can detect EOF because , will return -1 in that case, making the IP turn left.

,   # Read a character. Exit the loop if EOF.
(   # Decrement it.

That decrement isn't actually useful, but we can undo it later for free and here it allows us to overlap the two loops.

If we take the 5 ABCDEFGHIJKLMNOP input as an example, the stack looks like this:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' -1  |  5 ... ] Auxiliary

Note that these actually correspond to the input characters FGHIJKLMNOP (because we decremented them), and that we don't actually want to print the first of those (we've only discarded N-1 characters, but want to skip N).

Now there's a short linear bit that prepares the stack for the next loop:

;   # Discard the -1.
=   # Swap the tops of the stacks, i.e. N with the last character.
# By putting the last character on the auxiliary stack, we ensure that
# it doesn't get discarded in the next loop.
}   # Move N over to the auxiliary stack as well.

The stacks now look like:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N'  |  5 'O' ... ] Auxiliary

We enter another 2x2 clockwise loop. This discards the top N characters from the main stack:

;   # Discard the top of the main stack.
{   # Pull N over from the auxiliary stack.
(   # Decrement it. It it's 0 we leave the loop.
}   # Push N back to the auxiliary stack.

When we exit the loop = swaps that 0 and the last character of the input string again. Now the stacks look like this:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'O'  |  ... ] Auxiliary

We want to print the contents of the main stack (except the bottom element and all incremented by 1), from the left. That means we need to get it over to the auxiliary stack. That's what the next 2x2 (clockwise) loop does:

{   # Pull an element over from the auxiliary stack. This is necessary so we
# have a 0 on top of the stack when entering the loop, to prevent the IP
# from turning right immediately.
}   # Move the top of the main stack back to the auxiliary stack. If this was the
# bottom of the stack, exit the loop.
)   # Increment the current character.
}   # Move it over to the auxiliary stack.

Stacks now:

Main [ ...  |  'F' 'G' 'H' 'I' 'J' 'P] ... ] Auxiliary

We move the first of those (the one we don't want to print) back to the main stack with {. And now we enter final 2x2 (counterclockwise) loop, which prints the rest:

{   # Pull another character over from the auxiliary stack. Exit the loop
# if that's the zero at the bottom of the stack.
.   # Print the character.

Finally we terminate the program with @.

Mathematica, 29 bytes

#~Delete~{{2},{-2}}&~Nest~##&

The crux of bracketless Mathematica! Function inputs are a list (of characters, or whatever) and a number.

• Welcome to PPCG! :D Nice first answer. Commented Feb 19, 2016 at 16:47

JavaScript (ES6), 39 bytes

(s,n)=>s[0]+s.slice(++n,-n)+s.slice(-1)

Turns out I just reinvented @Sp3000's answer.

Jelly, 8 bytes

Ḣ1¦UðḤ}¡

Try it online!

How it works

Ḣ1¦UðḤ}¡  Main link. Left input: S (string). Right input: N (deletions)

Ḣ         Pop the first element of S.
This return the element and modifies S.
1¦       Apply the result to the first index.
This replaces the first character of the popped S with the popped char.
U      Upend/reverse the resulting string.
ð     Convert the preceding chain into a (dyadic) link.
Ḥ}   Apply double to the right input.
This yields 2N.
¡  Repeat the link 2N times.

MATL, 8 91213 bytes

th"P[]2(

Inputs are: first N as a unary string with quotes (allowed by the challenge); second S as a string with quotes (quotes in strings are allowed by default); separated by a linebreak.

This works by flipping the string, removing its second element, and repeating for a total of 2*N times.

Try it online!

th       % implicitly take first input (N) as a unary string. Concatenate horizontally
% with itself: gives a string of 2*N ones
"        % for each (i.e., repeat 2*N times)
P      %   flip string. Take S implicitly as input the first time
[]     %   empty array (used as new contents)
2      %   2 (used as index)
(      %   assign [] to position 2 of string; that is, remove second element
% implicitly end for each
% implicitly display
• Explanation? :P Commented Feb 19, 2016 at 14:03
• @VoteToClose Sure :-) I had to run. I've just added it Commented Feb 19, 2016 at 15:06

Ḣ;ṪjḊṖ$Ɠ¡F Input the number via STDIN, and the string via command line args. Thanks to @Dennis for a lot of hints/help getting this to work (Jelly still eludes me). Try it online! Ḣ;Ṫ Pop first and last chars of string and concatenate j Join by... Ɠ¡ Execute n times... ḊṖ$               Drop first, drop last of string ($combines the two monadically) F Flatten to filter out empty lists, since Jelly's j is weird • Honest question, how do the 10 bytes work? Isn't this in UTF-8 (and shouldn't it be at least 16 bytes because ḢṪḊṖƓ¡ are all using more than 1 byte) or do you use some kind of character code table for readability? Commented Feb 19, 2016 at 15:11 • @AutomatedChaos The latter :) (click on the link where the word "bytes" is in the header). Jelly uses a custom code page, akin to languages like APL. Commented Feb 19, 2016 at 15:13 Pyth, 13 bytes ++hz:zhQ_hQez Explanation: - autoassign z = input() - autoassign Q = eval(input()) :zhQ_hQ - z[Q+1:-(Q+1)] ++hz ez - z[0]+^+z[-1] Try it here Ruby, 29 bytes ->s,n{s[0]+s[n+1...~n]+s[-1]} Very straightforward. ~ trick stolen from Sp's answer, which saves a byte over s[n+1..-2-n]. (It works because ~n is -1-n in two's-complement, and then ... is an exclusive range.) Vitsy, 12 9 (code) + 1 (newline for function declaration) = 10 bytes \o/ Expects input on the stack as the string followed by the number. 2*\[vXvr] 2* Multiply by 2. \[ ] Do the stuff in the brackets that many times. (input num * 2) v Take the top item off the stack and save it as a local variable. X Remove the top item of the stack. v Push the temporary variable back onto the stack. r Reverse the stack. Which you can call with: 'String' r <number> 1m Z 2*\[vXvr] This is a function that leaves the resultant string on the stack. I have provided it as a program in the TryItOnline link. TryItOnline! • @Adnan Fixed - that places me in close proximity to Pyth. D: Commented Feb 19, 2016 at 13:13 • But still one byte ahead :D Commented Feb 19, 2016 at 13:14 • @Adnan Could I get away with saying that it expects items on the stack rather than input? Or is that a no-no? Commented Feb 19, 2016 at 13:14 • I'm not sure what the policy is for that, but if you can find a meta post about items already on the stack, it's fine :) Commented Feb 19, 2016 at 13:18 • @Adnan There's a meta post about items already being on the tape for languages like brainfuck. I'll ask about it in meta (because that's actually super important for Vitsy. :D) Commented Feb 19, 2016 at 13:19 Perl, 36 32 + 1 = 33 bytes for$i(1..<>){s;\B.(.+).(.);$1$2;}

Requires -p flag and takes input on two lines, with numbers of iterations at the end:

$perl -pe'for$i(1..<>){s;\B.(.+).(.);$1$2;}' <<< $'ABCDEFGHIJKLMNOP\n4' AFGHIJKP Ungolfed? for$i ( 1..<> ) {
s;
\B.(.+).(.);$1$2;x
}

Python 2, 49 48 bytes

g=lambda s,n:n and g(s[0]+s[2:-2]+s[-1],n-1)or s

Try it here with testcases!

Simple recursive solution. Removes the second and last second element from the input string and calls itself with this and n-1 until n=0.

edit: Feeling kinda stupid, looking at the other python solution. Guess I just like recursion too much...

C, 96 bytes

i;main(c,v,p)char**v,*p;{i=atoi(v[2])+1;c=strlen(p=v[1]);printf("%c%.*s%s",*p,c-2*i,p+i,p+c-1);}

Ungolfed

i; /* Param 2, the number of chars to remove */

main(c,v,p)char**v,*p;
{
i=atoi(v[2])+1; /* convert param 2 to integer */
c=strlen(p=v[1]); /* Length of the input */
printf("%c%.*s%s",*p, /* Print the first char... */
c-2*i, /* a number of characters equal to the length minus twice the input... */
p+i, /* skip the "removed" chars... */
p+c-1); /* Print the last character of the string */
}

Rust, 135 bytes

Well, that's a pretty terrible length.

fn f(s:&str,n:usize)->String{let s=s.as_bytes();s[..1].iter().chain(&s[n+1..s.len()-n-1]).chain(s.last()).map(|d|*d as char).collect()}

Pretty-printed:

fn f(s: &str, n: usize) -> String {
let s = s.as_bytes();
s[..1].iter()
.chain(&s[n+1..s.len()-n-1])
.chain(s.last())
.map(|d| *d as char)
.collect()
}

You can get it down to 104 bytes if we allow bytestrings instead of proper strings.

fn f(s:&[u8],n:usize)->Vec<u8>{let mut r=vec![s[0]];r.extend(&s[n+1..s.len()-n-1]);r.extend(s.last());r}

Pretty-printed:

fn f(s: &[u8], n: usize) -> Vec<u8> {
let mut r = vec![s[0]];
r.extend(&s[n+1..s.len()-n-1]);
r.extend(s.last());
r
}

Curious if anyone can do better.

CJam, 12 bytes

q~{VW@)t(t}*

Try it online!

How it works

q~            Read and evaluate all input. This pushes S (string) and N (integer).
{       }*  Do the following N times:
VW           Push 0 and -1.
@          Rotate S on top of them.
)         Pop the last character of S.
t        Set the item at index -1 to that character.
(       Pop the first character of S.
t      Set the item at index 0 to that character.

Octave, 28 bytes

@(S,N)S([1,N+2:end-N-1,end])

Index the string, omitting S(2:N+1) and S(end-N:end-1).

Sample run on ideone.

Vim, 27 bytes

o0lxehx <ESC>"ay0ddA@a<ESC>B"bdWx@b

Input is expected to be in the form STRING N on the first line with no other characters.

Explanation:

#Write a macro to do one round of the swap and delete and save to register a
o0lxehx <ESC>"ay0dd

#Append register a to N and save in register B so it will run @a N times.
A@a<ESC>B"bdWx

# Actually run the macro
@b

mSL - 137 bytes

c {
%l = $len($1)

VyxalṪ, 8 bytes

f÷?d($_^ Try it online! Explanation: f # Get the list of characters ÷ # and push each one to the stack. d # Double ? # the input ( # times:$    #   swap the top two items
_   #   pop the stack
^  #   then reverse the stack.
# Sum the whole stack and print

Factor, 47 bytes

[ 1 cut pick tail 1 cut* swap roll head* glue ]

Try it online!

! 5 "ABCDEFGHIJKLMNOP"
1      ! 5 "ABCDEFGHIJKLMNOP" 1
cut    ! 5 "A" "BCDEFGHIJKLMNOP"
pick   ! 5 "A" "BCDEFGHIJKLMNOP" 5
tail   ! 5 "A" "GHIJKLMNOP"
1      ! 5 "A" "GHIJKLMNOP" 1
cut*   ! 5 "A" "GHIJKLMNO" "P"
swap   ! 5 "A" "P" "GHIJKLMNO"
roll   ! "A" "P" "GHIJKLMNO" 5
head*  ! "A" "P" "GHIJ"
glue   ! "AGHIJP"

PHP, 60 bytes

This solution iteratively sets characters from the input string to an empty string by index. I'm manipulating the input string directly to prevent a long return.

function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";};

Basically in memory $w looks like this when done: Addr 0 1 2 3 4 H l o ^ ^ ^ >Result: Hlo Run like this: php -r '$f = function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";}; $f($argv[1],$argv[2]);echo"$argv[1]\n";' Hello 1
• PHP 4.1 (50 bytes): <?for(;$I;)$W[$I--]=$W[strlen($W)-$I-2]="";echo\$W;. It expects the values on the keys W and I, over POST/GET/COOKIE... An example would be http://example.com/a.php?W=MyString&I=5 Commented Feb 19, 2016 at 19:49
• Yeah, I don't wanna do answers which require register globals anymore. Thx for the suggestion though :) Commented Feb 19, 2016 at 23:57

Pylons, 16 Bytes.

i:At,{\,v\,v,A}c

How it works:

i    # Get command line input.
:At  # Set A equal to the top of the stack.
,    # Pop the stack.
{    # Start a for loop.
\   # Swap the top two elements of the stack.
,  # Pop the stack.
v # Reverse the stack.
\   # Swap the top two elements of the stack.
,  # Pop the stack.
v # Reverse the stack.
,   # Switch to loop iterations.
A   # Iterate A times.
}    # End the for loop.
c    # Print the stack as a string

CJam, 15 bytes

r(\)\{(;);}ri*\

I'm sure it's possible to golf this further...

Jolf, 13 bytes

ΆFi liγhj_γgi

A tranpilation of the JavaScript answer.

Explanation:

ΆFi liγhj_γgi
Fi            i[0],
li         i sliced
γhj       γ = j + 1
_γ     to -γ
gi  and the last of i

Try it here!

A more interesting post-question version:

ΆFi]ihjYgi

Seriously, 17 bytes

,#,p@pXod@dXqnΣ

Takes input as s \n n.

Try it online!

Explanation:

,#,p@pXod@dXqnΣ
,#                 push a list of characters in s
,          n   do the following n times:
p@pXo          pop 2 characters off the front, discard the second, put the first back
d@dXq     pop 2 characters off the back, discard the second, put the first back
Σ  join