Backtracking first working version
This commit is contained in:
65
Backtracking/cs412_hw3_a.py
Normal file
65
Backtracking/cs412_hw3_a.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
name: Nicholas Tamassia
|
||||
|
||||
Honor Code and Acknowledgments:
|
||||
|
||||
This work complies with the JMU Honor Code.
|
||||
|
||||
Comments here on your code and submission.
|
||||
"""
|
||||
|
||||
|
||||
# I'm going to pat myself on the back, I wrote this in one shot
|
||||
# and it worked first try for the full credit
|
||||
def construct(sections: list[int], target: int) -> dict[int, int]:
|
||||
# We want to start with the largest sections first
|
||||
rev_sections = sorted(sections, reverse=True)
|
||||
|
||||
# Initialize to a worse-than-worst-case scenario
|
||||
best_sections: dict[int, int] = {i: target for i in sections}
|
||||
best_num: int = target * len(sections)
|
||||
|
||||
def recurse(
|
||||
cur_sections: dict[int, int], cur_height: int, num_sections: int
|
||||
) -> None:
|
||||
nonlocal best_sections, best_num
|
||||
|
||||
if num_sections >= best_num:
|
||||
return
|
||||
|
||||
if cur_height == target:
|
||||
best_sections = cur_sections
|
||||
best_num = num_sections
|
||||
return
|
||||
|
||||
for i in rev_sections:
|
||||
if cur_height + i > target:
|
||||
continue
|
||||
|
||||
new_sections = cur_sections.copy()
|
||||
new_sections[i] += 1
|
||||
|
||||
recurse(new_sections, cur_height + i, num_sections + 1)
|
||||
|
||||
recurse({i: 0 for i in sections}, 0, 0)
|
||||
return best_sections
|
||||
|
||||
|
||||
# All modules for CS 412 must include a main method that allows it
|
||||
# to imported and invoked from other python scripts
|
||||
def main():
|
||||
sections: list[int] = list(map(int, input().split(" ")))
|
||||
target: int = int(input())
|
||||
|
||||
best_sections = construct(sections, target)
|
||||
best_num = 0
|
||||
|
||||
for i, n in sorted(best_sections.items()):
|
||||
best_num += n
|
||||
print(f"{n} of length {i}")
|
||||
|
||||
print(f"{best_num} rocket sections minimum")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
2
Backtracking/inputs/sample1.txt
Normal file
2
Backtracking/inputs/sample1.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
1 2 5 7
|
||||
15
|
||||
2
Backtracking/inputs/sample2.txt
Normal file
2
Backtracking/inputs/sample2.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
1 2 3 5 7 14
|
||||
15
|
||||
2
Backtracking/inputs/sample3.txt
Normal file
2
Backtracking/inputs/sample3.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
1 9
|
||||
17
|
||||
2
Backtracking/inputs/sample4.txt
Normal file
2
Backtracking/inputs/sample4.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
1 9 10
|
||||
18
|
||||
2
Backtracking/inputs/sample5.txt
Normal file
2
Backtracking/inputs/sample5.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
1 9 10 90 100
|
||||
198
|
||||
Reference in New Issue
Block a user