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):

211   <- Depthmap

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.



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


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.


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


Input:     Ouput:

5321       0001
1456       1012
2105       1112

Input:     Output:

22         01
13         12
00         22

Input:     Output:    (of the sample image)

232        010
210        211
101        322
  • \$\begingroup\$ Can you provide a sample input / output for the example image you posted? \$\endgroup\$
    – mellamokb
    Commented May 24, 2011 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\$ Commented May 24, 2011 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\$ Commented May 24, 2011 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
    Commented May 25, 2011 at 11:26
  • 1
    \$\begingroup\$ Don't worry. It's a fine task as it is now. \$\endgroup\$
    – Joey
    Commented May 25, 2011 at 17:15

13 Answers 13


Golfscript, 42 chars



$ golfscript 2657.gs < 2657-1.txt 

$ golfscript 2657.gs < 2657-2.txt 

$ golfscript 2657.gs < 2657-3.txt 
  • \$\begingroup\$ Congratulations. \$\endgroup\$
    – pimvdb
    Commented May 25, 2011 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
    Commented May 25, 2011 at 17:07
  • \$\begingroup\$ Since the accepted answer can be changed any time again, where is the harm? \$\endgroup\$
    – Joey
    Commented May 25, 2011 at 17:38
  • \$\begingroup\$ +100: 42 chars :-) \$\endgroup\$
    – mellamokb
    Commented May 26, 2011 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\$ Commented May 26, 2011 at 20:11

Ruby 1.9, 102 characters

f.flatten.max.downto(49){|j|puts f.transpose.map{|n|n.count{|r|r>=j}}*""}

Passes all testcases.


Windows PowerShell, 108 111 114


Passes all test cases.


Haskell, 118 characters

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

  • Edit (122 → 118): avoid filtering by only iterating to maximal height

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
    val a=Array.ofDim[Int](l.head.size,10)
    for(i<-l;(j,q)<-i.zipWithIndex;x<-1 to j-48)
    for(i<-1 to m)

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


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.join("")}return f.join("\n")}

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


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
  • \$\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\$ Commented May 25, 2011 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
    Commented May 25, 2011 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
    Commented May 26, 2011 at 12:58

Python, 117 chars

import sys
while n:print''.join(`sum(e>=`n`for e in r)`for r in a);n-=1

Similar to Ventero's Ruby solution.


Uiua, 10 bytes


Try it online!

⇌⍉/+⬚0∵↯∶1    input: a matrix of numbers
        ∵↯∶1    replace each number with that many 1s repeated...
     ⬚0         ...filling the remaining space in the 3D array with zeros
   /+            sum layers element-wise
⇌⍉              transpose and reverse to put the result in correct orientation

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.

Clojure, 102 bytes

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

Japt, 12 bytes

c rÔÆÕËè>X

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


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

Julia, 55 bytes

!a=[sum(a[:,j].>m-i) for i=1:(m=max(a...)),j=axes(a,2)]

Attempt This Online!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.