Last active
April 26, 2016 17:13
-
-
Save adleroliveira/5d69c69c6ffb829b94c00310f3cc421c to your computer and use it in GitHub Desktop.
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
let edificios = [ | |
[2, 9, 10], | |
[2, 4, 12], | |
[3, 7, 15], | |
[5, 12, 12], | |
[15, 20, 10], | |
[19, 24, 8] | |
] | |
function skyline(buildings){ | |
//this line get the most right wall of the buildings | |
let maxRight = Math.max(...buildings.map(b => b[1])) | |
//this function returns an array of buildings that appear on a given x position | |
let buildingsOfX = x => buildings.filter(b => x >= b[0] && x <= b[1]) | |
//this variable holds the previous height as the loop goes on | |
let heightPointer = 0 | |
//this variable will hold the points that outline the buildings | |
let result = [] | |
//for each point from 1 to the outter left wall of buildings get the max height for that x | |
for(let x=1; x<=maxRight+1; x++){ | |
//this function return all heights of all buildings from a given x point | |
let heightsOfX = buildingsOfX(x).map(b => b[2]) | |
//this returns the height of the tallest building of the current x point | |
let maxHeigth = heightsOfX.length? Math.max(...heightsOfX): 0 | |
//every time that the height changes we push previous and current point to the result array | |
if(maxHeigth !== heightPointer){ | |
//push the previous and current points to the result array | |
result.push([maxHeigth < heightPointer? x-1: x, heightPointer]) | |
result.push([maxHeigth < heightPointer? x-1: x, maxHeigth]) | |
//update the current height | |
heightPointer = maxHeigth | |
} | |
} | |
return result.map(x => x.join(',')).join('\n') | |
} | |
console.log(skyline(edificios)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment