Skip to content

Instantly share code, notes, and snippets.

@alexshive
Created July 13, 2022 15:06
Show Gist options
  • Select an option

  • Save alexshive/1357cbea53b476ba116a6dd14ab19496 to your computer and use it in GitHub Desktop.

Select an option

Save alexshive/1357cbea53b476ba116a6dd14ab19496 to your computer and use it in GitHub Desktop.
Write a function that takes a list of pin objects, each with a height attribute, and a number of columns and returns a grid layout. You put the next pin in the column with the shortest total height (sum of heights of pins in the column) so far. If there is a tie, insert the pin into the left most column. Return a list which contains a list for e…
struct Pin {
var id: Int
var height: Int
}
func layout(_ pins: [Pin], col: Int) -> [[Pin]] {
func calcHeight() -> Int {
var sum = Int.max
var indexMax = 0
for (ind,o) in output.enumerated() {
var temp = 0
for oo in o {
temp += oo.height
}
if (temp < sum) {
indexMax = ind
sum = temp
}
}
return indexMax
}
var output = [[Pin]]()
// init
for c in 0...col-1 {
output.append([pins[c]])
}
for p in col...pins.count-1 {
let pin = pins[p]
let id = calcHeight()
output[id].append(pin)
}
return output
}
let pins = [
Pin(id: 1, height: 300),
Pin(id: 2, height: 200),
Pin(id: 3, height: 250),
Pin(id: 4, height: 350),
Pin(id: 5, height: 100),
]
layout(pins, col:2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment