Build me a city

Coders are always trying to flatten arrays into boring 1-dimensional entities and it makes me sad.

Your task is to unflatten an arbitrary string of characters, outputting a lovely city skyscape.

Consider the string: aaabbbbbccqrrssstttttttPPw

It looks much better like this:

            tt
tt
bb        tt
bb        tt
aabb      sstt


(Ok, yes, the letters are duplicated to make it look more city-skyline-ery).

Take an input string, duplicate each subsection of matching characters (not necessarily alphabetic letters) and build me a city!

Shortest code bytes win.

I actually thought I had the requirements nailed, but to answer some questions:

• it must be on the ground
• you can have extra sky if you want (leading blank lines, surrounding blank space) - but not between the buildings
• letters can be reused inside the string (same architecture, different location)
• the letters are assumed to be ASCII, but more flair will be given to those supporting additional encodings (UTF8, etc)
• Can we output the cityscape rotated 90 degrees? – Okx Jun 27 '17 at 11:30
• Will characters ever repeat again i.e. aaabbbbaa? – TheLethalCoder Jun 27 '17 at 11:30
• @Okx have you ever seen a city rotated 90 degrees, that would look very silly! ;) – Tom Jun 27 '17 at 11:30
• @Tom maybe..? – Rod Jun 27 '17 at 11:31
• Welcome on the site! For future challenges, I recommend posting them first in the Sandbox where you can get feedbacks from the community before posting it as a challenge. – Dada Jun 27 '17 at 11:32

05AB1E, 6 bytes

γ€DζR»


Try it online!

In a version newer than the challenge, ζ has been added as a replacement fo .Bø

05AB1E, 8 bytes

γ€D.BøR»


Explanation:

γ            Convert into a list of consecutive equal elements
€D          Duplicate each element
.B        Squarify; pad each element with spaces so that they are the length of the longest element
ø       Transpose
R      Reverse (otherwise the city would be upside-down)
»     Join by newlines


Try it online!

• Interestingly, Jelly has z⁶ for .Bø...but it also has Œgx'2 for γ€D >_> – Erik the Outgolfer Jun 27 '17 at 11:46
• γ.BD)ø˜øR» was what I had without looking, €D is way better; I feel like we're both missing the 1-byte solution to inline duplication though. – Magic Octopus Urn Jun 27 '17 at 20:25
• @MagicOctopusUrn Wait, you solved the challenge without even looking at it? – Okx Jun 27 '17 at 20:51
• @Okx Well, it's wise not to look at the answers before since the whole fun of golfing it yourself could be cut off. – Erik the Outgolfer Jun 29 '17 at 15:24
• @EriktheOutgolfer It was a joke, and what I mean was that he solved it without looking at the content of the challenge. – Okx Jun 29 '17 at 16:10

CJam, 23 bytes

qe::*:__:,:e>f{Se[}zN*


Try it online!

Explanation:

qe::*:__:,:e>f{Se[}zN* Accepts (multi-line?) input
q                       Take all input
e::*                  Split into groups of equal elements
:_                Duplicate each
_:,:e>          Push maximal length without popping
f{Se[}    Left-pad each to that length with space strings (NOT space chars, although not a problem here)
z   Zip
N* Join with newlines

• Wow, a CJam answer >_> – Mr. Xcoder Jun 27 '17 at 12:08

Jelly, 9 bytes

Œgx'2z⁶ṚY


Try it online!

Explanation:

Œgx'2z⁶ṚY  Main Link
Œg         Group runs of equal elements
x        Repeat
'              the lists
2                       twice without wrapping
z⁶    Zip (transpose), filling in blanks with spaces
Ṛ   Reverse the whole thing so it's upside-down
Y  Join by newlines

• Could you add an explanation please milord? I can't understand what's happening here :o – Nathan Jun 27 '17 at 15:02
• @Nathan pastebin.com/DzaBSjd5 – HyperNeutrino Jun 27 '17 at 19:24
• @HyperNeutrino Nice explanation... – Erik the Outgolfer Jun 27 '17 at 19:25
• Just to be sure, is it correct? :P – HyperNeutrino Jun 27 '17 at 19:33
• @HyperNeutrino Well, that wasn't entirely the intention for ', which was to repeat the lists themselves and not the items inside them, but overall it's good. :) – Erik the Outgolfer Jun 27 '17 at 19:38

Python 3, 155136134 132 bytes

-19 bytes thanks to @LeakyNun
-2 bytes thanks to @officialaimm
-1 byte thanks to @Wondercricket

s=input()+'+'
k=' '*len(s)
a=[]
c=b=''
while s:
while c in b:b+=c;c,*s=s
a+=b+k,b+k;b=c
for r in[*zip(*a)][:0:-1]:print(*r,sep='')


Try it online!

Python 2, 117 bytes

import re
s=input()
for l in zip(*[x+S*len(s)for x,_ in re.findall(r'((.)\2*)',s)for S in'  '])[::-1]:print''.join(l)


Try it online!

Java 8, 412400330324312 319 bytes

-6 bytes thanks to VisualMelon
-12 bytes thanks to Kevin Cruijssen
but +19 bytes because I forgot to include the imports in the byte count.

import java.util.*;x->{Map m=new HashMap(),n;int l=x.length(),i=l,v,y,h=0,d=1;char c,k;for(;i-->0;m.put(c,d=m.get(c)!=null?d+1:1),h=d>h?d:h)c=x.charAt(i);for(y=h;y>0;y--){n=new HashMap(m);for(i=0;i<l;i++)if(n.get(k=x.charAt(i))!=null){v=(int)m.get(k);System.out.print((y>v?"  ":k+""+k)+(i==l-1?"\n":""));n.remove(k);}}}


Try it online!

• Golfing Java and C# (my department) is great fun! Keep at it! Not tested, but I think you can save a few bytes by rejigging the for loops: you can pre-assign i=0, or better, i=l, and count down for(;i-->0;h=d>h?d:h) (and stuff the h= bit in there). The same back-counting will work for the inner loop also. The inner if also has no need for the braces {}. And always be weary of <= or >=, you can turn the ternary around with > and save a byte. – VisualMelon Jun 28 '17 at 12:10
• Thanks, I could shave another 6 bytes off the code thanks to your tips. Well, I think I'm going to stay with Java Golfing since I actually like it ;). – Twometer Jun 28 '17 at 14:59
• Welcome to PPCG! I'm afraid you'll have to increase the byte-count to 329 (+19 bytes due to the required import java.util.*; for Map and HashMap, imports are part of the byte-count; and -1 by removing trailing semi-colon, which isn't part of the byte-count). – Kevin Cruijssen Jun 29 '17 at 12:57
• – Kevin Cruijssen Jun 29 '17 at 12:58
• Summary of the changes: HashMap<>HashMap; Map n=,n and n=; m.put(c,d=m.get(c)!=null?d+1:1); inside the for-loop to get rid of the brackets; k=x.charAt(i) inside the if(n.get(k)!=null) to get rid of the semi-colon and for-loop's brackets. Again, welcome and great answer! +1 from me. Also, in case you haven't seen it yet: Tips for golfing in Java and Tips for golfing in <any language> might be interesting to read through. – Kevin Cruijssen Jun 29 '17 at 13:02

Japt, 19181513 12 bytes

Includes trailing spaces on each line.

ò¦
íU c ·z w


Test it

Explanation

         :Implicit input of string U
ò        :Split U to an array by ...
¦        :   checking for inequality between characters.
í        :Pair each item in U with...
U        :   The corresponding item in U (i.e, duplicate each string)
c        :Flatten the array (í creates an array of arrays).
·        :Join to a string with newlines.
z        :Rotate 90 degrees.
w        :Reverse.
:Implicit output of resulting string.


Mathematica, 150 bytes

(z=Characters[v=#];f=CharacterCounts[v][#]&/@(d=Union@z);Row[Column/@Map[PadLeft[#,Max@f,""]&,Table[Table[d[[i]]<>d[[i]],f[[i]]],{i,Length@d}],{1}]])&


R, 135 bytes

e=rle(sub('(.)','\\1\\1',strsplit(scan(,''),'')[[1]]));write(sapply(sum(e$l|1):1,function(x)ifelse(e$l>=x,e$v,' ')),'',sum(e$l|1),,'')


Try it online!

reads from stdin, writes to stdout (with a trailing newline).

Explanation:

• rle finds the lengths of the streaks of characters, the heights of each tower.
• the sub expression replaces each character with its double (so I didn't have to muck about with setting adjacent indices together)
• sapply returns an array (in this case a matrix):
• sum(e$l|1) is the number of distinct characters; we go from top to bottom • ifelse( ... ) is a vectorized if...else allowing us to build a matrix of towers and double spaces • write writes to console, with a few options to format. Pyth, 13 bytes j_.tsC*2]*Mr8  Try it online! • 49 minutes... way too slow – Okx Jun 27 '17 at 12:17 PHP, 138 bytes for(;~$s=&$argn;$s=substr($s,$r++%2*$i))for($i=0;$i<strspn($s,$c=$s[0]);$f[$i++][$r]=$c)a&$f[$i]?:$f[$i]=" ";krsort($f);echo join(" ",$f);


Try it online!

MATL, 15 bytes

'(.)\1*'XXtvc!P


Try it online!

Explanation

'(.)\1*' % Push string to be used as regexp pattern
XX       % Implicit input. Regexp matching. Pushes row cell array of matching substrings
t        % Duplicate
v        % Concatenate vertically
c        % Convert to char. This reads cells in column-major order (down, then across)
% and produces a 2D char array, right-padding with spaces
!        % Transpose
P        % Flip vertically. Implicitly display


Charcoal, 40 bytes:

Ａ⟦⟦ω⟧⟧λＦθ¿⁼ι§§λ±¹¦⁰⊞§λ±¹ι⊞λ⟦ι⟧ＦλＦ²↑⁺⪫ιω¶


Try it online! Link is to verbose version of code. I originally tried a simple loop over the input string to print an oblong every time the letter changed, but I switched to this list-building method as it saved 5 bytes. Explanation: The variable l contains a nested list of the input letters. Characters that match the current last list elements get pushed onto the last list otherwise a new sublist is created for that character. It then remains to join the letters in each sublist so that they can be printed vertically twice.

C, 259 231 Bytes

Golfed Code

#define v a[1][i
i,k,l,x,h,w;main(char*s,char**a){for(;v];w+=2*!x,s=v++],h=x>h?x:h)x=(s==v])*(x+1);h++;s=malloc((x=h++*++w+1)+w);memset(s,32,h*w);for(i=k;v];s[x+1]=s[x]=k=v++],x=k==v]?x-w:(h-1)*w+l++*2+3)s[i*w]=10;printf("%s",s);}


Verbose Code

//Variable Explanations:
//i - increment through argument string, must beinitialized to 0
//k - increment through argument string, must be initialized to 0
//l - record x coordinate in return value, must be initialized to 0
//x - record the actual character position within the return string
//arrheight - the height of the return string
//arrwidth - the width of the return string
//arr - the return string
//argv - the string containing the arguments
#define v argv[1][i

i,k,l,x,arrheight,arrwidth;

main(char*arr,char**argv){
for(;v];                                 //For Length of input
arrwidth+=2*!x,                        //increment width by 2 if this char is not the same as the last
arr=v++],                              //set arr to current char
arrheight=x>arrheight?x:arrheight      //see if x is greater than the largest recorded height
)x=(arr==v])*(x+1);                     //if this character is the same as the last, increment x (using arr to store previous char)
arrheight++;                             //increment height by one since its 0 indexed
arr=malloc((x=arrheight++*++arrwidth+1)+arrwidth); //create a flattened array widthxheight and set x to be the bottom left position
memset(arr,32,arrheight*arrwidth);       //fill array with spaces
for(i=k;v];                              //For Length of input
arr[x+1]=arr[x]=k=v++],                //set x and x+1 positions to the current character, store current character in i
x=k==v]?x-arrwidth:(arrheight-1)*arrwidth+l++*2+3 //if next char is same as current move vertically, else set x to bottom of next column
)arr[i*arrwidth]=10;                     //Add new lines to string at end of width

printf("%s",arr);                        //output string

}


Compiled with GCC, no special Flags

Edit

Saved 28 bytes thanks to adelphus. His change allowed me to create a define. And I made the while loops into for loops to save 2 bytes each by rearranging the loop. I also fixed an issue where the code would break when the last character in input wasn't singleton. The code will fail if there is only one unique letter but should work in all other cases.

• Nice! But the golfed version doesn't seem to work with arbitrary input for some reason. Removing the final "w" from the sample input appears to lose the q's and repeat the string. Sure it's something small... – adelphus Jun 28 '17 at 23:01
• also while (i < strlen(argv[1])) can be shortened to while (argv[1][i]) - loop until null character – adelphus Jun 28 '17 at 23:06
• @adelphus Interesting, I'll try it out tomorrow when I get a chance. I did not test anything other than the given test case (lazy I know). – dj0wns Jun 29 '17 at 0:54
• That actually helped a ton, I was able to fix the problem and reduce by almost 30 bytes! – dj0wns Jun 29 '17 at 12:46

Pip, 22 bytes

21 bytes of code, +1 for -l flag.

Ya@(.)\1*RV:yWVyZDs


Try it online!

Explanation

                       a is 1st cmdline arg; s is space (implicit)
a@(.)\1*            Using regex, create list of runs of same character in a
Y                      Yank that into y variable
yWVy     Weave (interleave) y with itself to duplicate each item
ZDs  Zip to transpose, with a default character of space filling gaps
RV:         Reverse the resulting list (with the compute-and-assign
meta-operator : being abused to lower the precedence)
Auto-print, one sublist per line (implicit, -l flag)


QuadS, 15 + 1 = 16 bytes

+1 byte for the 1 flag.

⊖⍵
(.)\1*
2/⍪⍵M


Try it online!

⊖⍵ post-process by flipping upside down

(.)\1* runs of identical characters

2/⍪⍵M duplicate the columnified Match

The 1 flag causes the results to be merged together.

f s=let x=groupBy(==)s;l=length;m=maximum(map l x)in concatMap(++"\n")$reverse$transpose$concat[[z,z]|z<-(map(\y->y++(replicate(m-(l y))' '))x)]  I'm pretty confident I can do better than this, but this is the best I can come up with for the time being. • Bad news first: you use functions from Data.List which is not in scope by default. You have to either add the import Data.List to the byte count or specify a Haskell environment which does include it by default (e.g. change the language from Haskell to Haskell (lambdabot). -- Some tips: a) use pattern guards to bind variables instead of let and/or declare helper functions directly: l=length;f s|x<-groupBy(==)s,m<-... =concatMap. b) map l x is l<$>x, c) concatMap("++\n" is unlines. d) groupBy(==) is just group. e) concat is id=<<. You use m only once, so inline it – nimi Jun 28 '17 at 17:37
• ... f) no need for () around l y, replicate ... ' ' and map ... x. All in all: import Data.List;l=length;f s|x<-group s=unlines$reverse$transpose$id=<<[[z,z]|z<-map(\y->y++replicate(maximum(l<$>x)-l y)' ')x]. – nimi Jun 28 '17 at 17:38
• groupBy(==)=group, altough I'm not sure whether one is in Prelude and the other isn't. concatMap can be written >>=, and map can be infixed as <$>, and concat[[z,z]|z<-…] might be (replicate 2)=<<… or (\z->[z,z])=<<… – Bergi Jun 28 '17 at 17:44 • You can shave off one more byte from @Bergi's excellent tip: (\z->[z,z]) is (:)<*>pure, i.e. ...transpose$(:)<*>pure=<<map(\y...)x – nimi Jun 28 '17 at 17:59

Stacked, 42 bytes

[rle toarr[...*chars]map FIX 2*tr rev out]


Try it online!

Ruby, 116 bytes

->s{a=s.scan(/(.)(\1*)/).map{|x,y|[x,y.size+1]}.to_h
m=a.values.max
m.times{|i|puts a.map{|k,v|v+i<m ?'  ':k*2}*''}}


Try it online!

• puts a.map{...} can be replaced with p(a.map{}) – Filip Bartuzi Jun 29 '17 at 0:06
• p will output quote characters, so it's not fit here – Alex Jun 29 '17 at 5:37
• oh, wow, thanks. You learn everyday - stackoverflow.com/a/1255362/2047418 – Filip Bartuzi Jun 29 '17 at 7:45

APL (Dyalog), 37 bytes

{⊃,/⍵↑⍨¨-⌈/≢¨⍵}'(.)\1*'⎕S{2/⍪⍵.Match}


Try it online!

q/kdb+, 53 bytes

Solution:

{(|)(+)(,/)(max(#:)each c)$(+)2#(,)c:((&)differ x)_x}  Example:  q){(|)(+)(,/)(max(#:)each c)$(+)2#(,)c:((&)differ x)_x}"BBPPPPxxGGGGKKKKKKKkkkkEEeeEEEeeEEEEEOOO8####xxXXX"
"        KK                      "
"        KK                      "
"        KK          EE          "
"  PP  GGKKkk        EE    ##    "
"  PP  GGKKkk    EE  EEOO  ##  XX"
"BBPPxxGGKKkkEEeeEEeeEEOO  ##xxXX"
"BBPPxxGGKKkkEEeeEEeeEEOO88##xxXX"


Explanation:

{reverse flip raze (max count each c)$flip 2#enlist c:(where differ x)_x} / ungolfed function { } / lambda function (where differ x) / indices where x differs _ / cut at these points aabbbc -> "aa","bbb","c" c: / save in variable c enlist / put this list in another list 2# / take two from this list (duplicate) flip / rotate columns/rows (max count each c) / find the longest run of characters$                                    / whitespace pad lists to this length
raze                                                        / reduce down lists
flip                                                             / rotate columns/rows
reverse                                                                  / invert so buildings are on the ground


Perl 5, 92 + 1 (-p) = 93 bytes

while(s/(.)\1*//){$a[$_].=($"x($i-length$a[$_])).$1x2for 1..length$&;$i+=2}say while$_=pop@a
`

Try it online!