Created
December 13, 2021 23:25
-
-
Save zedchance/839a6dddfe4bcfc0b3fc57fde0e4130e to your computer and use it in GitHub Desktop.
Divide books ordered on a bookshelf so each person reads roughly the same amount
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# book partitioning so each person reads roughly the same amount | |
import math | |
def solve(pages, people): | |
n = len(pages) | |
m = [[0 for j in range(people)] for i in range(n)] | |
s = [[-1 for j in range(people)] for i in range(n)] | |
# work left to right | |
for j in range(people): | |
# top to bottom | |
for i in range(n): | |
if j == 0: | |
m[i][j] = sum(pages[:i + 1]) | |
else: | |
potential = [max(m[k][j - 1], sum(pages[k + 1:i + 1])) for k in range(i + 1)] | |
new = math.inf | |
for k, p in enumerate(potential): | |
if p < new: | |
m[i][j] = p | |
s[i][j] = k | |
new = p | |
for r1, r2 in zip(m, s): | |
for col in r1: | |
print(f'{col:5}', end=" ") | |
print(end=" ") | |
for col in r2: | |
print(f'{col:5}', end=" ") | |
print() | |
print() | |
def _print_solution(i, j): | |
if j == 0: | |
for k in range(i + 1): | |
print(pages[k], end=" ") | |
else: | |
_print_solution(s[i][j], j - 1) | |
print("|", end=" ") | |
for k in range(s[i][j] + 1, i + 1): | |
print(pages[k], end=" ") | |
print("partitions:") | |
_print_solution(n - 1, people - 1) | |
print(f'\n{m[-1][-1]} max pages read by 1 person') | |
if __name__ == '__main__': | |
t1 = [100, 100, 100, 100, 100, 100, 100, 100, 100] | |
t2 = [100, 200, 300, 400, 500, 600, 700, 800, 900] | |
t3 = [694, 837, 880, 688, 331, 430, 111, 514, 605, 291, 278, 858, 554, 871, 898, 343, 628, 287, 782, 814, 273, 236, 625, 922, 735] | |
solve(t3, 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output