Introduction:

Inspired by this comment of @MagicOctopusUrn on @Emigna's 05AB1E answer for my "It was just a bug" challenge:

8F9ÝÀNð×ý}».∊ I done did made a spaceship maw! And I was all excited about suggesting a 12-byte edit. – Magic Octopus Urn Jul 17 '17 at 20:10

Which is a 05AB1E (legacy) program resulting in this:

1234567890
1 2 3 4 5 6 7 8 9 0
1  2  3  4  5  6  7  8  9  0
1   2   3   4   5   6   7   8   9   0
1    2    3    4    5    6    7    8    9    0
1     2     3     4     5     6     7     8     9     0
1      2      3      4      5      6      7      8      9      0
1       2       3       4       5       6       7       8       9       0
1      2      3      4      5      6      7      8      9      0
1     2     3     4     5     6     7     8     9     0
1    2    3    4    5    6    7    8    9    0
1   2   3   4   5   6   7   8   9   0
1  2  3  4  5  6  7  8  9  0
1 2 3 4 5 6 7 8 9 0
1234567890

Try it online.

Challenge:

Input: A non-empty string

Output: From outwards going inwards, add one more space between each character every line, similar as done in the output above, equal to the length - 1. So for an input 1234567890 the output would actually be this instead:

1234567890
1 2 3 4 5 6 7 8 9 0
1  2  3  4  5  6  7  8  9  0
1   2   3   4   5   6   7   8   9   0
1    2    3    4    5    6    7    8    9    0
1     2     3     4     5     6     7     8     9     0
1      2      3      4      5      6      7      8      9      0
1       2       3       4       5       6       7       8       9       0
1        2        3        4        5        6        7        8        9        0
1         2         3         4         5         6         7         8         9         0
1        2        3        4        5        6        7        8        9        0 
1       2       3       4       5       6       7       8       9       0
1      2      3      4      5      6      7      8      9      0
1     2     3     4     5     6     7     8     9     0
1    2    3    4    5    6    7    8    9    0
1   2   3   4   5   6   7   8   9   0
1  2  3  4  5  6  7  8  9  0
1 2 3 4 5 6 7 8 9 0
1234567890

Why? The length of 1234567890 is 10. So we start by outputting 10 lines: the first line without spaces; second with one space delimiter; third with two; etc. And then (without have the middle line with length - 1 spaces duplicated), we go back to the initial input while going down.

Challenge rules:

  • Input is guaranteed to be non-empty (a length >= 1). (For single char inputs we simply output that character.)
  • Any amount of trailing/leading spaces/newlines are allowed, as long as the output itself (wherever on the screen) is correct. (Empty line(s) in between output lines also isn't allowed.)
  • Input will only contain printable ASCII characters excluding whitespaces (code-point range [33, 126])
  • I/O is flexible. Input may be taken as STDIN, argument, or function parameter. May be a list/array/stream of characters instead of string. Output may also be a list/array/stream of characters instead of strings; may be printed to STDOUT; returned as newline-delimited string; etc.

General rules:

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code.
  • Also, adding an explanation for your answer is highly recommended.

Test cases:

Input: @
Output:
@

Input: test
Output:
test
t e s t
t  e  s  t
t   e   s   t
t  e  s  t
t e s t
test

Input: ?!
Output:
?!
? !
?!

Input: Spaceship
Output:
Spaceship
S p a c e s h i p
S  p  a  c  e  s  h  i  p
S   p   a   c   e   s   h   i   p
S    p    a    c    e    s    h    i    p
S     p     a     c     e     s     h     i     p
S      p      a      c      e      s      h      i      p
S       p       a       c       e       s       h       i       p
S        p        a        c        e        s        h        i        p
S       p       a       c       e       s       h       i       p
S      p      a      c      e      s      h      i      p
S     p     a     c     e     s     h     i     p
S    p    a    c    e    s    h    i    p
S   p   a   c   e   s   h   i   p
S  p  a  c  e  s  h  i  p
S p a c e s h i p
Spaceship

Input: 05AB1E
Output:
05AB1E
0 5 A B 1 E
0  5  A  B  1  E
0   5   A   B   1   E
0    5    A    B    1    E
0     5     A     B     1     E
0    5    A    B    1    E
0   5   A   B   1   E
0  5  A  B  1  E
0 5 A B 1 E
05AB1E

Input: )}/\
Output:
)}/\
) } / \
)  }  /  \
)   }   /   \
)  }  /  \
) } / \
)}/\
  • 1
    Gets all just jittery !!!SPACESHIP!!! – WallyWest Sep 5 at 22:03
  • 1
    I knew I recognized that output. I love that this idea is still going. – Carcigenicate Sep 5 at 23:01
  • 1
    TFW you vaguely recognize a pattern in a question ಠ_ಠ then realize it's because you accidentally made it a year ago ಠ⌣ಠ. – Magic Octopus Urn Sep 6 at 17:25
  • 1
    @MagicOctopusUrn Thanks for the inspiration. ;D – Kevin Cruijssen Sep 6 at 17:26
  • 3
    @KevinCruijssen thanks for keeping the goofy quote haha! – Magic Octopus Urn Sep 6 at 17:26

41 Answers 41

up vote 11 down vote accepted

Japt, 8 6 bytes

Takes input as an array of characters, outputs an array of strings.

£qYçÃê

Try it


Explanation

£          :Map each element at (0-based) index Y
 q         :  Join input with
  Yç       :   Space repeated Y times
    Ã      :End Map
     ê     :Palindromise

Original, 8 bytes

I/O is a string. Uses the -R flag. Includes trailing spaces on each line.

¬£múYÄÃê

Try it

Explanation

             :Implicit input of string U
¬            :Split
 £           :Map each character at 0-based index Y
  m          :  Map original U
   ú         :    Right pad with spaces to length ...
    YÄ       :     Y+1
      Ã      :End map
       ê     :Palindromise
             :Implicitly join with newlines
  • S.ç() FTW once again :-) – ETHproductions Sep 4 at 16:00
  • 1
    Serious question: would it be feasible to search iteratively through all 1 to 6 bytes long solutions for a puzzle like this? – filip Sep 5 at 7:22
  • 2
    @filip No: there are more than 256**6=281474976710656 (at least naive) combinations. It's like guessing a password. – Kirill Bulygin Sep 5 at 14:44
  • 2
    @KirillBulygin, there are over 37 trillion (37,764,717,485,592) possible ways of combining the characters available in Japt into a string between 1 & 6 characters long. If you include all the other 1 byte characters which can be used in string literals or compressed strings, that number grows to over 276 trillion (276,024,445,697,280). So, no, writing a bot to generate all those then filter out the valid Japt programmes then find the one (if any exists) that works for the challenge at hand probably wouldn't be feasible. Besides where's the fun in letting a bot do your golfing for you?! – Shaggy Sep 5 at 15:46
  • 5
    @Shaggy: "where's the fun in letting a bot do your golfing for you?!" What if you made the bot really, really short? – Oddthinking Sep 7 at 2:17

R, 105 99 85 84 79 bytes

-6 thanks to @Kevin Cruissen and @Giuseppe

-14 from changing to a regex based method

-1 thanks to @Giuseppe

-5 thanks to @digEmALl

function(w,n=nchar(w)-1)write(trimws(Map(gsub,"",strrep(" ",n-abs(n:-n)),w)),1)

Try it online!

  • You can golf 1 byte by removing the space at in(r<-. – Kevin Cruijssen Sep 4 at 17:01
  • 1
    and you only use s once so you can just use it as an argument in write directly; bringing you down to 99 bytes – Giuseppe Sep 4 at 17:08
  • 1
    should that be a 1 rather than a "" in write? I'm digging your use of Map! – Giuseppe Sep 4 at 17:57
  • 1
    Awesome ! 79 bytes using math :) – digEmAll Sep 5 at 7:27
  • 1
    I was convinced I could beat this with the collapse argument to paste but it just isn't happening... – JDL Sep 6 at 16:21

JavaScript (ES6), 53 bytes

Takes input as an array of characters.

f=(s,p=i='',o=s.join(p)+`
`)=>s[++i]?o+f(s,p+' ')+o:o

Try it online!

Canvas, 8 bytes

┐² ×*]──

Try it here!

The 7 byte version was too good for this challenge..

  • I like your 7 byte version. Would you be willing to explain how it works? Which operator overlaps the two /s into a X? – Kaya Sep 4 at 21:31
  • 3
    @Kaya it's the last character - - vertical palindromize. The palindromization of Canvas does cool things. The overlapping part has it's own character too. – dzaima Sep 4 at 21:37

Python 2, 72 70 68 66 65 bytes

-2 bytes thanks to Kevin Cruijssen
-3 bytes thanks to ovs

w=input();c=s=-1
while c:print(' '*~c).join(w);s*=w[:c]>'';c+=s|1

Try it online!

  • c==len(w)-1 can be golfed by 1 byte with c+2>len(w). EDIT: In your new 70-byte version, 0<c can be c. – Kevin Cruijssen Sep 4 at 14:13

05AB1E, 10 9 bytes

Saved 1 bytes thanks to Adnan

εINð×ý}û»

Try it online!

Explanation

ε            # apply to each in input
 I           # push the input
  Nð×        # push <index> spaces
     ý       # merge the input on the spaces
      }      # end loop
       û     # palendromize
        »    # join on newlines
  • You can drop the S. Input is flexible, so inputting as list is allowed. – Kevin Cruijssen Sep 4 at 14:26
  • 1
    @KevinCruijssen: Your first version is 9 bytes in legacy though, as » can be omitted. – Emigna Sep 4 at 16:22
  • 1
    Yours actually works in the legacy in 9 bytes as well if you remove » and change the loop v to a map ε. – Kevin Cruijssen Sep 4 at 17:04
  • 1
    Posted the answer. And currently Japt is beating us with 6 bytes I'm afraid. Or did you mean shortest in 05AB1E (Elixir rewrite) and 05AB1E (Python legacy)? :) – Kevin Cruijssen Sep 4 at 21:09
  • 2
    Does εINð×ý}û» also work? – Adnan Sep 4 at 21:20

Charcoal, 10 bytes

Eθ⪫θ× κ‖O↓

Try it online! Link is to verbose version of code. Explanation:

Eθ          Map over characters of input string
  ⪫θ        Join characters of input string using
    ×       a literal space repeated 
      κ     current index number of times
            Implicitly print each result on its own line
       ‖O↓  Reflect vertically with overlap
  • Charcoal doesn't reflect things like [ to ]-- or is that another separate command? – Magic Octopus Urn Sep 6 at 21:50
  • @MagicOctopusUrn There are separate commands if you want to transform the reflection. See codegolf.stackexchange.com/a/127164 for example. – Neil Sep 6 at 22:19
  • I thought I had seen it reflect before, but wasn't sure. Neat! – Magic Octopus Urn Sep 6 at 22:23

Ruby, 54 49 bytes

->a{(-(z=a.size-1)..z).map{|i|a*(?\s*(z-i.abs))}}

Try it online!

Takes input as an array of characters, outputs array of strings.

Japt, 9 8 bytes

-1 byte from @Shaggy

ÊƬqXîÃê

ÊƬqXîÃê        Full program, implicity input U
ÊÆ              Rage from 0 to U length and map
  ¬             split U at ""
   qXîà     join U using " " times range current value
        ê       horizontal mirror

Try it online!

  • Dang; looks like you ninjaed me again! Lemme know if you'd like me to delete mine. – Shaggy Sep 4 at 14:19
  • 1
    @Shaggy no, keep your answer, you are using array as input while I use a string so they are kind of different xD – Luis felipe De jesus Munoz Sep 4 at 14:20
  • 1
    SpX -> for a 1 byte saving. – Shaggy Sep 4 at 14:30

PowerShell, 66 54 bytes

-12 bytes thanks to mazzy

0..($x=($a=$args).count-1)+$x..0|gu|%{$a-join(' '*$_)}

Try it online!

Takes input via splatting, which on TIO manifests as separate command-line arguments for each character.

We first set $a=$args as the input argument. Then we set $x equal to the .count of that array -1. We then need to loop through the letters to construct the spaceship. That's done by constructing a range from 0 to $x, then $x back down to 0, then using Get-Unique to pull out just the appropriate range.

Each iteration, we take our input arguments and -join them together with the corresponding number of spaces. Each of those strings is left on the pipeline, and an implicit Write-Output gives us newlines for free when the program completes.

  • Try this: 0..($x=($a=$args).count-1)+$x..0|gu|%{$a-join(' '*$_)} – mazzy Sep 5 at 13:25
  • 1
    @mazzy What the ... how does Get-Unique work like that on the range? That's crazy! Thanks! – AdmBorkBork Sep 5 at 13:50

05AB1E (legacy), 9 bytes

εINúíJ}û»

Input as list of characters.

Try it online or verify all test cases.

Explanation:

ε     }    # Map each character in the input to:
 I         #  Take the input
  Nú       #  Prepend each with the 0-indexed amount of spaces
           #   i.e. ["t","e","s","t"] & 3 → ["   t","   e","   s","   t"]
    í      #  Reverse each item
           #   i.e. ["   t","   e","   s","   t"] → ["t   ","e   ","s   ","t   "]
     J     #  Join them together to a single string
           #   i.e. ["t   ","e   ","s   ","t   "] → "t   e   s   t   "
       û»  # Palindromize the list, and join by newlines
           #  i.e. ["test","t e s t ","t  e  s  t  ","t   e   s   t   "]
           #   → "test\nt e s t \nt  e  s  t  \nt   e   s   t   \nt  e  s  t  \nt e s t \ntest"
  • 1
    Oooooo, also this isn't valid because mirror changes the orientation of / to \ when mirrored, same with [, ] and (, ). May want to add those cases to catch charcoal too. (Moved the other comments to Emigna's answer, because he was the answer I originally commented on) – Magic Octopus Urn Sep 6 at 21:46
  • @MagicOctopusUrn Thanks for letting me know. Fixed it by using û» instead of .∊. – Kevin Cruijssen Sep 7 at 7:07

Haskell, 60 59 bytes

(init<>reverse).(scanl(?)<*>tail)
a?_=do u<-a;u:[' '|' '<u]

Try it online!

Explanation

For a string (eg. "abc") we apply first

scanl (?) <*> tail

which is the same as

\str -> scanl (?) str (tail str)

This repeatedly applies (?) (appends a space to each character in the range [33..]) to the str until there are that many strings as str has characters: ["abc","a b c ", "a b c "]

Now we only need to concatenate the result (minus the last element) with its reversed counter part:

init<>reverse

MATL, 25 22 13 bytes

zZv"Gtz@he!1e

Try it online!

Thanks to Luis Mendo for suggesting a 5 byte golf, which then inspired me to shave off 4 more bytes!

Explanation, with example input 'abc':

         # Implicit input, 'abc'
z        # find number of nonzero elements (length of string)
         # stack: [3]
Zv       # symmetric range
         # stack: [[1 2 3 2 1]]
"        # begin for loop, iterating over [1 2 3 2 1] as the loop indices
G        # push input
         # stack: ['abc']
tz       # dup and push length
         # stack: ['abc', 3]
@        # push loop index, i (for example, 2)
         # stack: ['abc', 3, 2]
h        # horizontally concatenate
         # stack: ['abc', [3, 2]]
e!       # reshape to matrix of 3 rows and i columns, padding with spaces, and transpose
         # stack: [['abc';'   ';'   ']]
1e       # reshape to matrix of 1 row, leaving last value on stack
         # stack: ['a  b  c  ']
         # implicit end of for loop
         # implicit end of program, display stack contents

Jelly, 9 bytes

jⱮLḶ⁶ẋƲŒḄ

Try it online!

Returns a list of lines; output prettified over TIO.

  • A somewhat different 9: ,€⁶$LСŒḄ. Other, more similar, 9's: J’⁶ẋŒḄɓjⱮ and J’⁶ẋŒḄjⱮ@ (I was looking for shorter but no joy yet) – Jonathan Allan Sep 4 at 16:33
  • @JonathanAllan I'm pretty sure this is optimal, I don't think there's any shorter way to write LḶ⁶ẋ or ŒḄ. However, if you manage to find a save, do ping me. :-) – Erik the Outgolfer Sep 4 at 16:35
  • Thinking about it a bit my ,€⁶$LСŒḄ may not be valid since it has crazy nesting so might need a Y and be a full program. – Jonathan Allan Sep 4 at 16:37
  • @JonathanAllan Yeah, of course it's not. ['I', 'f', [[' '], 't', 'h', [['i']], 's'], ' ', 'i', ['s', ' '], 'a', [[' ', 's', 't'], 'r', ['i', 'n', 'g'], ' '], 'w', ['e', ' ', 'a', 'r', 'e'], ' ', 'd', 'o', ['o'], 'm', [[[[['e']]]]], [[[['d']]]], '!'] At least I've outgolfed 05AB1E... – Erik the Outgolfer Sep 4 at 16:39
  • I said I outgolfed 05AB1E, eh? Bah, not anymore. :/ – Erik the Outgolfer Sep 5 at 18:00

Pyth, 12 bytes

Just my mandatory Pyth submission. I am quite proud of this so an explanation will likely come soon.

+P_=jRQ*L;_U

Try it here!

+P_=jRQ_.e*d

Try it here!

Stax, 10 bytes

Ç·9ƒù▌╘Ä┘e

Run and debug it

Outputs with trailing whitespace on each line.

Explanation:

%R|pmx{]n(m Full program, unpacked, implicit input
%           Length of input
 R          1-based range
  |p        Palindromize
    m       Map:
     x{   m   Map over characters of input:
       ]        Character -> string
        n(      Right-pad to length given by outer map value
              Implicit flatten and output

Java (JDK 10), 115 bytes

s->{for(int l=s.length(),i=-l;++i<l;)System.out.printf(s.replaceAll(".","%-"+(i<0?l+i:l-i)+"s")+"%n",s.split(""));}

Try it online!

  • 1
    l-Math.abs(i) can be golfed to i<0?l+i:l-i for -2 bytes. – Kevin Cruijssen Sep 4 at 14:42
  • @KevinCruijssen Thanks! :) – Olivier Grégoire Sep 4 at 14:44
  • could it be l-i<0?-i:i? – Quintec Sep 4 at 18:06
  • @thecoder16 You would need parentheses: l-(i<0?-i:i) (12 bytes). – Jonathan Frech Sep 4 at 18:22

K (oK), 25 24 bytes

Solution:

,/'(1+a,1_|a:!#x)$\:+,x:

Try it online!

Explanation:

Port of my K4 solution:

,/'(1+a,1_|a:!#x)$\:+,x: / the solution
                      x: / save input as x
                     ,   / enlist
                    +    / flip
                 $\:     / pad ($) right by each-left (\:)
   (            )        / do this together
              #x         / count length of input,           e.g. 3
             !           / range 0..length,                 e.g. 0 1 2
           a:            / save as a
          |              / reverse it,                      e.g. 2 1 0
        1_               / drop first,                      e.g. 1 0
      a,                 / join to a,                       e.g. 0 1 2 1 0
    1+                   / add 1,                           e.g. 1 2 3 2 1
,/'                      / flatten (,/) each (')

Notes:

  • -1 byte thanks to ngn
  • 1
    ,:' -> +,­­ – ngn Sep 14 at 10:15

Pascal (FPC), 143 135 bytes

var s:string;i,j,l:word;begin read(s);l:=length(s);repeat i:=i+1;for j:=1to l do write(s[j],'':l-abs(l-i)-1);writeln until i=l*2-1 end.

Try it online!

I will probably win only against Lenguage...

PHP, 88 89 bytes

for(;++$i<2*$e=count($a=str_split($argn));)echo join(str_pad("",~-$e-abs($i-$e)),$a),"\n";

requires PHP 5 or later for str_split. Run as pipe with -nR or try it online.

  • Your try-it-online link gives the wrong output I'm afraid. In your output all lines also have leading spaces, instead of only between characters (or optionally trailing). The first character should all be in the same column in the output. – Kevin Cruijssen Sep 4 at 19:06
  • 1
    @KevinCruijssen Didn´t look at the output close enough. Fixed. (Though imo my previous output looked more like a rocket) ;-) – Titus Sep 4 at 19:34
  • It kinda looked like the head of an arrow to me. :D But +1 now that it's fixed. – Kevin Cruijssen Sep 4 at 20:53
  • If you place an actual newline instead of the \n, you save a byte :) – Martijn Sep 6 at 14:22
  • @Martijn I actually did only count one byte for it ... forgot to replace it when I pasted the code here. – Titus Sep 6 at 22:26

K4, 23 bytes

Solution:

,/'(1+a,1_|a:!#x)$\:$x:

Example:

q)k),/'(1+a,1_|a:!#x)$\:$x:"Spaceship"
"Spaceship"
"S p a c e s h i p "
"S  p  a  c  e  s  h  i  p  "
"S   p   a   c   e   s   h   i   p   "
"S    p    a    c    e    s    h    i    p    "
"S     p     a     c     e     s     h     i     p     "
"S      p      a      c      e      s      h      i      p      "
"S       p       a       c       e       s       h       i       p       "
"S        p        a        c        e        s        h        i        p        "
"S       p       a       c       e       s       h       i       p       "
"S      p      a      c      e      s      h      i      p      "
"S     p     a     c     e     s     h     i     p     "
"S    p    a    c    e    s    h    i    p    "
"S   p   a   c   e   s   h   i   p   "
"S  p  a  c  e  s  h  i  p  "
"S p a c e s h i p "
"Spaceship"

Explanation:

Has trailing whitespace on each line.

,/'(1+a,1_|a:!#x)$\:$x: / the solution
                     x: / save input as x,                 e.g. "abc"
                    $   / string,                          e.g. (,"a";,"b";,"c")
                 $\:    / pad ($) right by each-left (\:)
   (            )       / do this together
              #x        / count length of input,           e.g. 3
             !          / range 0..length,                 e.g. 0 1 2
           a:           / save as a
          |             / reverse it,                      e.g. 2 1 0
        1_              / drop first,                      e.g. 1 0
      a,                / join to a,                       e.g. 0 1 2 1 0
    1+                  / add 1,                           e.g. 1 2 3 2 1
,/'                     / flatten each

C#, 113 105 98 bytes

s=>{for(int l=s.Length,i=-l;++i<l;)WriteLine(Join("",s.Select(c=>$"{c}".PadRight(i<0?l+i:l-i))));}

Try it online!

  • Hi there. Currently your answer is a snippet instead of a function or full program. This can cheaply be fixed by adding s=>{ before and } after to make it a lambda-function. In addition, one thing to golf is removing the brackets around the for-loop. Try it online. – Kevin Cruijssen Sep 5 at 11:38
  • @KevinCruijssen Thanks! Forgot to fix that before posting... – RobIII Sep 5 at 11:44

Scala, 82 bytes

for(i<-(0 to a.size)union(-a.size to 0))println(a.map(_+" "*Math.abs(i)).mkString)

Try it online

Scala has lot of shortcuts that are helping me here and that is quite readable! Try Scala

  • Hi there, welcome to PPCG! Although it's a nice answer, I'm afraid two things are slightly incorrect. The line with the most spaces should only be output once in the middle instead of twice. And currently you print from 0 to length amount of spaces, instead of 0 to length-1 amount of spaces. I don't know Scala too well, but it seem you can fix both issues with +4 bytes (86 bytes in total) like this: for(i<-(0 to a.size-1)union(-a.size+2 to 0))println(a.map(_+" "*Math.abs(i)).mkString) Again welcome, and enjoy your stay! :) – Kevin Cruijssen Sep 5 at 16:53

Oracle SQL, 115 bytes

Not a golfing language but...

SELECT TRIM(REGEXP_REPLACE(v,'(.)',LPAD('\1',1+LENGTH(v)-ABS(LEVEL-LENGTH(v)))))FROM t CONNECT BY LEVEL<2*LENGTH(v)

Assuming that the value is in column v of table t:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE t ( v ) AS
  SELECT 'test' FROM DUAL;

Query 1:

SELECT TRIM(REGEXP_REPLACE(v,'(.)',LPAD('\1',1+LENGTH(v)-ABS(LEVEL-LENGTH(v)))))
FROM   t
CONNECT BY LEVEL<2*LENGTH(v)

Results:

(SQLFiddle prints the values right-aligned in the column for some reason... there are no leading spaces)

| TRIM(REGEXP_REPLACE(V,'(.)',LPAD('\1',1+LENGTH(V)-ABS(LEVEL-LENGTH(V))))) |
|---------------------------------------------------------------------------|
|                                                                      test |
|                                                                   t e s t |
|                                                                t  e  s  t |
|                                                             t   e   s   t |
|                                                                t  e  s  t |
|                                                                   t e s t |
|                                                                      test |
  • Your SQL Fiddle results seems to only have single spaces in between characters? See this screenshot. I assume this is due to SQL Fiddle and it works locally? Btw, not sure if SQL uses standard regex rules, but can (.) be golfed to . by using \0 instead of \1 like you could in Java for example? EDIT: Never mind, that is for $0, not \0.. (Java example of what I meant). – Kevin Cruijssen Sep 6 at 13:11
  • 1
    @KevinCruijssen Click on the down arrow next the the "Run SQL" button and change the output to "Plaintext Output" or "Markdown Output" and you will see the spaces. – MT0 Sep 6 at 13:21
  • Thanks. It indeed looks good in that case! – Kevin Cruijssen Sep 6 at 13:23

8086 machine code, 56 53 bytes

00000000  bf 35 01 57 ba 01 00 52  be 82 00 b3 ff ac 59 51  |.5.W...R......YQ|
00000010  aa 3c 0d 74 07 b0 20 e2  f7 43 eb f1 b0 0a aa 59  |.<.t.. ..C.....Y|
00000020  00 d1 e3 08 38 cb d6 08  c2 51 eb dc c6 05 24 5a  |....8....Q....$Z|
00000030  b4 09 cd 21 c3                                    |...!.|
00000035

Assembled from:

org 0x100
use16
        mov di, buffer
        push di
        mov dx, 1
        push dx
nextl:  mov si, 0x82
        mov bl, -1
nextc:  lodsb
        pop cx
        push cx
stor:   stosb
        cmp al, 0x0d
        je cr
        mov al, ' '
        loop stor
        inc bx
        jmp nextc
cr:     mov al, 0x0a
        stosb
        pop cx
        add cl, dl
        jcxz done
        cmp bl, cl
        salc
        or dl, al
        push cx
        jmp nextl
done:   mov [di], byte '$'
        pop dx
        mov ah, 0x09
        int 0x21
        ret
buffer:

Test case:

screenshot

  • Hi there. I guess there isn't any online compiled for 8086 machine code, but could you perhaps add a screenshot of the output for one of the test cases? Then I can check if everything is correct. :) – Kevin Cruijssen Sep 5 at 16:56
  • Done. Also shaved off one more byte :) – user5434231 Sep 5 at 17:02
  • Thanks for the screenshot! Unfortunately there is one small mistake in the output. The middle line now has length amount of spaces and there are 9 lines in total, but the middle line should have length-1 amount of spaces and there should be a total of 7 lines instead (for the 4-letter word 'test'`).. :( I hope it's not to expensive in terms of bytes to fix? – Kevin Cruijssen Sep 5 at 17:10
  • 1
    Ohh I see. That's fixed now, I even reduced it by one more byte. – user5434231 Sep 5 at 17:22

Haskell, 64 60 59 bytes

(""#)
a#s|l<-(:a)=<<s,w<-' ':a=l:[x|w<(' '<$s),x<-w#s++[l]]

Try it online!

a#s                         -- take a string of spaces 'a' and the input string 's'
 |l<-(:a)=<<s               -- let 'l' be the current line, i.e. the spaces in 'a'
                            -- appended to each char in 's'
  w<-' ':a                  -- let 'w' be 'a' with an additional space   
 =l                         -- return that 'l'
   :[   |w<(' '<$s)   ]     -- and, if 'w' is shorter than 's',
     x  ,x<-w#s++[l]        -- followed by a recursive call with 'w' 
                            -- and by another copy of 'l'

(""#)                       -- start with an empty 'a'

Bash, 115, 109, 105, 100, 97, 96, 92, 91, 90 bytes

-5 & -3 thanks to Kevin Cruissen

read s;for((c=f=1;f;c-=2*(f>=${#s}),f+=c))
{ printf '%-'${f}'.c' `grep -o .<<<"$s"`
echo
}

Try it online!


Note that since the \ is a shell escape char, the test case )}/\ should be entered with an extra \ like this: )}/\\.

  • Hi there. Is it possible to add a TIO-link with test case(s)? Also, I don't know Bash very well, but is it possible to remove the spaces after in and printf like in Python? – Kevin Cruijssen Sep 7 at 13:29
  • 1
    @KevinCruijssen, Thanks, see revised answer. I'm new to TIO-link however, and am not sure how to use multiple test cases, since this bash code only inputs a string, (i.e. just one line). The test cases all work however, though )}/\ must be single quoted like this <<< ')}/\' read s; ...etc. . The spaces after in and printf are needed. – agc Sep 7 at 13:47
  • Thanks. And a single test case for TIO is fine. It's mainly to verify if everything is working as expected, which indeed seems the case. +1 from me. :) – Kevin Cruijssen Sep 7 at 13:49
  • 1
    In your new version you can golf 5 more bytes like this. Spaces after for and do can be removed. f=1 can be changed to c=f=1. And f=f+c can be f+=c. – Kevin Cruijssen Sep 7 at 14:31
  • 1
    Oh, one more small thing to golf. Wasn't sure if it's possible in Bash, but apparently it is (one more reason why a TIO-link is handy ;) ), is by changing f!=0 to f in the for-loop. Just like in JavaScript and Python, 0 is falsey and every other positive/negative integer is apparently truthy in Bash. – Kevin Cruijssen Sep 7 at 14:49

Perl 6, 43 bytes

{(0....comb-1...0)>>.&{join ' 'x$^a,.comb}}

Try it online!

Returns a list of lines.

Explanation:

 {                                         }  # Anonymous code block
  (0....comb-1...0) # A list from
   0                  # 0
    ...               # to
       .comb-1        # the length of the input string -1
              ...     # back to
                 0    # 0
                   >>.&{                  }  # Map each number to
                        join        ,.comb   # Join the list of characters
                             ' 'x$^a         # With the number of spaces

C (gcc), 131 129 111 bytes

i;x;f(k,j)char*k,*j;{x=strlen(k)-1;for(i=0;i<x-~x;i+=puts(""))for(j=k;*j;)printf("%c%*s",*j++,i<x?i:2*x-i,"");}

Try it online!

-20 bytes thanks to ceilingcat!

#import<string.h>
i;x;f(k,j)char*k,*j;{x=strlen(k)-1;for(i=0;i<x-~x;i+=puts(""))for(j=k;*j;)printf("%c%*s",*j++,i<x?i:2*x-i,"");}

Try it online!

Or, if length can be accepted as a parameter:

C (gcc), 105 102 bytes

-1 byte thanks to ceilingcat!

i;x;f(k,x,j)char*k,*j;{for(i=!x--;i<x-~x;i+=puts(""))for(j=k;*j;)printf("%c%*s",*j++,i<x?i:2*x-i,"");}

Try it online!

  • @ceilingcat huh! – Conor O'Brien Sep 14 at 2:05
  • 1
    In your 102 bytes long golf, I think the global x is shadowed and thus redundantly declared. – Jonathan Frech Sep 19 at 22:50

PHP, 148 146 143 141 Bytes

function s($s){for(;$i<strlen($s);++$i)f($i,$s);for(--$i;--$i>=0;)f($i,$s);}function f($i,$s){echo chunk_split($s,1,str_repeat(' ',$i))."
";}

You can test it like this:

<?php
error_reporting(0);

$s = 1234567890;
function s($s){for(;$i<strlen($s);++$i)f($i,$s);for(--$i;--$i>=0;)f($i,$s);}function f($i,$s){echo chunk_split($s,1,str_repeat(' ',$i))."
";}

Output

1234567890
1 2 3 4 5 6 7 8 9 0 
1  2  3  4  5  6  7  8  9  0  
1   2   3   4   5   6   7   8   9   0   
1    2    3    4    5    6    7    8    9    0    
1     2     3     4     5     6     7     8     9     0     
1      2      3      4      5      6      7      8      9      0      
1       2       3       4       5       6       7       8       9       0       
1        2        3        4        5        6        7        8        9        0        
1         2         3         4         5         6         7         8         9         0         
1        2        3        4        5        6        7        8        9        0        
1       2       3       4       5       6       7       8       9       0       
1      2      3      4      5      6      7      8      9      0      
1     2     3     4     5     6     7     8     9     0     
1    2    3    4    5    6    7    8    9    0    
1   2   3   4   5   6   7   8   9   0   
1  2  3  4  5  6  7  8  9  0  
1 2 3 4 5 6 7 8 9 0 
1234567890

Sandbox

Expanded version

 function s($s){
    //loop upwards 0-10
    for(;$i<strlen($s);++$i) f($i,$s);
     //decrement so it's odd, from 9 loop downwards to 0
    for(--$i;--$i>=0;)f($i,$s);
 }
 //2nd function to save space
 function f($i,$s){
     //chunk it, split 1 char, insert $i number of spaces
     echo chunk_split($s,1,str_repeat(' ',$i))."
";}

Attempt 2, 92 bytes

after seeing @Titus answer I reduced mine to this:

for(;++$i<2*$e=strlen($s=$argn);)echo chunk_split($s,1,str_repeat(' ',~-$e-abs($i-$e)))."
";

I was trying to think of a way to use 1 loop, instead of 2... Believe it or not, I almost never use the for loop in "real" code. It was the ~ bitwise Not, that I was missing...

It's sill a tiny bit longer at 92 so I don't feel so bad. But I will put it in as a second attempt anyway.

$argn is the input from the command line

Run as pipe with -nR or try it online.

Sandbox

  • It seems to me that your first version would be 4 bytes shorter if you used a named function f instead of assigning an anonymous one to $f - function f( saves 2 bytes over $f=function(, and you save another byte every time you call f(...) instead of $f(...). Alternatively, you could capture the $s, saving 2 bytes - ($i)use($s) is 4 bytes longer than ($i,$s), but you save 3 bytes for each call to $f($i) instead of $f($s,$i); in languages with automatic capture, like JS, this is more often a viable saving, because you don't pay the penalty of the use statement. – IMSoP Sep 7 at 16:12
  • I do appreciate the help, I'm pretty new to code golf and don't really do it that much, one does get bored on the regular SO pages, though. I did think about using use but it feels longer, to do that sense $i is dynamic, it would have to be passed in by reference. So it has to be use(&$i) and the $i has to be defined before passing it by reference to $f. Which means setting it in the parent function, or before any other. For the function it could be function s($s,$i) and just know it has to be called with s($s,0) but it seems ugly, and that is around 11 bytes, use(&$i),$i – ArtisticPhoenix Sep 7 at 17:14
  • We could use $s though and change the \n to a real line return. That gets it to 143 2 from the line ending and 1 from use – ArtisticPhoenix Sep 7 at 17:31
  • Yes, I hadn't even considered putting $i into the use, because $s felt the "natural" capture, but it's always worth calculating the net saving. However, you can still save 2 bytes by just declaring a named function f instead of a closure: function s($s){for(;$i<strlen($s);++$i)f($i,$s);for(--$i;--$i>=0;)f($i,$s);}function f($i,$s){echo chunk_split($s,1,str_repeat(' ',$i))." ";} Extra functions like this are allowed according to this meta post: codegolf.meta.stackexchange.com/questions/7614/… – IMSoP Sep 8 at 9:06
  • Updated, saved a couple – ArtisticPhoenix Sep 8 at 11:27

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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