42
\$\begingroup\$

Given a non-empty string s, with even length, and a positive integer n, representing its height, compose a pyramid using the following rules:

The pyramid should contain n non-empty lines; trailing newlines are allowed. For each 1 <= i <= n, the i-th line should contain the string with each individual character repeated in-place i times; abcd repeated 3 times as such becomes aaabbbcccddd. Each line should be centered with padding spaces so that the middle of each line is vertically aligned. Trailing spaces at the end of each line are permitted. You can also have up to one leading newline but no other whitespace before the first line.

The input string is not guaranteed to be a palindrome.

Test Case

s = 'o-o  o-o', n = 10:

                                    o-o  o-o                                    
                                oo--oo    oo--oo                                
                            ooo---ooo      ooo---ooo                            
                        oooo----oooo        oooo----oooo                        
                    ooooo-----ooooo          ooooo-----ooooo                    
                oooooo------oooooo            oooooo------oooooo                
            ooooooo-------ooooooo              ooooooo-------ooooooo            
        oooooooo--------oooooooo                oooooooo--------oooooooo        
    ooooooooo---------ooooooooo                  ooooooooo---------ooooooooo    
oooooooooo----------oooooooooo                    oooooooooo----------oooooooooo
\$\endgroup\$
8
  • 1
    \$\begingroup\$ Sandbox Post created by user42649, which was my account until it got deleted. \$\endgroup\$
    – hyper-neutrino
    Jun 21, 2017 at 0:19
  • \$\begingroup\$ Can the output for a function on this question be a list of strings, each representing a line, or should it be joined by newlines? \$\endgroup\$
    – notjagan
    Jun 21, 2017 at 0:46
  • 8
    \$\begingroup\$ Output a pyramid You surely mean a highway! \$\endgroup\$
    – Luis Mendo
    Jun 21, 2017 at 8:32
  • 3
    \$\begingroup\$ @QBrute Na. Was made by a Goa'uld :) \$\endgroup\$
    – theblitz
    Jun 21, 2017 at 9:41
  • 1
    \$\begingroup\$ @LuisMendo Better? ;) :P \$\endgroup\$
    – hyper-neutrino
    Jun 22, 2017 at 1:05

33 Answers 33

12
\$\begingroup\$

05AB1E, 9 bytes

γ².D)ƶJ.C

Try it online!


γ was, in no short amount, inspired by Adnan's answer; but S would also work.


γ          # Split into runs.    | ['0','-','0']
 ².D)      # Push n times.       | [['0','-','0'],['0','-','0'],['0','-','0']]
     ƶ     # Lift by index.      | [['0','-','0'],['00','---','00'],['000','---','000']]
      J    # Inner join.         | ['0-0','00--00','000---000']
       .C  # Center.             | Expected output.
\$\endgroup\$
2
  • \$\begingroup\$ I can't believe someone actually downvoted your mistaken post :/ \$\endgroup\$ Jun 21, 2017 at 18:06
  • 1
    \$\begingroup\$ @JonathanAllan the frequency of my avoidable mistakes deserves negativity to some degree. \$\endgroup\$ Jun 21, 2017 at 18:08
12
\$\begingroup\$

05AB1E, 11 bytes

F²γN>×J}».C

Uses the 05AB1E encoding. Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ It starts going funky with inputs above 168. otherwise great! \$\endgroup\$
    – tuskiomi
    Jun 21, 2017 at 16:56
  • \$\begingroup\$ @carusocomputing » joins the inner arrays by spaces. Replacing it by J should work (and I think you should post that as a different answer). \$\endgroup\$
    – Adnan
    Jun 21, 2017 at 17:58
  • \$\begingroup\$ Ah! Has it always been that way? If so, cool, if not I must've missed that. Thanks, will do. \$\endgroup\$ Jun 21, 2017 at 18:01
8
\$\begingroup\$

Jelly, 14 13 bytes

LH×Ḷ}Ṛ⁶ẋżxЀY

Try it online!

How it works

LH×Ḷ}Ṛ⁶ẋżxЀY  Main link. Arguments: s (string), n (integer)

L              Get the length l of s.
 H             Halve it, yielding l/2.
   Ḷ}          Unlength right; yield [0, ... n-1].
  ×            Compute [0, l/2, ..., l(n-1)/2].
     Ṛ         Reverse; yield [l(n-1)/2, ..., l/2, 0].
      ⁶ẋ       Space repeat; create string of that many spaces.
         xЀ   Repeat in-place each; repeat the individual characters of s
               1, ..., n times, yielding an array of n strings.
        ż      Zipwith; pair the k-th string of spaces with the k-th string of 
               repeated characters of s.
            Y  Sepatate the resulting pairs by linefeeds.
\$\endgroup\$
0
8
\$\begingroup\$

C# (.NET Core), 139 137 136 130 bytes

using System.Linq;s=>n=>Enumerable.Range(0,n).Select(i=>"".PadLeft((n+~i)*s.Length/2)+string.Concat(s.Select(c=>new string(c,i))))

Try it online!

Returns an enumeration of strings with the lines of the drawing. Once joined the result is like this:

                        ಠ_ಠ  ಠ_ಠ
                    ಠಠ__ಠಠ    ಠಠ__ಠಠ
                ಠಠಠ___ಠಠಠ      ಠಠಠ___ಠಠಠ
            ಠಠಠಠ____ಠಠಠಠ        ಠಠಠಠ____ಠಠಠಠ
        ಠಠಠಠಠ_____ಠಠಠಠಠ          ಠಠಠಠಠ_____ಠಠಠಠಠ
    ಠಠಠಠಠಠ______ಠಠಠಠಠಠ            ಠಠಠಠಠಠ______ಠಠಠಠಠಠ
ಠಠಠಠಠಠಠ_______ಠಠಠಠಠಠಠ              ಠಠಠಠಠಠಠ_______ಠಠಠಠಠಠಠ
  • 2 bytes saved thanks to Kevin Cruijssen!
  • 1 byte saved thanks to Value Ink!
  • 6 bytes saved thanks to LiefdeWen!
\$\endgroup\$
10
  • 1
    \$\begingroup\$ You can save two bytes by removing the parenthesis at (n-i-1)*s.Length/2. And I like your test cases. +1 :) \$\endgroup\$ Jun 21, 2017 at 8:04
  • 10
    \$\begingroup\$ ಠ_ಠ intensifies \$\endgroup\$ Jun 21, 2017 at 19:25
  • 1
    \$\begingroup\$ Obligatory "~i is equivalent to -i-1", so you can save a byte by changing (n-i-1) to (n+~i). \$\endgroup\$
    – Value Ink
    Jun 22, 2017 at 9:37
  • 1
    \$\begingroup\$ and you can use currying so s=>n=>... for another byte \$\endgroup\$
    – LiefdeWen
    Jun 22, 2017 at 11:18
  • 1
    \$\begingroup\$ @CarlosAlejo Sorry for posting seperate edits but you can also replace new string(' '... with "".PadLeft(... \$\endgroup\$
    – LiefdeWen
    Jun 22, 2017 at 11:34
7
\$\begingroup\$

Cheddar, 71 64 bytes

Saved 7 bytes thanks to @ValueInk

(s,n)->(1|>n=>i->(s.len*(n-i)/2)*" "+s.sub(/./g,"$&"*i)).asLines

Try it online! I will add explanation in a bit

Explanation

(string, count)->(
   1 |> count          // 1..count, the amount of rep/char per line
     => i -> (         // Map over the range       
        s.len*(n-i)/2  // Calculate amount of spaces and repeat by it.
     )*" "
     + s.sub(/./g,"$&"*i) // replace each character, duplicate the amount of times `*i`
).asLines              // return the above joined with newlines
\$\endgroup\$
1
  • \$\begingroup\$ No problem! I wonder if Cheddar has a center function that you can use like I have on my Ruby answer, because that could potentially save bytes as well. \$\endgroup\$
    – Value Ink
    Jun 21, 2017 at 2:17
5
\$\begingroup\$

Ruby, 58 bytes

->s,n{(1..n).map{|i|s.gsub(/./){$&*i}.center s.size*n}*$/}

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Python 2, 75 77 bytes

s,n=input()
for i in range(n):print''.join(c*-~i for c in s).center(len(s)*n)

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Dang, I had nearly the same answer, but I was unsure whether a function could return a list of lines. If so, I'll post mine as a separate answer, but if not it would be too similar to post. \$\endgroup\$
    – notjagan
    Jun 21, 2017 at 0:56
  • 3
    \$\begingroup\$ Wow, there's a center builtin? I really need to read the docs sometimes :P \$\endgroup\$
    – hyper-neutrino
    Jun 21, 2017 at 0:59
  • \$\begingroup\$ Returns the wrong output; this has a leading blank line followed by n-1 rows. \$\endgroup\$
    – Value Ink
    Jun 21, 2017 at 2:20
  • \$\begingroup\$ You have also some leading whitespaces before the last line, is that allowed? \$\endgroup\$
    – Charlie
    Jun 21, 2017 at 8:18
  • \$\begingroup\$ @FryAmTheEggman that might be true, but it's still returning 9 lines of pyramid when the input is 10... \$\endgroup\$
    – Value Ink
    Jun 21, 2017 at 8:30
5
\$\begingroup\$

Java 11, 188 186 185 183 181 173 171 133 bytes

s->n->{var r="";for(int l=s.length()/2,x=l*n,i=0;i++<n;r+="\n"){r+=" ".repeat(x-i*l);for(var c:s.split(""))r+=c.repeat(i);}return r;}

-2 bytes (185 → 183) due to a bug-fix (it was outputting n+1 lines instead of n). Doesn't happen often that a bug-fix saves bytes. :)
-2 bytes (183 → 181) thanks to @OlivierGrégoire
-2 bytes (173 → 171) thanks to @ceilingcat

Try it online.

Explanation:

s->n->{                    // Method with String & integer parameters and String return
  var r="";                //  Return-String, starting empty
  for(int l=s.length()/2,  //  Halve the length of the input-String
          x=l*n,           //  Set `x` to halve the length multiplied by the input
          i=0;i++<n;       //  Loop `i` in the range (0,n):
      r+="\n"){            //    And after every iteration, add a new-line
    r+=" ".repeat(x-i*l);  //   Add the appropriate amount of trailing spaces
    for(var c:s.split("")) //   Inner loop over the characters of the String:
      r+=c.repeat(i);}     //    Repeat each character `i` amount of times
  return r;}               //  Return the result-String
\$\endgroup\$
3
  • 1
    \$\begingroup\$ If you move your ints first, you can declare r="",q=s.format("%"+x+"s",r) to save 2 bytes. Lots of move for just two bytes :( \$\endgroup\$ Jun 22, 2017 at 9:24
  • 1
    \$\begingroup\$ @OlivierGrégoire Thanks! By using s.format("%"+x+"s",r) directly I've been able to save 8 more bytes after your golf. :) \$\endgroup\$ Jun 22, 2017 at 12:04
  • \$\begingroup\$ @ceilingcat Thanks. Been able to golf a bunch more converting it to Java 11 (yay String#repeat ^_^ ). \$\endgroup\$ Nov 4, 2021 at 12:06
4
\$\begingroup\$

JavaScript (ES6), 85 bytes

Takes input in currying syntax (string)(height). Includes a leading newline.

s=>g=(n,p=`
`)=>n?g(n-1,p+' '.repeat(s.length/2))+p+s.replace(/./g,c=>c.repeat(n)):''

Demo

let f =

s=>g=(n,p=`
`)=>n?g(n-1,p+' '.repeat(s.length/2))+p+s.replace(/./g,c=>c.repeat(n)):''

o.innerHTML = f('o-o  o-o')(10)
<pre id=o></pre>

\$\endgroup\$
2
  • \$\begingroup\$ There are leading whitespaces before the last line, is that allowed? \$\endgroup\$
    – Charlie
    Jun 21, 2017 at 8:15
  • \$\begingroup\$ @CarlosAlejo Oh, that was an unintended side-effect of a last-minute update. Now fixed. Thanks for reporting this! \$\endgroup\$
    – Arnauld
    Jun 21, 2017 at 8:20
4
\$\begingroup\$

Charcoal, 19 bytes

F⁺¹N«J±×ι÷Lη²ιFηFικ

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

F⁺¹N«       for (Plus(1, InputNumber())) {

We need lines repeated 1..n times. The easiest way to achieve this is to loop from 0 to n, as loop 0 is basically a no-op.

J±×ι÷Lη²ι       JumpTo(Negate(Times(i, IntDivide(Length(h), 2))), i);

Position the cursor so that the resulting line is centred.

FηFικ           for (h) for (i) Print(k);

And this is how simple printing each character repeated i times is.

\$\endgroup\$
4
\$\begingroup\$

SOGL V0.12, 14 bytes

ā.∫dI*Hd⁄»±IFž

Try it Here!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 for using ∫dI. \$\endgroup\$
    – Adalynn
    Jun 21, 2017 at 17:12
4
\$\begingroup\$

Javascript, 105 bytes

(s,n)=>Array(N=n).fill().reduce(a=>a+'\n'+' '.repeat(--n*s.length/2)+s.replace(/./g,_=>_.repeat(N-n)),'')

After a few years off, the Stretch Maniac is back, hopefully slightly more educated this time.

\$\endgroup\$
2
  • \$\begingroup\$ You have too many leading spaces on each line. \$\endgroup\$
    – Shaggy
    Jun 21, 2017 at 8:25
  • \$\begingroup\$ Here's a 99 byte ES8 version of this method I came up with before I saw yours: s=>n=>[...Array(x=n)].reduce(a=>a+'\n'.padEnd(--x*s.length/2+1)+s.replace(/./g,c=>c.repeat(n-x)),'') - you'll need to replace the 's with backticks and the \n with a literal newline. \$\endgroup\$
    – Shaggy
    Jun 21, 2017 at 13:39
3
\$\begingroup\$

Haskell, 79 73 69 bytes

  • Saved 4 bytes thanks to nimi
s#n=unlines[(' '<$[1,3..(n-m)*length s])++((<$[1..m])=<<s)|m<-[1..n]]

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ If you use a step in .., you can drop the div: (' '<$[1,3..(n-m)*length s]). \$\endgroup\$
    – nimi
    Jun 21, 2017 at 15:10
  • \$\begingroup\$ Another 5 bytes off. \$\endgroup\$ Dec 29, 2017 at 23:56
3
\$\begingroup\$

APL (Dyalog), 33 31 bytes

2 bytes golfed thanks to @ZacharyT by removing unnecessary parentheses

{↑((' '/⍨(.5×≢⍵)×⍺-⊢),⍵/⍨⊢)¨⍳⍺}

Try it online!

Explanation

The right argument is the string and the left argument is the number.

{↑((' '/⍨(.5×≢⍵)×⍺-⊢),⍵/⍨⊢)¨⍳⍺}
                             ⍳⍺      Range 1 .. ⍺
  (                        )¨        For each element (let's call it i) do:
                      ⍵/⍨⊢          Replicate ⍵ i times
  (                 ),               Concatenated with
         (.5×≢⍵)×⍺-⊢                (⍺-i)×(len(⍵)×0.5)
   ' '/⍨                                spaces
 ↑                                    Convert the resulting array to a 2D matrix
\$\endgroup\$
2
  • \$\begingroup\$ Do you need the parens around ⍺-⊢? \$\endgroup\$
    – Adalynn
    Jun 21, 2017 at 17:07
  • \$\begingroup\$ @ZacharyT You're right, I don't need them. Thanks :) \$\endgroup\$
    – user41805
    Jun 22, 2017 at 7:19
3
\$\begingroup\$

SWI Prolog, 398 bytes

It is not the most compact solution (maybe somewhere reinventing the wheel instead of using built-in procedures), but it appers to work.

w(0).
w(X):-write(' '),Y is X-1,w(Y).
s(S,N):-string_length(S,X),Y is div(X,2)*N,w(Y).
d(S,N,R):-atom_chars(S,A),e([],A,N,R).
e(B,[H|T],N,R):-l(B,H,N,I),e(I,T,N,R).
e(B,[],_,B).
a([], L, L).
a([H|T],L,[H|R]):-a(T,L,R).
l(L,_,0,L).
l(L,I,N,R):-M is N-1,l(L,I,M,T),a(T,[I],R).
o([]):-nl.
o([H|T]):-write(H),o(T).
p(S,N):-p(S,N,N).
p(_,0,_).
p(S,N,L):-Q is N-1,p(S,Q,L),d(S,N,R),W is L-N,s(S,W),o(R).

Test:

?- p("o-o  o-o",10).
                                    o-o  o-o
                                oo--oo    oo--oo
                            ooo---ooo      ooo---ooo
                        oooo----oooo        oooo----oooo
                    ooooo-----ooooo          ooooo-----ooooo
                oooooo------oooooo            oooooo------oooooo
            ooooooo-------ooooooo              ooooooo-------ooooooo
        oooooooo--------oooooooo                oooooooo--------oooooooo
    ooooooooo---------ooooooooo                  ooooooooo---------ooooooooo
oooooooooo----------oooooooooo                    oooooooooo----------oooooooooo
true .

Explanation:

w and s writes proper amount of leading spaces:

w(0).
w(X):-write(' '),Y is X-1,w(Y).
s(S,N):-string_length(S,X),Y is div(X,2)*N,w(Y).

d manages the "duplication" of characters and e is it's recursive facility:

//d(String, Number of repetitions, Result)
d(S,N,R):-atom_chars(S,A),e([],A,N,R).
e(B,[H|T],N,R):-l(B,H,N,I),e(I,T,N,R).
e(B,[],_,B).

a and l append to the result (maybe there exists a built in procedure?):

a([], L, L).
a([H|T],L,[H|R]):-a(T,L,R).
l(L,_,0,L).
l(L,I,N,R):-M is N-1,l(L,I,M,T),a(T,[I],R).

o creates the output:

o([]):-nl.
o([H|T]):-write(H),o(T).

and finally the p is the main method:

p(S,N):-p(S,N,N).
p(_,0,_).
//p(String, Current level, Number of levels) :- go to the bottom, create pyramide level, write whitespaces, write the level
p(S,N,L):-Q is N-1,p(S,Q,L),d(S,N,R),W is L-N,s(S,W),o(R).
\$\endgroup\$
3
\$\begingroup\$

Japt -R, 20 19 14 8 bytes

õ@VmpXÃû

Try it

\$\endgroup\$
2
  • \$\begingroup\$ I think you can change SpUl to... wait, nevermind :( You can save a byte though by replacing (V-X with XnV, if I'm not mistaken. \$\endgroup\$ Jun 22, 2017 at 1:08
  • \$\begingroup\$ Oh, yeah, forgot about n; thanks @ETHproductions. \$\endgroup\$
    – Shaggy
    Jun 22, 2017 at 9:07
2
\$\begingroup\$

PHP, 113 bytes:

for([,$s,$n]=$argv;$i++<$n;)for(print($f=str_pad)("
",($n-$i)*strlen($s)/2+!$p=0);~$c=$s[$p++];)echo$f($c,$i,$c);

Run with php -nr '<code>' '<string>' <N> or test it online.

breakdown

# import input, loop $i from 1 to $n
for([,$s,$n]=$argv;$i++<$n;)
    # 1. print newline and padding, reset $p
    for(print($f=str_pad)("\n",($n-$i)*strlen($s)/2+!$p=0);
    # 2. loop $c through string
        ~$c=$s[$p++];)
        # print repeated character
        echo$f($c,$i,$c);
\$\endgroup\$
0
2
\$\begingroup\$

CJam, 36 bytes

l_,2/:T;]li:F{[_U)*zSTFU)-**\N]\}fU;

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to PPCG! Nice first submission :) \$\endgroup\$
    – hyper-neutrino
    Jun 21, 2017 at 18:20
  • \$\begingroup\$ @HyperNeutrino Well, I have a feeling my code is pretty far from optimized, but... thanks. :) \$\endgroup\$
    – Siguza
    Jun 21, 2017 at 18:25
  • 4
    \$\begingroup\$ But it contains STFU :-D \$\endgroup\$
    – Luis Mendo
    Jun 21, 2017 at 23:21
2
\$\begingroup\$

T-SQL, 223 bytes

DECLARE @ char(99),@n INT,@i INT=1,@j INT,@p varchar(max)SELECT @=s,@n=n FROM t
R:SET @j=0SET @p=SPACE((@n-@i)*len(@)/2)C:SET @j+=1SET @P+=REPLICATE(SUBSTRING(@,@j,1),@i)IF @j<LEN(@)GOTO C
PRINT @p SET @i+=1IF @i<=@n GOTO R

Input is via pre-existing table t with columns s and n, per our IO standards.

Not much to explain, it's a pretty straightforward nested loop, using @i for the rows and @j to walk through the characters of the string which are REPLICATED @i times:

DECLARE @ char(99),@n INT,@i INT=1,@j INT,@p varchar(max)
SELECT @=s,@n=n FROM t
R:
    SET @j=0
    SET @p=SPACE((@n-@i)*len(@)/2) 
    C:
        SET @j+=1
        SET @P+=REPLICATE(SUBSTRING(@,@j,1),@i)
    IF @j<LEN(@)GOTO C
    PRINT @p
    SET @i+=1
IF @i<=@n GOTO R
\$\endgroup\$
2
\$\begingroup\$

R, 125 95 bytes

function(S,n)for(i in 1:n)cat(rep(' ',(n-i)/2*nchar(S)),rep(el(strsplit(S,'')),e=i),sep="",'
')

Try it online!

Explanation:

It's pretty straightforward, splitting the string and repeating the elements i times each rep(s,e=i) (e is short for each) as we loop. The tricky part is rep('',(n-i)/2*length(s)+1). This is the padding string, but it's a bunch of empty strings. I need to add 1 because otherwise the result is character(0), a zero-length vector, and cat, which by default separates its elements with spaces, misaligns the final line.

\$\endgroup\$
2
\$\begingroup\$

Python 2, 79 77 bytes

s,n=input();m=n
while m:m-=1;print' '*(m*len(s)/2)+''.join(i*(n-m)for i in s)

Try it online!

Edit: -2 bytes courtesy @FlipTack

\$\endgroup\$
1
  • \$\begingroup\$ You can remove the square brackets around [i*(n-m)for i in s], as .join is capable of taking a generator, which should ave you two bytes. \$\endgroup\$
    – FlipTack
    Dec 28, 2017 at 18:44
1
\$\begingroup\$

Mathematica, 97 bytes

(c=Characters@#;T=Table;Column[T[""<>T[""<>T[c[[i]],j],{i,Length@c}],{j,#2}],Alignment->Center])&


input

["o-o o-o", 10]

\$\endgroup\$
1
\$\begingroup\$

Tcl, 143 142 141 138 bytes

proc p s\ n {set p [expr [set w [expr [string le $s]/2]]*$n];time {incr p $w;puts [format %$p\s [regsub -all . $s [append r \\0]]]} $n;cd}

Test:

% p "o-o  o-o" 5
                o-o  o-o
            oo--oo    oo--oo
        ooo---ooo      ooo---ooo
    oooo----oooo        oooo----oooo
ooooo-----ooooo          ooooo-----ooooo

Remark: the "cd" at the end of the procedure prevents time's result to be printed out below the pyramid, but changes the current directory - a side effect that's not explicitly forbidden.

Thanks to sergiol for a hint to save one byte.... and another hint to save one more byte.

Thanks to aspect (on tcl chat) for another 3 bytes saved!

\$\endgroup\$
0
1
\$\begingroup\$

Swift, 232 bytes

Probably could be better, but I don't have much time to refactor.

This answer uses Swift 4, so it can't currently be run online.

var p:(String,Int)->String={s,i in let r=(1...i).map{n in return s.map{return String(repeating:$0,count:n)}.joined()};return(r.map{return String(repeating:" ",count:(r.last!.count-$0.count)/2)+$0}as[String]).joined(separator:"\n")}
\$\endgroup\$
1
\$\begingroup\$

LOGO, 97 95 bytes

to f :s :n
for[i 1 :n][repeat(:n-:i)/2*count :s[type "\ ]foreach :s[repeat :i[type ?]]pr "]
end

Try the code on FMSLogo interpreter.

Define a function f which takes two inputs, :s and :n, then print the result.

\$\endgroup\$
1
\$\begingroup\$

Java 8, 164 148 bytes

s->n->{String o="";for(int i=0,m,j;i++<n;){o+="\n";for(m=0;m++<(n-i)*s.length()/2;)o+=" ";for(char c:s.toCharArray())for(j=0;j++<i;)o+=c;}return o;}

Explanation:

s->n->{
    String o = "";                                  //empty output string
    for (int i = 0, m, j; i++ < n; ) {              //for each row
        o += "\n";                                  //append a new line
        for (m = 0; m++ < (n - i)*s.length()/2; )   //for amount of spaces = inversed row_number * half length
            o += " ";                               //append a space
        for (char c : s.toCharArray())              //for each char of the string
            for (j = 0; j++ < i; )                  //row_number times
                o+=c;                               //append char
    }
    return o;
}
\$\endgroup\$
1
\$\begingroup\$

Rust, 107 bytes

|a:&str,b|for i in 0..b{println!("{:^1$}",a.split("").map(|s|s.repeat(i+1)).collect::<String>(),a.len()*b)}

playpen link

Defines an anonymous function that takes a string slice and number, printing the wanted pattern to standard output. It assumes that the string slice only contains ASCII characters, but the challenge never specifies that full unicode support is necessar. To be correct for unicode as well would require 117 bytes:

|a:&str,b|for i in 0..b{println!("{:^1$}",a.split("").map(|s|s.repeat(i+1)).collect::<String>(),a.chars().count()*b)}

The explanation is rather simple:

|a:&str,b|                             // arguments, compiler can't infer the type of a unfortunately
    for i in 0..b {                    // iterate from row 0 to row b - 1
        println!(
            "{:^1$}",                  // print a line containing arg 0, centered with the width specified as arg 1
            a.split("")                // split the string into slices of one character
                .map(|s|s.repeat(i+1)) // for each slice, yield a string containing row+1 times that slice
                .collect::<String>(),  // concatenate each of the strings into one string
            a.len()*b                  // total length should be the length of the string times the amount of rows
        )
    }
\$\endgroup\$
1
\$\begingroup\$

SOGL V0.12, 8 bytes

∫dč*∑}¹╚

Try it Here!

Explanation:

∫dč*∑}¹╚
∫    }    iterate over 1..input, pushing counter
 d        push the variable D, which sets itself to the next input as string
  č       chop into characters - a vertical array
   *      multiply horizontally by the counter
    ∑     join the array together
      ¹   wrap all that in an array
       ╚  center horizontally

I didn't feel like updating my old answer here as it uses a different method and uses a new(er than the challenge) feature -

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 6 5 bytes

L€×.c

First input is \$n\$, second input is \$s\$ as character-list.

Try it online.

Explanation:

L      # Push a list in the range [1, first (implicit) input-integer]
 €     # Map over each integer:
  ×    #  Repeat each character in the (implicit) second input-list the integer
       #  amount of times as string
   .c  # Join each inner list to a string; then each string by newlines;
       # and then centralize each line by padding leading spaces
       # (after which it is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 123 bytes

i,j,c;p(char*s,int n){for(i=0;i<n;){printf("\n%*s",strlen(s)/2*(n-++i),"");for(c=0;s[c];c++)for(j=0;j++<i;)putchar(s[c]);}}

Try it online!

Pretty Code:

// declare variables gcc-style
i,j,c;
p(char *s, int n){
    // for every n
    for(i=0;i<n;){
        // print [ strlen(s)/2 * (n-(i+1)) ] spaces
        printf("\n%*s",strlen(s)/2*(n-++i),""); // increment i instead of (i+1)
        // for every character in the input string
        for(c=0;s[c];c++)
            // for every repetition required
            for(j=0;j++<i;)
                // print the current character
                putchar(s[c]);
    }
}
\$\endgroup\$
1

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.