Last active
December 28, 2015 04:59
-
-
Save glenjamin/7446385 to your computer and use it in GitHub Desktop.
*That* interview question, explored
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns water | |
(require [clojure.string :as s])) | |
(defn right-reductions [f l] | |
"just like (reductions) but form the right" | |
(reverse (reductions f (reverse l)))) | |
(defn transpose [m] | |
"Transpose a list of lists" | |
(apply mapv vector m)) | |
(defn fill [land] | |
"The main water filling function" | |
(map - | |
(map min (reductions max land) | |
(right-reductions max land)) | |
land)) | |
; Some rendering stuff | |
(defn line [land water maxi] | |
"Draw a line of water" | |
(concat | |
(repeat land "#") | |
(repeat water "~") | |
(repeat (- maxi land water) " "))) | |
(defn render [land] | |
"Give some land, calculate the fill and render it" | |
(let [water (fill land) | |
maxi (apply max land)] | |
(->> (map line land (fill land) (repeat maxi)) | |
(transpose) | |
(map (partial apply str)) | |
(reverse) | |
(s/join "\n")))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def scan(f, l): | |
o = [l[0]] | |
for i in l[1:]: | |
o.append(f(o[-1], i) | |
return o | |
def water(land): | |
return map(min, scan(max, l), reversed(maxl(reversed(l)))) | |
def fill(land): | |
return map(lambda a, b: a - b, water(land), land) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment