Skip to content

Instantly share code, notes, and snippets.

@CrabDude
Created June 23, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrabDude/b5a38ddf83cc28e96e03d3c60dcdfc00 to your computer and use it in GitHub Desktop.
Save CrabDude/b5a38ddf83cc28e96e03d3c60dcdfc00 to your computer and use it in GitHub Desktop.
/*
pins: [{
id, height
}]
*/
// orderedByHeight = [{height: 0, index: 0}]
// Output: datastructure to describe pins
function layoutPins(pins, cols) {
// [{height: 0, index: 0}]
let heights = Array.apply(null, Array(cols)).map((v, k) => {
return {height: 0, index: k}
})
// [0, 0, 0, 0, 0]
let graph = Array.apply(null, Array(cols)).map(() => [])
for (let pin of pins) {
let col = heights.shift()
col.height += pin.height
let inserted = false
for (let i=0; i<heights.length; i++) {
let height = heights[i]
if (height.height > col.height) {
heights.splice(i-1, 0, col)
inserted = true
break
}
}
if (!inserted) heights.push(col)
graph[col.index].push(pin)
}
return graph
}
let inputPins = [
{
id: 1,
height: 300
},
{
id: 2,
height: 200
},
{
id: 3,
height: 250
},
{
id: 4,
height: 350
}]
console.log(layoutPins(inputPins, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment