Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

2     ADEFGHIJKLMP
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.

The Task

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.

share|improve this question
    
Question: Is it okay to take N in unary with something like ' as the counting character? For example: ''123321? – daavko Feb 19 at 13:24
    
@daavko Yes, unary is acceptable by default – Adnan Feb 19 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) – Luis Mendo Feb 19 at 15:21
    
@LuisMendo Yes, you may use that – Adnan Feb 19 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? – VisualBean Feb 22 at 13:14

33 Answers 33

up vote 5 down vote accepted

MATL, 8 9 12 13 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
share|improve this answer
    
Explanation? :P – VTCAKAVSMoACE Feb 19 at 14:03
    
@VoteToClose Sure :-) I had to run. I've just added it – Luis Mendo Feb 19 at 15:06

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!

share|improve this answer
7  
Related. – VTCAKAVSMoACE Feb 19 at 13:56
    
@MartinBüttner Aha! So this was your psychological masterplan :p – Adnan Feb 19 at 14:05
9  
@Adnan ¯\_(ツ)_/¯ – Martin Ender Feb 19 at 14:07
    
Crossed out 44 looks like crossed out 11... – CocoaBean Feb 19 at 19:52

Python 2, 31 bytes

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

I think this works?

share|improve this answer
    
Yes, it seems to work :) – Adnan Feb 19 at 12:56
    
It's also valid python 3. – Chiel ten Brinke Feb 20 at 15:30

Mathematica, 29 bytes

My first answer!

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

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

share|improve this answer
1  
Welcome to PPCG! :D Nice first answer. – VTCAKAVSMoACE Feb 19 at 16:47

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 @.

share|improve this answer

JavaScript (ES6), 39 bytes

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

Turns out I just reinvented @Sp3000's answer.

share|improve this 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.
share|improve this answer

Jelly, 10 bytes

Ḣ;Ṫ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
share|improve this answer
    
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? – AutomatedChaos Feb 19 at 15:11
1  
@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. – Sp3000 Feb 19 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

share|improve this answer

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!

share|improve this answer
    
@Adnan Fixed - that places me in close proximity to Pyth. D: – VTCAKAVSMoACE Feb 19 at 13:13
    
But still one byte ahead :D – Adnan Feb 19 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? – VTCAKAVSMoACE Feb 19 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 :) – Adnan Feb 19 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) – VTCAKAVSMoACE Feb 19 at 13:19

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

share|improve this answer

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 */
}
share|improve this answer

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.)

share|improve this answer

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
}
share|improve this answer

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.
share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

As of yet untitled language (so new noncompetitive), 9 bytes

hD_RQ:Q|J

You can find the source code here, language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 7)

This is a stack based language with functions that add and remove objects from the stack. There are currently 2 stack manipulation commands: D(duplicate the top of the stack N times) and R(rotate the top N items on the stack)

Explanation:

          - autoassign Q = eval_or_not(input()) (string)
h         - imp_eval_input()+1
 D        - duplicate(^)
  _       - neg(^)
   R      - rotate(^)
    Q:    - Q[^:^]
      Q|  - Q[0], Q[-1]
        J - "".join(all)
share|improve this answer

CJam, 14 bytes

l(o)\l~_W*@<>o

Test it here.

Explanation

l   e# Read the input string.
(o  e# Pull off the first character and print it.
)\  e# Pull off the last character and swap with the rest of the string.
l~  e# Read the second line of the input and evaluate it (N).
_   e# Duplicate.
W*  e# Multiply by -1 to get -N.
@   e# Pull up the string.
<   e# Discard the last N characters.
>   e# Discard the first N characters.
o   e# Output what's left. The last character of the input is now still on the
    e# stack and is automatically printed at the end of the program.
share|improve this answer

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
share|improve this answer

mSL - 137 bytes

c {
%l = $len($1)
return $mid($+($mid($1,2,1),$left($1,1),$right($left($1,-2),-2),$right($1,1),$mid($1,$calc(%l -1),1)),2,$calc(%l -2))
}

Explanation:

%l = $len($1) will get the length of the input string and saves it in variable called l

$right(<input>,<length>) and $left(<input>,<length> can be used to return the left or right most part of the original string respectably. $left always return text starting from the very left side while $right always return text starting from the right side. If the length specified is a negative number, $left and $right return the entire text minus that many characters from their respective sides.

$mid(<string>,<start>,[length]) is used to get a substring from the middle of the string. Start is the start of the substring from the left. A negative value indicates a start from the right. In both case, an optional length can be specified. A negative length can be used to remove that many characters from the end. So I used it to retrieve the second character and the second last character by using the length of the input string.

$calc(<input>) is used to perform mathematical calculations

share|improve this answer
1  
Welcome to PPCG! It's generally a good idea to add some annotations or an explanation of your code. – Zach Gates Feb 22 at 2:15
    
@ZachGates Thanks! Will remember this for the next time! – Denny Feb 22 at 11:20

Brainfuck, 130 bytes

My first PPCG entry!

Obviously not gonna win but hey.

Takes input like: 4ABCDEFGHIJKL, with the first character being N.

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

Test it on this wonderful site.

Limited to N less than or equal to 9, because two-digit numbers are a pain in the butt.

EDIT: I sucked it up and added support for two-digit numbers. Pad with a zero for single digits.

,>+++++++[<------->-]<+ [>++++++++++<-]>[<+>-],>+++++++[<------->-]<+ [<+>-]>+[>,]<[<]>-<<[>>>[<+>-]>[<+>-]<<[>>+<<-]>[>]<[>+<-]<[>+<-]>>[<<+>>-]<[-]<[<]>[-]>[[<+>-]>]<<[<]<<-]>>>[.>]
share|improve this answer
    
Welcome to PPCG! This is a very nice first answer! :) – Adnan Mar 3 at 13:24
    
@AandN thanks! I've been looking for a while for a challenge that could be reasonably easily solved in BF, which is one of my new favorite languages :D – user3284178 Mar 3 at 14:16

Perl, 27 bytes

Include +1 for -p

Run as perl -p sdr.pl

Input given on STDIN, first line the string, second line the count Assumes the string contains only "word" characters

sdr.pl:

eval's%\B.(.*).\B%$1%;'x<>
share|improve this answer

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
share|improve this answer
    
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 – Ismael Miguel Feb 19 at 19:49
1  
Yeah, I don't wanna do answers which require register globals anymore. Thx for the suggestion though :) – aross Feb 19 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
share|improve this answer

CJam, 15 bytes

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

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

share|improve this answer

Jolf, 13 bytes

ΆFi liγhj_γgi

A tranpilation of the JavaScript answer.

Explanation:

ΆFi liγhj_γgi
Ά             ternary add
 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
share|improve this answer

Seriously, 17 bytes

,#,`p@pXod@dXq`nΣ

Takes input as s \n n.

Try it online!

Explanation:

,#,`p@pXod@dXq`nΣ
,#                 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
share|improve this answer

C#, 129 bytes

Since we basically skip 1 and remove N and the reversed scenario

string o(string i,int n){var s=i.ToList();int x=0;while(x<2){s.RemoveRange(1,n);s.Reverse();x++;}return new string(s.ToArray());}

ungolfed

string o(string i, int n)
{
    var s = i.ToList();
    int x = 0;
    while (x < 2) //Repeat the following twice
    {
        s.RemoveRange(1, n); //remove n at index 1
        s.Reverse(); //Reverse the list
        x++;
    }
    return new string(s.ToArray());
}
share|improve this answer

Java, 144 bytes

static String y(int i,String s){return i==0?s:y(i-1,new StringBuffer(s).replace(1,2,"").replace(s.length()-3,s.length()-2,"").toString());}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.