Given a string whose length is divisible by 4, make a triangle as demonstrate below.

If the string is abcdefghijkl, then the triangle would be:

   a
  b l
 c   k
defghij

If the string is iamastringwithalengthdivisiblebyfour, then the triangle would be:

         i
        a r
       m   u
      a     o
     s       f
    t         y
   r           b
  i             e
 n               l
gwithalengthdivisib

If the string is thisrepresentationisnotatriangle, then the triangle would be:

        t
       h e
      i   l
     s     g
    r       n
   e         a
  p           i
 r             r
esentationisnotat

Notes

  • The string will only consist of characters from a to z.
  • Leading/Trailing whitespaces and newlines are allowed as long as the shape is not broken.
  • A list of strings as output is allowed.

This is . Shortest answer in bytes wins. Standard loopholes apply.

share|improve this question

17 Answers 17

Charcoal, 25 22 bytes

A÷Lθ⁴λ↙✂θ⁰λ→✂θλ±λ↖✂θ±λ

Try it online! Link is to verbose version of code. Simply slices the string into three parts and prints them in the appropriate directions. Edit: Saved 3 bytes by using integer division and slicing.

share|improve this answer
    
What do the s do? – Erik the Outgolfer Jun 22 at 9:19
    
@EriktheOutgolfer That's the new Slice operator. – Neil Jun 22 at 9:52

05AB1E, 23 bytes

ćsIg4÷GćsÁćsŠN·<ú«s}».C

Try it online!

Explanation

ć                        # extract head of input
 s                       # swap the remaining string to top of stack
  Ig4÷G                  # for N in [1...len(input)/4-1] do:
       ć                 # extract head
        sÁ               # swap remaining string to top of stack and rotate right
          ć              # extract head
           sŠ            # reorder stack as tail, head, remaining
             N·<ú        # prepend N-1 spaces to tail
                 «s      # concatenate with head and swap remaining string to top
                   }     # end loop
                    ».C  # join by newlines and center
share|improve this answer

JavaScript (ES6), 119 117 108 105 bytes

s=>(l=s.length/4,S=' ',g=([c,...s],p)=>S.repeat(l)+c+(l--?p+s.pop()+`
`+g(s,p?p+S+S:S):s.join``))(s+S,'')

Formatted and commented

s => (                            // given the input string s:
  l = s.length / 4,               // l = length of side edge - 1
  S = ' ',                        // S = space (defining S costs 6 bytes but saves 7)
  g = (                           // g = recursive function which takes:
       [c,                        //   - c = next character
           ...s],                 //   - s = array of remaining characters
                  p) =>           //   - p = middle padding string
    S.repeat(l) + c + (           // append left padding + left character
      l-- ?                       // if side edges are not complete:
        p + s.pop() + '\n' +      //   append middle padding + right character + Line Feed
        g(s, p ? p + S + S : S)   //   and do a recursive call with updated middle padding
      :                           // else:
        s.join``                  //   append all remaining characters and stop recursion
    )                             //   (this is the bottom edge)
  )(s + S, '')                    // initial call to g()

Test cases

let f =

s=>(l=s.length/4,S=' ',g=([c,...s],p)=>S.repeat(l)+c+(l--?p+s.pop()+`
`+g(s,p?p+S+S:S):s.join``))(s+S,'')

console.log(f('abcdefghijkl'))
console.log(f('iamastringwithalengthdivisiblebyfour'))
console.log(f('thisrepresentationisnotatriangle'))

share|improve this answer

C#, 260 bytes

namespace System{using static Console;class P{static void Main(){var d=ReadLine();int e=d.Length/4,x=e,y=0,g=0,i=0;Action<int,int>a=(p,q)=>{SetCursorPosition(p,q);Write(d[g++]);};for(;i<e;i++)a(x--,y++);for(i=0;i<e*2;i++)a(x++,y);for(i=0;i<e;i++)a(x--,y--);}}}

Really wanted to use SetCursorPosition.

Ungolfed:

namespace System {
    using static Console;

    class P {
        static void Main() {
            var d = ReadLine();
            int e = d.Length / 4, x = e, y = 0, g = 0, i = 0;
            Action<int, int> a = (p, q) => { SetCursorPosition(p, q); Write(d[g++]); };
            for (; i < e; i++)
                a(x--, y++);
            for (i = 0; i < e * 2; i++)
                a(x++, y);
            for (i = 0; i < e; i++)
                a(x--, y--);
        }
    }
}
share|improve this answer
    
Pardon my ignorance, but what is the purpose of Action in your solution? Is it just less bytes than a void function? – confusedandamused Jun 22 at 18:40
1  
@confusedandamused I'm used to writing single function answers so didn't even consider putting the function normally, it will be shorter though. – LiefdeWen Jun 22 at 22:50

GNU sed, 178 + 1 = 179 bytes

+1 byte for -r flag. Takes input on STDIN.

h
s/./;/g
s/^(;+)..\1$/ \1/
:
s/( *)(;+);;/\1 \2\n\1;;/
t
s/;;/; ;/
:A
s/(( +);\n +);;/\1;\2  ;/
tA
G
s/;(.*\<)(.)/\2\1/
:B
s/;( +);(.*)(\<.)(.*)(.)/\3\1\5\2\4/
tB
s/;\n(.)/\1\n/

Try it online!

Explanation

The program works in two phases. In the phase 1, it creates the top of the triangle. Suppose the input is abcdefghijklmnop. First, it's copied the hold space. Then each character is replaced with ;, the second half-plus-one is deleted, and a space is prepended, leaving _;;;;;;; where _ is a space.

Now, working from the end, the string is split into pairs, with an increasing number of spaces prepended:

┆ ;;;;;;;
┆    
┆  ;;;;;
┆ ;;

┆   ;;;
┆  ;;
┆ ;;

┆    ;
┆   ;;
┆  ;;
┆ ;;

Then an increasing number of spaces is inserted between each pair:

┆    ;
┆   ; ;
┆  ;;
┆ ;;

┆    ;
┆   ; ;
┆  ;   ;
┆ ;;

┆    ;
┆   ; ;
┆  ;   ;
┆ ;     ;

In phase 2, the ;s are replaced with the letters of the string. First the letters are appended from the hold space, and the first ; is replaced with the first letter, which is deleted:

┆    ;
┆   ; ;
┆  ;   ;
┆ ;     ;
┆abcdefghijklmnop

┆    a
┆   ; ;
┆  ;   ;
┆ ;     ;
┆bcdefghijklmnop

Finally each pair of ;s is replaced with the first and last of the remaining letters, which are deleted:

┆    a
┆   b p
┆  ;   ;
┆ ;     ;
┆cdefghijklmno

┆    a
┆   b p
┆  c   o
┆ ;     ;
┆defghijklmn

┆    a
┆   b p
┆  c   o
┆ d     n
┆efghijklm

There's one special case, which is four-character input. In that case, the result is:

┆ ;
┆abcd

...and a simple substitution fixes it:

┆ a
┆bcd

Here's the annotated code:

# Copy pattern space to hold space
h
# Replace every character with `;`
s/./;/g

# Delete the second half+1 characters, prepend a space
s/^(;+)..\1$/ \1/

# Split the string into pairs, each time prepending one more space than the previous pair
:
  s/( *)(;+);;/\1 \2\n\1;;/
  t

s/;;/; ;/  # Put a space between the first pair

# Put increasing spaces between subsequent pairs
:A
  s/(( +);\n +);;/\1;\2  ;/
  tA

# Append hold space to pattern space
G

# Replace the first `;` with the first letter and remove the letter
s/;(.*\<)(.)/\2\1/

# Replace subsequent pairs of `;` with the first and last remaining letters, respectively
:B
  s/;( +);(.*)(\<.)(.*)(.)/\3\1\5\2\4/
  tB

# Special case: Four characters, ;\nabcd -> a\nbcd
s/;\n(.)/\1\n/
share|improve this answer

C#, 172 bytes

int i=0,n=s.Length;var p="";p=new string(' ',n/4)+s[i]+"\r\n";for(i=1;i<n/4;i++){p+=new string(' ',n/4-i)+s[i]+new string(' ',i*2-1)+s[n-i]+"\r\n";}p+=s.Substring(i,n/2+1);

Try it online!

share|improve this answer

Mathematica, 164 bytes

(b=Length[c=Characters@#];k=Column[#,Alignment->Center]&;T=Table;k@{#&@@c,k@T[""<>{c[[i+2]],T[" ",2i+1],c[[-i-1]]},{i,0,(a=b/4)-2}],""<>T[c[[i]],{i,a+1,b/2+1+a}]})&


input

["iamastringwithalengthdivisiblebyfour"]

share|improve this answer
    
We all know that [[1]] can be replaced with #&@@. – user202729 Jun 21 at 13:47
    
you are all so smart sweeties! – Jenny_mathy Jun 21 at 13:52
    
    
When you find yourself doing @(...), just do [...] instead. And I haven't tested but you can probably save another byte by giving Column a name (or maybe even to Column[#,Alignment->Center]& to avoid q) and then by putting all the remaining variables into the first argument of the outer Column (to save the surrounding parentheses). – Martin Ender Jun 21 at 14:00
    
Thank you Martin! – Jenny_mathy Jun 21 at 14:05

Python 2, 100 97 96 bytes

  • Jacoblaw saved 1 byte: integer division is unnecessary
a=input()+" "
k=j=len(a)/4
while j:print j*" "+a[0]+(2*(k-j)-1)*" "+a[-1];a=a[1:-1];j-=1
print a

Try it online!

Explanation:

One smart thing I've done here is padded the input with a space at the end, such that the first character pairs with it and this can be pushed into the loop (and since trailing whitespaces are allowed)

abcdefghijkl[space]   
To print [0] [-1]            Output=>[spaces]a[another_calculated_spaces(=0 here)][space]
Strip at both ends(a[1:-1])  
bcdefghijkl                
To print [0] [-1]            Output=>[spaces]b[another_calculated_spaces]l
Strip at both ends(a[1:-1])
and so on.

The number of loops to follow is associated with len(word)//4. In the final step, the whole remaining string is printed(this forms the base of the triangle). The spaces follow a simple pattern; the first set of spaces go-on decreasing by 1, while second set of spaces go on increasing by 2.

share|improve this answer
1  
Can you shave off a byte by not doing integer division? Since a will always be a multiple of 4. // -> / – jacoblaw Jun 21 at 17:01
    
Thank you, I am surprised it is not throwing any errors even for [inputs with length not divisible by 4] [tio.run/… – officialaimm Jun 21 at 17:11
1  
That's because in Python 2, division is integer by default. That was canged in Python 3. – CalculatorFeline Jun 21 at 17:57

Octave, 87 bytes

@(s,x=(n=nnz(s))/4)[[' ';flip(diag(s(1:x))')]' [' ';diag(s(n:-1:n-x+2))];s(x+1:n-x+1)];

*In a windows machine the above code produces the correct result however in tio I added some code to correct it.

Explanation:

[' ';flip(diag(s(1:x))')]'        %left side
[' ';diag(s(n:-1:n-x+2))]         %right side
s(x+1:n-x+1)                      %bottom side

Try it online!

share|improve this answer

Haskell, 136 bytes

i#x=x<$[1..i]
f s|let h=div l 4;l=length s=unlines$[(h-i)#' '++(s!!i):(2*i-1)#' '++[(s++" ")!!(l-i)]|i<-[0..h-1]]++[drop h$take(l-h+1)s]

Try it online!

share|improve this answer

C 225 bytes

p(c){putchar(c);}S(n){while(n--)p(' ');}main(int c,char**v){int i= strlen(v[1]),n=i/4,r;char*s=v[1],*e=&s[i-1];S(n);p(*s++);p('\n');for (r=1;r<n;r++){S(n-r);p(*s++);S(2*r-1);p(*e--);p('\n');}e++;while (s!=e)p(*s++);p('\n');}

explained

p(c){putchar(c);}        // p is alias for putchar
S(n){while(n--)p(' ');}  // S prints n spaces
main(int c,char**v){
    int i= strlen(v[1]), // counter
        n=i/4,           // num rows in figure - 1
        r;               // current row 
    char*s=v[1],         // start char
        *e=&s[i-1];      // end char
    S(n);p(*s++);p('\n');// print first row
    for (r=1;r<n;r++){ 
        S(n-r);p(*s++);S(2*r-1);p(*e--);p('\n'); // print middle rows
    }
    e++;while (s!=e)p(*s++);p('\n'); // print last row
}
share|improve this answer

PHP>=7.1, 122 Bytes

for(;$i*2<$w=strlen($a=$argn)/2;$e=$a[-++$i])echo str_pad(str_pad($a[$i],$i*2).$e,$w+1," ",2),"
";echo substr($a,$i,$w+1);

PHP Sandbox Online

PHP>=7.1, 124 Bytes

for(;$i*2<$w=strlen($a=$argn)/2;$e=$a[-++$i],$s.=$s?"  ":" ")echo str_pad("",$w/2-$i)."$a[$i]$s$e
";echo substr($a,$i,$w+1);

PHP Sandbox Online

share|improve this answer

AWK, 129 bytes

{n=split($0,a,"")
printf"%"(w=n/4+1)"s\n",a[++i]
for(;++i<w;)printf"%"(w-i+1)"s%"2*i-2"s\n",a[i],a[n-i+2]
$0=substr($0,i,i+w-1)}1

Try it online!

I should think this could be golfed a bit more, just not seeing it.

share|improve this answer

Ruby, 106 bytes

i=-1
s= ~/$/
sub /./,"#{' '*l=s/4}\\0
"
(l-1).times{sub /^(\w)(.*)(.)/,"#{' '*l-=1}\\1#{' '*i+=2}\\3
\\2"}

Try it online!

share|improve this answer

Retina, 99 bytes

^(.)(?=(....)+)
$#2$*  $1¶$#2$* 
( ( *).)(.*)(.)$
$1 $4¶$2$3
+`(( +).¶ ( *).)(.*)(.)$
$1$2  $5¶$3$4

Try it online! Explanation: The first two stages generate the first two lines, but after that no special-casing is necessary and each subsequent line can be generated automatically:

thisrepresentationisnotatriangle

        t
       hisrepresentationisnotatriangle

        t
       h e
      isrepresentationisnotatriangl

        t
       h e
      i   l
     srepresentationisnotatriang

...

        t
       h e
      i   l
     s     g
    r       n
   e         a
  p           i
 r             r
esentationisnotat
share|improve this answer

Python 3, 120 bytes

First golf, figured I might as well learn some Python along the way.

a=input()
l=len(a)//4
print(l*" "+a[0])
for i in range(1,l):print((l-i)*" "+a[i]+(2*i-1)*" "+a[4*l-i])
print(a[l:3*l+1])

Try it online!

Explanation:

The first character is printed by itself after len(a)//4 spaces, then the first and last i-th characters starting from the second are printed, separated by 2*i - 1 spaces.

Finally, the remaining substring is printed.

share|improve this answer
    
Welcome to PPCG! You can learn from this solution. – Leaky Nun Jun 22 at 14:27

Java 8, 213 bytes

s->{int n=s.length()/4,i;String r=s(n)+s.charAt(0)+"\n";for(i=1;i<n;r+=s(n-i)+s.charAt(i)+s(i*2-1)+s.charAt(n*4-i++)+"\n");return r+s.substring(i,n*2+i+1);}String s(int n){String r="";for(;n-->0;r+=" ");return r;}

Explanation:

Try it here.

s->{                           // Method (1) with String parameter and String return-type
  int n=s.length()/4,          //  The length of the input divided by 4
      i;                       //  And an index-integer
  String r=                    //  Result-String which starts as:
           s(n)                //   Trailing spaces
           +s.charAt(0)+"\n";  //   + the first character and a new-line
  for(i=1;i<n;                 //  Loop from `1` to `n`
      r+=                      //   And append the result-String with:
         s(n-i)                //    Trailing spaces
         +s.charAt(i)          //    + the character of the left diagonal line
         +s(i*2-1)             //    + center spaces
         +s.charAt(n*4-i++)    //    + the character of the right diagonal line
         +"\n"                 //    + a new-line
  );                           //  End of loop
  return r                     //  Return the result-String
         +s.substring(i,n*2+i+1);
                               //   + the bottom part of the triangle
}                              // End of method (1)

String s(int n){               // Method (2) with integer parameter and String return-type
  String r="";                 //  Result-String
  for(;n-->0;r+=" ");          //  Append the result-String with `n` spaces
  return r;                    //  Return the result-String
}                              // End of method (2)
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.