34
\$\begingroup\$

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
aabbcc  rrssttPP
aabbccqqrrssttPPww

(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)
\$\endgroup\$
  • 3
    \$\begingroup\$ Can we output the cityscape rotated 90 degrees? \$\endgroup\$ – Okx Jun 27 '17 at 11:30
  • 6
    \$\begingroup\$ Will characters ever repeat again i.e. aaabbbbaa? \$\endgroup\$ – TheLethalCoder Jun 27 '17 at 11:30
  • 14
    \$\begingroup\$ @Okx have you ever seen a city rotated 90 degrees, that would look very silly! ;) \$\endgroup\$ – Tom Jun 27 '17 at 11:30
  • 7
    \$\begingroup\$ @Tom maybe..? \$\endgroup\$ – Rod Jun 27 '17 at 11:31
  • 10
    \$\begingroup\$ 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. \$\endgroup\$ – Dada Jun 27 '17 at 11:32

22 Answers 22

11
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Interestingly, Jelly has z⁶ for .Bø...but it also has Œgx'2 for γ€D >_> \$\endgroup\$ – Erik the Outgolfer Jun 27 '17 at 11:46
  • \$\begingroup\$ γ.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. \$\endgroup\$ – Magic Octopus Urn Jun 27 '17 at 20:25
  • 3
    \$\begingroup\$ @MagicOctopusUrn Wait, you solved the challenge without even looking at it? \$\endgroup\$ – Okx Jun 27 '17 at 20:51
  • \$\begingroup\$ @Okx Well, it's wise not to look at the answers before since the whole fun of golfing it yourself could be cut off. \$\endgroup\$ – Erik the Outgolfer Jun 29 '17 at 15:24
  • \$\begingroup\$ @EriktheOutgolfer It was a joke, and what I mean was that he solved it without looking at the content of the challenge. \$\endgroup\$ – Okx Jun 29 '17 at 16:10
6
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Wow, a CJam answer >_> \$\endgroup\$ – Mr. Xcoder Jun 27 '17 at 12:08
6
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Could you add an explanation please milord? I can't understand what's happening here :o \$\endgroup\$ – Nathan Jun 27 '17 at 15:02
  • \$\begingroup\$ @Nathan pastebin.com/DzaBSjd5 \$\endgroup\$ – HyperNeutrino Jun 27 '17 at 19:24
  • \$\begingroup\$ @HyperNeutrino Nice explanation... \$\endgroup\$ – Erik the Outgolfer Jun 27 '17 at 19:25
  • \$\begingroup\$ Just to be sure, is it correct? :P \$\endgroup\$ – HyperNeutrino Jun 27 '17 at 19:33
  • \$\begingroup\$ @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. :) \$\endgroup\$ – Erik the Outgolfer Jun 27 '17 at 19:38
6
\$\begingroup\$

Python 3, 155 136 134 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!

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

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!

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

Java 8, 412 400 330 324 312 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!

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

Japt, 19 18 15 13 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.
\$\endgroup\$
4
\$\begingroup\$

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}]])&
\$\endgroup\$
4
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

Pyth, 13 bytes

j_.tsC*2]*Mr8

Try it online!

\$\endgroup\$
  • 6
    \$\begingroup\$ 49 minutes... way too slow \$\endgroup\$ – Okx Jun 27 '17 at 12:17
3
\$\begingroup\$

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!

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

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
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 40 bytes:

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

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.

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

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.

\$\endgroup\$
  • \$\begingroup\$ 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... \$\endgroup\$ – adelphus Jun 28 '17 at 23:01
  • \$\begingroup\$ also while (i < strlen(argv[1])) can be shortened to while (argv[1][i]) - loop until null character \$\endgroup\$ – adelphus Jun 28 '17 at 23:06
  • \$\begingroup\$ @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). \$\endgroup\$ – dj0wns Jun 29 '17 at 0:54
  • \$\begingroup\$ That actually helped a ton, I was able to fix the problem and reduce by almost 30 bytes! \$\endgroup\$ – dj0wns Jun 29 '17 at 12:46
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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.

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

Haskell, 144 bytes

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – nimi Jun 28 '17 at 17:37
  • 1
    \$\begingroup\$ ... 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]. \$\endgroup\$ – nimi Jun 28 '17 at 17:38
  • 1
    \$\begingroup\$ 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])=<<… \$\endgroup\$ – Bergi Jun 28 '17 at 17:44
  • \$\begingroup\$ You can shave off one more byte from @Bergi's excellent tip: (\z->[z,z]) is (:)<*>pure, i.e. ...transpose$(:)<*>pure=<<map(\y...)x \$\endgroup\$ – nimi Jun 28 '17 at 17:59
1
\$\begingroup\$

Stacked, 42 bytes

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

Try it online!

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

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!

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

APL (Dyalog), 37 bytes

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

Try it online!

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

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
\$\endgroup\$
0
\$\begingroup\$

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!

\$\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.