19
\$\begingroup\$

Continuing my It was just a bug challenge:

Input:

A string consisting of printable ASCII characters without white-spaces nor new-lines.

Output:

First turn the input into a palindrome by reverting the input, and adding it before itself, excluding the middle character (i.e. with an input 1234567890, it will becomes 0987654321234567890).

And then output this text:

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

(From the middle outward in both directions, each character is separated by one more space than the previous line.)

Challenge rules:

  • You need to print twice the length of the input, minus 3 lines. So with the input 1234567890, the output displayed above is 17 lines (length 10 * 2 - 3).
  • The input will only contain printable ASCII (excluding space, tab and new-line).
  • Trailing spaces are optional.
  • A single trailing new-line is optional.
  • (Additional) leading spaces or leading new-lines are not allowed.
  • You can assume the input will always be at least four characters long.
  • Unlike my It was just a bug challenge, both the input and output formats are flexible. So you are allowed to output the result as a String-array, String-list, 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, please add an explanation if necessary.

Test cases:

Input: 1234567890
Output:
0        9        8        7        6        5        4        3        2        1        2        3        4        5        6        7        8        9        0
         0       9       8       7       6       5       4       3       2       1       2       3       4       5       6       7       8       9       0
                  0      9      8      7      6      5      4      3      2      1      2      3      4      5      6      7      8      9      0
                           0     9     8     7     6     5     4     3     2     1     2     3     4     5     6     7     8     9     0
                                    0    9    8    7    6    5    4    3    2    1    2    3    4    5    6    7    8    9    0
                                             0   9   8   7   6   5   4   3   2   1   2   3   4   5   6   7   8   9   0
                                                      0  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9  0
                                                               0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
                                                                        0987654321234567890
                                                               0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
                                                      0  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9  0
                                             0   9   8   7   6   5   4   3   2   1   2   3   4   5   6   7   8   9   0
                                    0    9    8    7    6    5    4    3    2    1    2    3    4    5    6    7    8    9    0
                           0     9     8     7     6     5     4     3     2     1     2     3     4     5     6     7     8     9     0
                  0      9      8      7      6      5      4      3      2      1      2      3      4      5      6      7      8      9      0
         0       9       8       7       6       5       4       3       2       1       2       3       4       5       6       7       8       9       0
0        9        8        7        6        5        4        3        2        1        2        3        4        5        6        7        8        9        0

Input: ABCD
Output:
D  C  B  A  B  C  D 
   D C B A B C D
      DCBABCD
   D C B A B C D
D  C  B  A  B  C  D

Input: =>)}]
Output:
]   }   )   >   =   >   )   }   ]
    ]  }  )  >  =  >  )  }  ]
        ] } ) > = > ) } ]
            ]})>=>)}]
        ] } ) > = > ) } ]
    ]  }  )  >  =  >  )  }  ]
]   }   )   >   =   >   )   }   ]

Input: XXxxXX
Output:
X    X    x    x    X    X    X    x    x    X    X
     X   X   x   x   X   X   X   x   x   X   X
          X  X  x  x  X  X  X  x  x  X  X
               X X x x X X X x x X X
                    XXxxXXXxxXX
               X X x x X X X x x X X
          X  X  x  x  X  X  X  x  x  X  X
     X   X   x   x   X   X   X   x   x   X   X
X    X    x    x    X    X    X    x    x    X   X
\$\endgroup\$
4
  • \$\begingroup\$ Are an equal amount of leading spaces on every line OK? \$\endgroup\$
    – Adám
    Jul 5 '17 at 12:33
  • \$\begingroup\$ @Adám Sorry but no. Any number of trailing spaces are fine, but leading spaces not. I'll specify this rule in the challenge. \$\endgroup\$ Jul 5 '17 at 12:36
  • 2
    \$\begingroup\$ "You need to print the length of the input minus 3 lines." then "(length 10 * 2 - 3)". The first sentence says "no double", the second one says "double". So which is it? \$\endgroup\$ Jul 5 '17 at 13:20
  • \$\begingroup\$ @OlivierGrégoire Oops, first line should have contained 2x the length minus 3. Fixed \$\endgroup\$ Jul 5 '17 at 21:17

16 Answers 16

5
\$\begingroup\$

Charcoal, 14 bytes

E⁻Lθ¹⪫θ× ι‖O←↑

Try it online!

AST:

Program
├Print
│└E: Map
│ ├⁻: Difference
│ │├L: Length
│ ││└θ: Identifier θ
│ │└1: Number 1
│ └⪫: Join
│  ├θ: Identifier θ
│  └×: Product
│   ├' ': String ' '
│   └ι: Identifier ι
└‖O: Reflect overlap
 └Multidirectional
  ├←: Left
  └↑: Up
\$\endgroup\$
11
  • \$\begingroup\$ Might be 16 codepoints, but as UTF-8 Python 3 reports that it is 41 bytes. Which charset do you use to make it 16 bytes? \$\endgroup\$ Jul 5 '17 at 15:12
  • \$\begingroup\$ @JanusTroelsen It's a custom charset. \$\endgroup\$ Jul 5 '17 at 15:16
  • \$\begingroup\$ Huh, ⪫ works on strings? Must remember that for next time... \$\endgroup\$
    – Neil
    Jul 5 '17 at 15:31
  • \$\begingroup\$ @Neil Yeah it makes sense doesn't it? \$\endgroup\$ Jul 5 '17 at 15:32
  • \$\begingroup\$ Technically your edit is noncompeting because the relevant commit postdates the challenge. \$\endgroup\$
    – Neil
    Jul 10 '17 at 8:49
7
\$\begingroup\$

Japt, 22 21 bytes

¬Å£¬qYîÃy w ê y w ê ·

Test it online!

Explanation

The first 8 bytes generate the bottom-right quadrant of the pattern:

 ¬ Å  £    ¬ qYîÃ
Uq s1 mXY{Uq qYî} 

Uq                 : Split the input into characters.
   s1              : Slice off the first.
      mXY{      }  : Map each item X and index Y to
          Uq       :   the input split into chars,
             q     :   joined with
              Yî   :     Y spaces.

At this point we have an array of e.g. ["ABCD", "A B C D", "A B C D"]. Unfortunately, it takes 13 bytes to square this:

y w ê y w ê ·
y w ê y w ê qR
y                : Pad each line to the same length with spaces and transpose.
  w              : Reverse the array, and
    ê            : palindromize. Now we have the bottom half of the output transposed.
      y          : Transpose back.
        w ê      : Reverse and palindromize again, giving the full output.
            qR   : Join with newlines.
                 : Implicit: output result of last expression
\$\endgroup\$
5
  • \$\begingroup\$ Wish I'd thought to use transpose - nicely done :) \$\endgroup\$
    – Shaggy
    Jul 5 '17 at 13:56
  • \$\begingroup\$ Can I ask a question I'm scared to know the answer to? Are you and the rest here actually coding this out in its minified version? \$\endgroup\$
    – gdbj
    Jul 5 '17 at 15:41
  • \$\begingroup\$ If you dare. Probably not. \$\endgroup\$ Jul 5 '17 at 17:56
  • 1
    \$\begingroup\$ @gdbj I usually do... is that a bad sign? :P \$\endgroup\$ Jul 5 '17 at 18:19
  • \$\begingroup\$ @ETHproductions Was just telling a buddy that this is similar to real golf: frustrating to learn, strangely addicting, and demonstrating skill in it commands respect. \$\endgroup\$
    – gdbj
    Jul 5 '17 at 21:09
5
\$\begingroup\$

Python 3, 149 141 95 bytes

def f(s):l=len(s)-1;[print((' '*abs(i)).join(s[:0:-1]+s).center(2*l*l+1))for i in range(1-l,l)]

Try it online!

Thanks to @KevinCruijssen and @ETHproductions for saving some bytes

Special thanks to @notjagan for saving 46 bytes!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Changing l=len(s); to l=len(s)-1; and then changing all the values involving l (i.e. l-1 -> l; -l+2 -> -l+1; etc.) is 8 bytes shorter. Try it here. \$\endgroup\$ Jul 5 '17 at 12:45
  • 1
    \$\begingroup\$ -l+2 -> 2-l :) \$\endgroup\$ Jul 5 '17 at 12:48
  • \$\begingroup\$ Thanks @KevinCruijssen, unfortunately I cannot edit right now, can you please edit in? \$\endgroup\$
    – Mr. Xcoder
    Jul 5 '17 at 12:50
  • \$\begingroup\$ @KevinCruijssen Thanks a lot! \$\endgroup\$
    – Mr. Xcoder
    Jul 5 '17 at 12:55
  • 3
    \$\begingroup\$ Down to 95 bytes using center instead of the for loop! \$\endgroup\$
    – notjagan
    Jul 5 '17 at 13:56
5
\$\begingroup\$

05AB1E, 17 bytes

g<F¹RSðN×ýû})Rû.c

Try it online!

-1 thanks to kalsowerus.

\$\endgroup\$
2
  • \$\begingroup\$ You can save one byte by replacing .c.∊ with û.c \$\endgroup\$
    – kalsowerus
    Jul 6 '17 at 13:30
  • \$\begingroup\$ @kalsowerus And I knew there would be some way to use û...thanks! \$\endgroup\$ Jul 6 '17 at 13:36
5
\$\begingroup\$

JavaScript (ES6), 159 136 129 127 bytes

f=(i,x=1-(l=i.length-1),y=x<0?-x:x,[,...b]=i)=>l>x?''.padEnd(l*(l+~y))+[...b.reverse(),...i].join(''.padEnd(y))+`
`+f(i,x+1):''

Try it online! Explanation below

// This is a recursive function
// First, inputs and various variable initializations
// by using defaults
let func = (
  // Text input, will not be modified through recursion
  input,

  // Current line, for the first function call we start from -lines to +lines
  // It's roughly equivalent to lines*2 but this helps us computing the spacing
  // Also computing the total amount of lines
  currentLine = 1 - (totalLines = input.length - 1),

  // Getting the absolute value of the current line (like Math.floor)
  absCurrentLine = currentLine < 0 ? -currentLine : currentLine,

  // Getting the input without it's first letter, useful for the palidrome of the input
  [,...slicedInput] = input

// Base case, stopping the recursion if the current line
// is still below the total amount of lines
) => totalLines > currentLine

  // Leading spacing
  ? ''.padEnd(totalLines * (totalLines + ~absCurrentLine)) + 

  // Putting together the palindrome version and adding spaces between the chars
    [...slicedInput.reverse(), ...input].join(''.padEnd(absCurrentLine)) + `

  // Line return + recursion call
` + f(input, currentLine + 1)
  : ''

First entry to codegolf, I apologise in advance for any obvious mistakes.

Thanks to Justin Mariner for saving 23 bytes! Thanks to Craig Ayre for saving 11 bytes and for the bug report.

\$\endgroup\$
9
  • \$\begingroup\$ Nice first answer, +1 from me and welcome to PPCG. I'm not too familiar with Js, but is it possible to start x at -2 instead of -1, and change x<=l to ++x<=l so you can remove the x++ and save a byte? \$\endgroup\$ Jul 5 '17 at 14:48
  • \$\begingroup\$ I tried but didn't manage to because lines is entangled with the spacing as well so it ends up costing more bytes to make it all work again. But I'm fairly certain that there is both a better way to organise the code and add your suggestion. \$\endgroup\$
    – Saming
    Jul 5 '17 at 15:11
  • 1
    \$\begingroup\$ Welcome to PPCG, nice first post and explanation! Golfed down to 133 bytes here. Includes explanation of what was changed. \$\endgroup\$ Jul 5 '17 at 18:21
  • \$\begingroup\$ Unfortunately your output doesn't seem to quite match the expected output: see here \$\endgroup\$
    – Craig Ayre
    Jul 6 '17 at 13:19
  • 1
    \$\begingroup\$ This is great, I added your new function and updated the explanation \$\endgroup\$
    – Saming
    Jul 7 '17 at 9:51
4
\$\begingroup\$

SOGL V0.12, 22 18 bytes

ā,⁄H{,čFH@*∑Κ}▓±╬-

Try it Here!

Explanation:

ā                   push an empty array - canvas
 ,⁄H{        }      input length-1 times do
     ,                push the input
      č               chop it into chars
       FH@*           get the current iteration-1 amount of spaces
           ∑          join the chopped input with the spaces
            Κ         prepend it to the array
              ▓     space to a square
               ±    reverse each string in that list
                ╬-  quad-palindromize with 1 X and 1 Y overlap and without swapping characters
\$\endgroup\$
6
  • \$\begingroup\$ Is ╬- the four-way palindromize command? I was just over here wishing Japt had something like that... :P \$\endgroup\$ Jul 5 '17 at 12:03
  • 1
    \$\begingroup\$ @ETHproductions FWIW, is many things \$\endgroup\$
    – dzaima
    Jul 5 '17 at 12:29
  • \$\begingroup\$ I know, hence why I specified ╬-. But thanks, I couldn't find that page for some reason \$\endgroup\$ Jul 5 '17 at 12:29
  • \$\begingroup\$ @ETHproductions Oh. It only exists in the SOGLOnline copy of the interpreter :/ At some point I need to join the two together :| \$\endgroup\$
    – dzaima
    Jul 5 '17 at 12:42
  • \$\begingroup\$ Hmm...you should implement automatic F for if it's needed. \$\endgroup\$ Jul 5 '17 at 13:43
4
\$\begingroup\$

PHP, 145 131 bytes

It took some thinking to golf that additional byte; but it was worth it.

while($y<=2*$e=strlen($a=$argn)-1)echo($p=str_pad)("
",$e*($e-$d=abs($y++-$e))+1),chunk_split($a.substr(strrev($a),1),1,$p("",$d));

prints a leading newline. Run as pipe with -nR or try it online.

breakdown

while($y<=2*$e=strlen($a=$argn)-1)  # $e=length-1, loop through rows
                                        # 1. print linebreak and left padding
    echo($p=str_pad)("\n",$e*($e-$d=abs($y++-$e))+1),
        chunk_split(
            $a.substr(strrev($a),1)     # 2. palindromize input
            ,1,$p("",$d));              # 3. insert $e..0..$e spaces between characters

alternative solution, same length:

for($d=-$e=strlen($a=$argn)-1;$d<$e;)echo($p=str_pad)("
",$e*($e-$b=abs($d++))+1),chunk_split($a.substr(strrev($a),1),1,$p("",$b));
\$\endgroup\$
1
3
\$\begingroup\$

APL (Dyalog), 37 bytes

Requires ⎕IO←0 which is default on many systems.

{⍉m(2-d)↓⍉(m←⊖⍪1↓⊢)↑∊¨(1↓⍳d←≢⍵)↑¨¨⊂⍵}

{} anonymous function where the argument is represented by

()↑¨¨⊂⍵ for each (¨) of the following numbers take () that many characters from each (¨) of the entire () argument, padding with spaces as necessary:

  ≢w the number of characters in the argument

  d← store that in d

   that many ɩndices (0 … d − 1)

  1↓ drop one (the zero)

∊¨ϵnlist (flatten) each

 raise the rank (convert the list of lists into a matrix)

(m←) apply the following tacit function m, defined as:

   the upside-down argument

   on top of

  1 one [row]

   dropped from

   the argument

 transpose

()↓ drop:

  2-d = −(d − 2), i.e. d − 2 rows from the bottom

m apply m

 transpose

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Java (OpenJDK 8), 201 196 bytes

s->{for(int l=s.length()-1,i=-l,x=0;++i<l;x+=i<0?l:-l)System.out.printf("%1$"+(x<1?"":x)+"s"+s.join("%1$"+(i<0?-i:i>0?i:"")+"s",(new StringBuffer(s.substring(1)).reverse()+s).split(""))+"%n","");}

Try it online!

It's the same idea as the one I used for the previous challenge, except that the generator string is now a tad longer and with more hard to handle cases.

%1$Ns0%1$Ns9%1$Ns8%1$Ns7%1$Ns6%1$Ns5%1$Ns4%1$Ns3%1$Ns2%1$Ns1%1$Ns2%1$Ns3%1$Ns4%1$Ns5%1$Ns6%1$Ns7%1$Ns8%1$Ns9%1$Ns0%n
\$\endgroup\$
3
\$\begingroup\$

Python 3, 134 124 bytes

f=lambda s:'\n'.join([' '*(len(s)-1)*abs(len(s)-abs(i)-2)+(' '*abs(i)).join(s[::-1]+s[1:]) for i in range(2-len(s),len(s)-1)])

Try it online!

First post to PPCG after lurking for a while. Looking for any suggestions/advice!


Thanks to @LyricLy and @Łukasz Rogalski for improvements!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You don't have to print the output inside the function, output can be given in a return value. Also, you don't have to count the f= in the bytecount, simply providing an anonymous function is fine. \$\endgroup\$
    – LyricLy
    Jul 6 '17 at 3:27
  • 1
    \$\begingroup\$ Also, -len(s)+2 is just 2-len(s), one less byte. \$\endgroup\$ Jul 6 '17 at 6:21
  • \$\begingroup\$ Thank you @Łukasz Rogalski and @LyricLy; you have saved me 10 bytes! \$\endgroup\$ Jul 6 '17 at 14:12
3
\$\begingroup\$

Haskell, 177 163 bytes

import Data.List
k n=[1..n]>>" "
f s=let n=length s in map(\x->(k(((n-1)*(n-(abs x)))))++(intercalate (k(abs x))$map(\z->[z])$((++)=<<reverse.tail) s))[n,n-1.. -n]

The function f is the challenge function and returns a list of strings ([String]), using unlines on it should provide the same visual output as the test cases (main = putStr $ unlines $ f "test string" to compile it).

Try it online!

-14 bytes thanks to @nimi

\$\endgroup\$
1
  • 1
    \$\begingroup\$ k can be defined as k n=[1..n]>>" " and p as p=(++)=<<reverse.tail (you can even inline this definition). \$\endgroup\$
    – nimi
    Jul 6 '17 at 17:29
2
\$\begingroup\$

Mathematica, 141 bytes

Column[Join[Reverse@(s=Row/@Table[Riffle[Reverse@Rest@b~Join~b,""<>Table[" ",i]],{i,0,Length[b=Characters@#]-1}]),Rest@s],Alignment->Center]&
\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 100 90 bytes

s->(l=length(s)-2;[' '^(-~l*(l-j))*prod(s[abs(i)+1]*' '^j for i=~l:l+1) for j=abs.(-l:l)])

Try it online!

-10 bytes thanks to @KevinCruijssen

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice answer! Some small things to golf: (l+1) can be -~l and in -l-1 can be in~l for -5 bytes. (Here is the relevant tip. And if you haven't seen it yet, tips for golfing in Julia might be interesting to read through as well.) \$\endgroup\$ Nov 5 '20 at 17:34
  • \$\begingroup\$ You've now accidently used ~-l (l-1) instead of -~l (l+1) in your latest edit, so the output is incorrect.. :) \$\endgroup\$ Nov 6 '20 at 12:01
  • \$\begingroup\$ true, thanks for checking ;) \$\endgroup\$
    – MarcMush
    Nov 6 '20 at 12:50
1
\$\begingroup\$

Japt -R, 15 bytes

ÊÆÔ¬qXç)êÃÔÅê û

Try it

ÊÆÔ¬qXç)êÃÔÅê û     :Implicit input of string
Ê                   :Length
 Æ                  :Map each X in the range [0,length)
  Ô                 :  Reverse U
   ¬                :  Split
    q               :  Join with
     Xç             :    X spaces
       )            :  End join
        ê           :  Palindromise
         Ã          :End map
          Ô         :Reverse
           Å        :Slice off first element
            ê       :Palindromise
              û     :Centre pad each element with spaces to the length of the longest
                    :Implicit output joined with newlines
\$\endgroup\$
1
\$\begingroup\$

Canvas, 14 bytes

L╷rH ×⁸;*∔}↔↕┼

Try it here!

Explanation

L|rH ×⁸;*∔}↔↕┼
L              length of input
 |r            decrement, make range [0..n-1]
   H           create an empty art object, start a loop with i
     ×         repeat space i times
      ⁸;       swap with the input
        *      join input with i spaces
         ∔     add to the bottom of the previous iteration
          }    close the loop
           ↔↕  mirror horizontally and vertically
             ┼ quad palindromize with 1 character overlap
\$\endgroup\$
1
  • \$\begingroup\$ Yep, looks great now. I'll remove my comments. +1 from me. Would you mind adding an explanation? \$\endgroup\$ Nov 6 '20 at 14:03
0
\$\begingroup\$

05AB1E, 14 bytes

¦ε\RðN×ýû}Rû.c

Input as a list of characters.

Try it online or verify all test cases.

14 bytes alternative:

ā¨RjJíðδÜ€ûû.c

Also takes a list of characters as input.

Try it online or verify all test cases.

Explanation:

¦              # Remove the first item of the (implicit) input-list
               # (could have removed the last as alternative as well)
 ε             # Map over each character:
  \            #  Discard the character
   R           #  Reverse the (implicit) input-list
     N         #  Push the 0-based map-index
    ð ×        #  Repeat a space character that many times as string
       ý       #  Join the reversed input-list with this spaces-string as delimiter
        û      #  Palindromize the entire string
 }R            # After the map: reverse the resulting list
   û           # Palindromize this entire list
    .c         # And centralize it, which also implicitly joins by newlines
               # (after which the result is output implicitly)

ā              # Push a list in the range [1, (implicit) input-length]
 ¨             # Remove the last item to make the range [1, input-length)
  R            # Reverse the list to (input-length, 1]
   j           # Pad each character in the (implicit) input-list with leading spaces so
               # the string lengths become equal to the current integer
    J          # Join each inner list of strings together to a single string
     í         # Reverse each string
       δ       # Map over each string:
      ð Ü      #  And remove all trailing spaces
         €û    # Palindromize each string
           û   # Palindromize the entire list
            .c # And centralize it, which also implicitly joins by newlines
               # (after which the result is output implicitly)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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