Skip to content

Instantly share code, notes, and snippets.

@TheSithPadawan
Last active March 10, 2022 19:53
Show Gist options
  • Save TheSithPadawan/da397ff223882535493644f563a50d19 to your computer and use it in GitHub Desktop.
Save TheSithPadawan/da397ff223882535493644f563a50d19 to your computer and use it in GitHub Desktop.
"""
OO Design: design data types for Amazon locker and packages
Requirement: Design an optimized algorithm to fit the package in the right locker
"""
import bisect
class Locker:
def __init__(self, x, y , z, **kwargs):
self.length = x
self.width = y
self.height = z
self.locker_id = kwargs.get('id', None)
self.vacant = True
def get_max_dimension(self):
return max([self.length, self.width, self.height])
class Package:
def __init__(self, x, y, z, **kwargs):
self.length = x
self.width = y
self.height = z
self.package_id = kwargs.get('id', None)
class LockerLocator:
def __init__ (self, lockers = None):
self.lockers = lockers
self.sorted_lockers = sorted((x.get_max_dimension(), x) for x in self.lockers)
def find_locker_for_box(self, box):
# given a box, find a suitable unoccupied locker
# lockers in the locator is sorted by max dimension
# first fit the box's maximum dimension, then try to rotate the box
# and find the first fit for the remaining two dimensions
maxd = max([box.length, box.width, box.height])
index = bisect.bisect_left(self.sorted_lockers, maxd)
for i in range(index, len(self.sorted_lockers)):
if not self.sorted_lockers[i][1].vacant:
continue
if self.check_fit(self.sorted_lockers[i][1], box):
self.sorted_lockers[i][1].vacant = False
return self.sorted_lockers[i][1].id
def check_fit(self, locker, box):
"""
sort the three dimensions, and check each dimension of the box fits
into the locker
"""
locker_dimensions = sorted([locker.length, locker.width, locker.height])
box_dimensions = sorted([box.length, box.width, box.height])
for i in range(3):
if box_dimensions[i] <=locker_dimensions[i]:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment