Skip to content

Instantly share code, notes, and snippets.

@exarkun
Created March 20, 2023 20:17
Show Gist options
  • Save exarkun/9cca423d82de14f5409420f9753aafe9 to your computer and use it in GitHub Desktop.
Save exarkun/9cca423d82de14f5409420f9753aafe9 to your computer and use it in GitHub Desktop.
def canPlaceItems(templateBox: tuple[T], items: tuple[T], box: tuple[T]):
return templateBox[len(box):len(box)+len(items)] == items
def placeItem(items: tuple[T], boxes: tuple[tuple[T]]) -> tuple[tuple[T]]:
for n, box in enumerate(boxes):
if canPlaceItem(items, box):
# It fits here, place it.
return boxes[:n] + (box + items,) + boxes[n + 1:]
# It fits nowhere, create a new box.
return boxes + (items,)
def main():
expected = ("foo", "bar", "baz")
actual = [
# A
("foo",)
# A
("bar", "baz"),
# B
("foo", "bar")
# C
("foo",),
# C
("bar", "baz"),
# B
("baz",)
# D
("foo",),
# E
("foo",),
# D
("bar", "baz"),
# E
("bar", "baz"),
]
boxes = foldl(placeItem, partial(canPlaceItems, expected), (), actual)
assert all(lambda b: b == expected, boxes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment