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

Given a non-empty string, keep removing the first and last characters until you get to one or two characters.

For example, if the string was abcde, your program should print:

abcde
 bcd
  c

However, if it was abcdef, it should stop at two characters:

abcdef
 bcde
  cd

Trailing newlines and trailing spaces at the end of each line are optional. You can have as many as you want or none.

Test cases

ABCDEFGHIJKLMNOPQRSTUVWXYZ -> ABCDEFGHIJKLMNOPQRSTUVWXYZ
                               BCDEFGHIJKLMNOPQRSTUVWXY 
                                CDEFGHIJKLMNOPQRSTUVWX  
                                 DEFGHIJKLMNOPQRSTUVW   
                                  EFGHIJKLMNOPQRSTUV    
                                   FGHIJKLMNOPQRSTU     
                                    GHIJKLMNOPQRST      
                                     HIJKLMNOPQRS       
                                      IJKLMNOPQR        
                                       JKLMNOPQ         
                                        KLMNOP          
                                         LMNO           
                                          MN            

ABCDEFGHIJKLMNOPQRSTUVWXYZ! -> ABCDEFGHIJKLMNOPQRSTUVWXYZ!
                                BCDEFGHIJKLMNOPQRSTUVWXYZ 
                                 CDEFGHIJKLMNOPQRSTUVWXY  
                                  DEFGHIJKLMNOPQRSTUVWX   
                                   EFGHIJKLMNOPQRSTUVW    
                                    FGHIJKLMNOPQRSTUV     
                                     GHIJKLMNOPQRSTU      
                                      HIJKLMNOPQRST       
                                       IJKLMNOPQRS        
                                        JKLMNOPQR         
                                         KLMNOPQ          
                                          LMNOP           
                                           MNO            
                                            N             

A -> A

AB -> AB

Remember this is , so the code with the smallest number of bytes wins.

share|improve this question
    
Can the output be a list of strings, instead of printing the strings? – Greg Martin yesterday
    
@GregMartin Yes. – Oliver yesterday
1  
Do we need to have the leading spaces on each line? – ETHproductions yesterday
    
@ETHproductions Yes. – Oliver yesterday
8  
@Oliver That's important information, you should include it in the text – Luis Mendo yesterday

13 Answers 13

V, 10 bytes

ò^llYpr $x

Try it online!

Explanation:

ò^ll         " While there are at least two non-whitespace characters on the current line
    Y        " Yank this line
     p       " Paste it below
      r      " Replace the first character with a space
        $    " Move to the end of the line
         x   " Delete a character
share|improve this answer

ES6 (Javascript), 47, 48, 43 bytes

EDIT: Replaced ternary operator with &&, prefixed padding string with the newline. Thanks @Neil for an excellent advice !

EDIT: included the function name for the recursive invocation, stripped one byte off by using a literal newline

Golfed

R=(s,p=`
 `)=>s&&s+p+R(s.slice(1,-1),p+' ')

Test

R=(s,p=`
 `)=>s&&s+p+R(s.slice(1,-1),p+' ')

console.log(R("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

ABCDEFGHIJKLMNOPQRSTUVWXYZ
 BCDEFGHIJKLMNOPQRSTUVWXY
  CDEFGHIJKLMNOPQRSTUVWX
   DEFGHIJKLMNOPQRSTUVW
    EFGHIJKLMNOPQRSTUV
     FGHIJKLMNOPQRSTU
      GHIJKLMNOPQRST
       HIJKLMNOPQRS
        IJKLMNOPQR
         JKLMNOPQ
          KLMNOP
           LMNO
            MN

console.log(R("ABCDEFGHIJKLMNOPQRSTUVWXYZ!"))

ABCDEFGHIJKLMNOPQRSTUVWXYZ!
 BCDEFGHIJKLMNOPQRSTUVWXYZ
  CDEFGHIJKLMNOPQRSTUVWXY
   DEFGHIJKLMNOPQRSTUVWX
    EFGHIJKLMNOPQRSTUVW
     FGHIJKLMNOPQRSTUV
      GHIJKLMNOPQRSTU
       HIJKLMNOPQRST
        IJKLMNOPQRS
         JKLMNOPQR
          KLMNOPQ
           LMNOP
            MNO
             N
share|improve this answer
1  
I notice that @xnor starts with p equal to a newline and a space; maybe that could help you too. – Neil 18 hours ago
1  
Oh, and you can also use s&& instead of s?...:''. – Neil 17 hours ago

Python, 45 bytes

f=lambda s,p='\n ':s and s+p+f(s[1:-1],p+' ')

Recursively outputs the string, plus a newline, plus the leading spaces for the next line, plus the recursive result for the shortened string with an extra space in the prefix.

If a leading newline was allowed, we could save a byte:

f=lambda s,p='\n':s and p+s+f(s[1:-1],p+' ')

Compare with a program (49 bytes in Python 2):

s=input();p=''
while s:print p+s;s=s[1:-1];p+=' '
share|improve this answer

Python 2, 50 bytes

def f(i,j=0):
 print' '*j+i
 if i:f(i[1:-1],j+1)

Simple recursive function that keeps shortening the string until it disappears.

Call as f('string')

Output

string
 trin
  ri
share|improve this answer

Perl, 31 bytes

30 bytes of code + -p flag.

s/( *)\S(.+).$/$& 
 $1$2/&&redo

To run it :

perl -pE 's/( *)\S(.+).$/$&
 $1$2/&&redo' <<< "abcdef"

Explanations : The \S and .$ correspond to the first and last character, (.+) the middle and ( *) to the trailing spaces that are added every time we remove one character from the beginning. So the regex removes one character from the beginning, one from the end, and add one leading space each time.

share|improve this answer

MATL, 9 bytes

tg!*YRPRc

This produces trailing spaces and newlines.

Try it online!

Explanation

t      % Input string implicitly. Duplicate
g!     % Convert to logical and transpose: gives a column vector of ones
*      % Multiply with broadcast. This gives a square matrix with the string's
       % ASCII codes on each row
YR     % Lower triangular part: make elements above the diagonal 0
P      % Flip vertically
R      % Upper triangular part: make elements below the diagonal 0
c      % Convert to char. Implicitly display, with char 0 shown as space
share|improve this answer

Haskell, 47 43 bytes

f s@(a:b:c)=s:map(' ':)(f.init$b:c)
f s=[s]

Try it on Ideone. Output is a list of strings which was allowed in the comments of the challenge. To print, run with (putStr.unlines.f) instead of just f.

Edit: Saved 4 bytes after noticing that trailing whitespace is allowed.

Prelude> (putStr.unlines.f)"codegolf"
codegolf
 odegol
  dego
   eg
               --(trailing whitespace)
share|improve this answer

Batch, 92 bytes

@set/ps=
@set t=
:g
@echo %t%%s%
@set t= %t%
@set s=%s:~1,-1%
@if not "%s%"=="" goto g

Takes input on STDIN.

share|improve this answer

C, 73 bytes

f(char*s){char*b=s,*e=s+strlen(s)-1;while(e-b>-1)puts(s),*b++=32,*e--=0;}

Ungolfed:

f(char*s) {
  char *b=s,
       *e=s+strlen(s)-1;
  while (e-b>-1)
    puts(s),
    *b++=32,
    *e--=0;
}

Usage:

main(){
  char a[] = "abcde";
  f(a);
}
share|improve this answer

Pyke, 10 bytes

VQlRc
l7tO

Try it here!

share|improve this answer

05AB1E, 8 bytes

Code:

ÐvNú,¦¨D

Explanation:

Ð          # Triplicate the input
 v         # Length times do...
  Nú,      # Prepend N spaces and print with a newline
     ¦¨    # Remove the first and the last character
       D   # Duplicate that string

Uses the CP-1252 encoding. Try it online!

share|improve this answer

Perl 6, 42 bytes

for get,{S/\w(.*)./ $0/}.../\s..?$/ {.put}

Expanded:

for

  # generate the sequence
  get,       # get a line from the input

  {          # bare block lambda with implicit parameter 「$_」
             # used to produce the rest of the sequence

    S/       # replace
      \w     # a word character ( to be removed )
      (      # set 「$0」
        .*   # any number of any characters
      )
      .      # any character ( to be removed )
    / $0/    # append a space

  }

  ...        # repeat that until

  /          # match
    \s       # whitespace
    .        # any character
    .?       # optional any character
    $        # end of string
  /

{
  .put       # print $_ with trailing newline
}
share|improve this answer

Brainfuck, 67 bytes

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

This should work on all brainfuck flavors.

Try it online!

Ungolfed code:

# Print and read input_string into memory
>>,[.>,]<
while input_string is not empty [
    # Print newline
    >+++++ +++++.<
    # Remove last character
    [-]
    # GOTO start of input_string
    <[<]>
    # Remove first character
    [-]
    # Add space to space_buffer
    +++++ +++[-<++++>]
    # GOTO start of space_buffer
    <[<]>
    # Print space_buffer
    [.>]
    # Print input_string
    >[.>]
<]

There should still be some bytes to chop off here; I've only recently began using brainfuck, so my pointer movement is probably very inefficient.

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.