Skip to content

Commit

Permalink
feat(arrays): optimal task assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Jun 14, 2024
1 parent 03e848f commit fcc5584
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions algorithms/arrays/optimal_task_assignment/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Optimal Task Assignment

Assign tasks to workers so that the time it takes to complete all the tasks is minimized given a count of workers and an
array where each element indicates the duration of a task.

We wish to determine the optimal way in which to assign tasks to some workers. Each worker must work on exactly two
tasks. Tasks are independent of each other, and each task takes a certain amount of time.
18 changes: 18 additions & 0 deletions algorithms/arrays/optimal_task_assignment/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from typing import List, Tuple


def optimal_task_assignment(tasks: List[int]) -> List[Tuple[int, int]]:
"""
After sorting the array, the for loop iterates for half the length of the array adds the pairs using indexing to a
list. So ~x is the bitwise complement operator which puts a negative sign in front of x and subtracts 1 from it.
Thus, the negative numbers as indexes mean that you count from the right of the array instead of the left. So,
numbers[-1] refers to the last element, numbers[-2] is the second-last, and so on. In this way, we are able to pair
the numbers from the beginning of the array to the end of the array.
"""
sorted_tasks = sorted(tasks)
result: List[Tuple[int, int]] = []

for x in range(len(sorted_tasks) // 2):
result.append((sorted_tasks[x], sorted_tasks[~x]))

return result
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import unittest
from . import optimal_task_assignment


class OptimalTaskAssignmentTestCase(unittest.TestCase):
def test_1(self):
"""Should return [(2,7), (3,6),(5,5)] from [6, 3, 2, 7, 5, 5]"""
tasks = [6, 3, 2, 7, 5, 5]
expected = [(2, 7), (3, 6), (5, 5)]
actual = optimal_task_assignment(tasks)
self.assertEqual(expected, actual)


if __name__ == '__main__':
unittest.main()

0 comments on commit fcc5584

Please sign in to comment.