30
\$\begingroup\$

Description

Your task is to output a 'depthmap' - that is, a heightmap of an object but not seen from its top but from its front.

For example, consider the following object as shown on the image. The height map is shown on the left. The corresponding depth map would be (as seen from standing at the arrow):

010
211   <- Depthmap
322

If you stand at the arrow, there are 3 cubes behind each other at the bottom left-hand point, 2 behind each other on the middle left-hand point, 0 at the top left-hand point etc.

example

Input

Input is a two dimensional array of any sizes (not necessarily square).

Output

Output is another two dimensional array which represents the depthmap. As you can deduce, its sizes are (height x width). In the image, it would be (3 x 3). Note that if the highest tower of cubes was 5, the depthmap would be an array of (5 x 3).

Winning condition

The shortest code wins.

Disallowed

All languages allowed, no explicit restrictions. (I don't know what you can come up with, but play fair please.)

Examples

Input:     Ouput:

5321       0001
1456       1012
2105       1112
           1212
           2222
           3323


Input:     Output:

22         01
13         12
00         22


Input:     Output:    (of the sample image)

232        010
210        211
101        322
\$\endgroup\$
  • \$\begingroup\$ Can you provide a sample input / output for the example image you posted? \$\endgroup\$ – mellamokb May 24 '11 at 19:24
  • 4
    \$\begingroup\$ @pimvdb: Nice puzzle. We encourage people to seek advice on the Puzzle Lab char or the Meta SandBox before posting. That way, these kinds of issues can be ironed out before your puzzle goes live. All of us have trouble producing a perfect specification, especially if the task is non trivial. \$\endgroup\$ – dmckee May 24 '11 at 19:53
  • 2
    \$\begingroup\$ @pimvdb: Don't fret it; it's not some kind of requirement. Just a service we provide for each other in hope of making the site a little better. \$\endgroup\$ – dmckee May 24 '11 at 20:34
  • 2
    \$\begingroup\$ Well, the confusion regarding the last line might be that your definition of »depth map« is uncommon, I guess. Usually a depth map is the same as a height map, just seen from a specific camera – i.e. it tells the extension towards the viewpoint of a given scene (at least that's how 3D renderers treat it). What you have is essentially a how many blocks are behind each other in a given place. Not sure how to call it, though. An anlogy might be partially transparend glass blocks and the more you have of them behind each other, the darker the result gets – regardless of space between them. \$\endgroup\$ – Joey May 25 '11 at 11:26
  • 1
    \$\begingroup\$ Don't worry. It's a fine task as it is now. \$\endgroup\$ – Joey May 25 '11 at 17:15

11 Answers 11

12
\$\begingroup\$

Golfscript, 42 chars

n%{n*~]}%zip:|[]*$),{:);n|{{)>},,}%}%-1%\;

results

$ golfscript 2657.gs < 2657-1.txt 
0001
1012
1112
1212
2222
3323

$ golfscript 2657.gs < 2657-2.txt 
01
12
22

$ golfscript 2657.gs < 2657-3.txt 
010
211
322
\$\endgroup\$
  • \$\begingroup\$ Congratulations. \$\endgroup\$ – pimvdb May 25 '11 at 15:27
  • \$\begingroup\$ @pimvdb, thanks, but I think you should open it without accepting any answer for some time (may be one week). \$\endgroup\$ – YOU May 25 '11 at 17:07
  • \$\begingroup\$ Since the accepted answer can be changed any time again, where is the harm? \$\endgroup\$ – Joey May 25 '11 at 17:38
  • \$\begingroup\$ +100: 42 chars :-) \$\endgroup\$ – mellamokb May 26 '11 at 14:31
  • \$\begingroup\$ I refrained from looking at your solution until I'd written my own. Comparing them now, they're rather similar except that you save a ton of characters with the []*. Nice trick. \$\endgroup\$ – Peter Taylor May 26 '11 at 20:11
8
\$\begingroup\$

Ruby 1.9, 102 characters

f=$<.map{|g|[*g.chop.bytes]}
f.flatten.max.downto(49){|j|puts f.transpose.map{|n|n.count{|r|r>=j}}*""}

Passes all testcases.

\$\endgroup\$
7
\$\begingroup\$

Windows PowerShell, 108 111 114

(($i=@($input))-split''|sort)[-1]..1|%{$h=$_
-join(1..$i[0].Length|%{$x=$_-1
@($i|?{"$h"-le$_[$x]}).count})}

Passes all test cases.

\$\endgroup\$
7
\$\begingroup\$

Haskell, 118 characters

import List
p h=map(\c->transpose(lines h)>>=show.length.filter(>=c))['1'..maximum h]
main=interact$unlines.reverse.p

  • Edit (122 → 118): avoid filtering by only iterating to maximal height
\$\endgroup\$
4
\$\begingroup\$

Scala 236 characters

object D extends App{var(l,m,z)=(io.Source.stdin.getLines.toList,0,0);val a=Array.ofDim[Int](l.head.size,10);for(i<-l;(j,q)<-i.zipWithIndex;x<-1 to j-48){a(q)(x-1)+=1;m=List(m,j-48).max};for(i<-1 to m){for(j<-a){print(j(m-i))};println}}

With some formatting:

object Depthmap extends App
{
    var(l,m,z)=(io.Source.stdin.getLines.toList,0,0)
    val a=Array.ofDim[Int](l.head.size,10)
    for(i<-l;(j,q)<-i.zipWithIndex;x<-1 to j-48)
    {
        a(q)(x-1)+=1
        m=List(m,j-48).max
    }
    for(i<-1 to m)
    {
        for(j<-a)
        {
            print(j(m-i))
        }
        println
    }
}

I'm sure a better facility with for comprehensions would mean I could cut some characters from this.

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

JavaScript, 235 208 195 bytes

function _(b){for(e=Math.max.apply(0,b.join().split(",")),f=[],c=i=0;i<e;i++){for(
c=[],a=0;a<b[0].length;a++)for(d=c[a]=0;d<b.length;d++)b[d][a]>i&&c[a]++;f[e-i-1]
=c.join("")}return f.join("\n")}

Just for the record, this is the code I made up before posting the question. (Smallened now)

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

Haskell Version (Now optimized)

import Data.List
import Text.Parsec
import Text.Parsec.String

main= readFile"in.txt">>=(\t->either print(putStrLn.intercalate"\n".map(concatMap show).(\j->map (\n->(map(length.(filter(>=n)))(transpose$reverse j))) (reverse [1..(maximum$map maximum j)])))(parse(many1$many1 digit>>=(\x->newline>>(return$map(read.return)x)))""t))

Ungolfed version

import Data.List (foldl', transpose, intercalate)
import Text.Parsec
import Text.Parsec.String

-- Source:  http://codegolf.stackexchange.com/questions/2657/swapping-heightmaps-to-depthmaps

digitArray :: Parser [[Int]]
digitArray = many1 $ do xs <- many1 digit
                        optional newline
                        return $ map (read . return) xs

maxHeight :: Ord c => [[c]] -> c
maxHeight = maximum . (map maximum)

heightToDepth :: [[Int]] -> [[Int]]
heightToDepth ins = level (maxHeight ins)
        where level 0 = []
              level n = (map (length . (filter (>=n))) xs) : level (n-1)
              xs      = transpose $ reverse ins

lookNice xs = intercalate ['\n'] $ map (concatMap show) xs

main = do inText <- readFile "in.txt"
          case parse digitArray "" inText of
              Left err -> print err
              Right xs -> putStrLn $ lookNice $ heightToDepth xs
\$\endgroup\$
  • \$\begingroup\$ Long answers to [code-golf] questions are acceptable when the length arises from using unsuitable languages (say fortran 77), but you are still expected to make an attempt to golf them. Not even bothering to reduce your identifiers to single letter is failing to get into the spirit of the game, which I suspect is the cause of the downvotes. \$\endgroup\$ – dmckee May 25 '11 at 15:41
  • \$\begingroup\$ Welcome to code golf! Can you separate your golfed code from your ungolfed code, and put a character count in your post for your golfed code please? Thanks! It will make your post a little easier to read and is the general pattern we use. \$\endgroup\$ – mellamokb May 25 '11 at 20:44
  • \$\begingroup\$ The goal of code golf is to create the shortest code possible. Yours is rather verbose, so try harder! \$\endgroup\$ – FUZxxl May 26 '11 at 12:58
1
\$\begingroup\$

Python, 117 chars

import sys
a=zip(*sys.stdin)[:-1]
n=int(max(map(max,a)))
while n:print''.join(`sum(e>=`n`for e in r)`for r in a);n-=1

Similar to Ventero's Ruby solution.

\$\endgroup\$
0
+200
\$\begingroup\$

APL (Dyalog Extended), 14 bytes

{⊖⍉+⌿⍵≥⍀⍳⌈/,⍵}

Try it online!

{⊖⍉+⌿⍵≥⍀⍳⌈/,⍵}    Monadic function:
             ⍵     Start with a 2D array ⍵.
          ⌈/,      Find the overall maximum value h.
         ⍳         Make the list 1...h
       ≥⍀          Make a ≥ table between that list and ⍵.
                   Now we have a 3D matrix where position [a,b,c]
                   represents whether ⍵[a,b] is at least c.
    +⌿             We sum along the outermost (first) dimension, 
                   since that corresponds to a column of ⍵.
                   Now we have a 2D matrix where position [b,c]
                   represents how many values in column b of ⍵ are at least c.
  ⍉                Transpose so the heights are rows.
 ⊖                 Flip vertically.
\$\endgroup\$
0
\$\begingroup\$

Clojure, 102 bytes

#(for[h(range(apply max(flatten %))0 -1)](map(fn[w _](count(for[r % :when(>=(r w)h)]_)))(range)(% 0)))
\$\endgroup\$
0
\$\begingroup\$

Japt, 12 bytes

c rÔÆÕËè>X
w

Try all test cases

Outputting the rows in reversed order would save 2 bytes, taking input in column-major order would save 1 byte, doing both would (naturally) save 3 bytes

Explanation:

c rÔ          #Find the maximum height
    Æ         #For each number X in the range [0...max_height]:
     Õ        # Get the columns of the input
      Ë       # For each column:
       è>X    #  Count how many items are greater than X

w             #Reverse the output
\$\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.