Jump game finally (?) but differently than solutions

main
Dan Buch 6 months ago
parent 54a7a2340c
commit 2f3ce704b2
Signed by: meatballhat
GPG Key ID: A12F782281063434

@ -328,18 +328,6 @@ class JumpSpace(typing.NamedTuple):
return ret
def count_min_jumps_from_board(board: list[int]) -> int:
if len(board) == 1:
return 0
complete_paths = collect_complete_jump_paths_from_board(board)
if len(complete_paths) == 0:
return -1
return min([len(p) - 1 for p in complete_paths])
def collect_complete_jump_paths_from_board(board: list[int]) -> list[list[int]]:
return [
p
@ -354,3 +342,42 @@ def collect_jump_paths_from_board(board: list[int]) -> list[list[int]]:
return []
return space.jump_paths()
# NOTE: the expensive way goes like this
# complete_paths = collect_complete_jump_paths_from_board(board)
# if len(complete_paths) == 0:
# return -1
# return min([len(p) - 1 for p in complete_paths])
def count_min_jumps_from_board(board: list[int]) -> int:
return len(collect_min_jumps_from_board(board))
def collect_min_jumps_from_board(board: list[int]) -> list[int]:
if len(board) < 3:
return list(range(1, len(board)))
jumps: list[int] = []
range_begin: int = 0
val = board[range_begin]
range_end: int = range_begin + val + 1
while range_end < len(board):
potential_jumps = board[range_begin:range_end]
scored_jumps = [
(val + range_begin + i, val, range_begin + i)
for i, val in enumerate(potential_jumps)
]
_, val, space = max(scored_jumps)
jumps.append(space)
range_begin = space
range_end = range_begin + val + 1
return jumps + [len(board) - 1]

@ -290,6 +290,22 @@ def test_collect_complete_jump_paths_from_board(
[1, 2],
1,
),
(
[6, 2, 6, 1, 7, 9, 3, 5, 3, 7, 2, 8, 9, 4, 7, 7, 2, 2, 8, 4, 6, 6, 1, 3],
4,
),
(
[3, 4, 3, 2, 5, 4, 3],
3,
),
(
[3, 2, 1],
1,
),
(
[1, 2, 3],
2,
),
],
)
def test_count_min_jumps_from_board(board: list[int], expected: int):

Loading…
Cancel
Save