Skip to content

Commit 176ec47

Browse files
authored
Add sadness calculator and backtracking for laptop allocation
Implement calcutate_sandess and backtracking for laptop allocation based on user preferences and minimize sadness.
1 parent 964c731 commit 176ec47

File tree

1 file changed

+46
-12
lines changed

1 file changed

+46
-12
lines changed

laptop-allocation.py

Lines changed: 46 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,18 +31,52 @@ class Laptop:
3131
operating_system: OperatingSystem
3232
assigned: bool = False
3333

34+
# sadnes calculator
35+
def calculate_sadness(person: Person, laptop: Laptop) -> int:
36+
if laptop.operating_system in person.preferred_operating_system:
37+
return person.preferred_operating_system.index(laptop.operating_system)
38+
return 100
39+
3440
def allocate_laptops(people: List[Person], laptops: List[Laptop]) -> Dict[str, int]:
35-
allocation = {}
36-
for person in people:
37-
for os in person.preferred_operating_system:
38-
for laptop in laptops:
39-
if (laptop.operating_system == os and not laptop.assigned):
40-
allocation[person.name] = laptop.id
41-
assigned = True
42-
break
43-
if assigned:
44-
break
45-
return allocation
41+
best_allocation: Dict[str, int] = {}
42+
min_total_sadness = float("inf")
43+
44+
def backtrack(person_index: int, used_laptops: set, current_alloc: Dict[str, int], current_sadness: int):
45+
nonlocal best_allocation, min_total_sadness
46+
47+
# If all people assigned
48+
if person_index == len(people):
49+
if current_sadness < min_total_sadness:
50+
min_total_sadness = current_sadness
51+
best_allocation = current_alloc.copy()
52+
return
53+
54+
# stop if worse than best
55+
if current_sadness >= min_total_sadness:
56+
return
57+
58+
person = people[person_index]
59+
60+
for laptop in laptops:
61+
if laptop.id not in used_laptops:
62+
sadness = calculate_sadness(person, laptop)
63+
64+
used_laptops.add(laptop.id)
65+
current_alloc[person.name] = laptop.id
66+
67+
backtrack(
68+
person_index + 1,
69+
used_laptops,
70+
current_alloc,
71+
current_sadness + sadness
72+
)
73+
74+
# Undo choice
75+
used_laptops.remove(laptop.id)
76+
del current_alloc[person.name]
77+
78+
backtrack(0, set(), {}, 0)
79+
return best_allocation
4680

4781
people = [
4882
Person(name="Imran", age=22, preferred_operating_system=[OperatingSystem.UBUNTU,OperatingSystem.ARCH,OperatingSystem.MACOS]),
@@ -59,4 +93,4 @@ def allocate_laptops(people: List[Person], laptops: List[Laptop]) -> Dict[str, i
5993

6094
if __name__ == "__main__":
6195
allocation = allocate_laptops(people, laptops)
62-
print("Allocation:", allocation)
96+
print("Allocation:", allocation)

0 commit comments

Comments
 (0)