## Jump!

### February 3, 2017

Our solution visits each cell in order:

(define (jump xs) (let loop ((reachable 0) (xs xs)) (if (null? xs) #t (let ((next (max (- reachable 1) (car xs)))) (if (zero? next) #f (loop next (cdr xs)))))))

From any given cell, the maximum reachable position `reachable`

is the greater of one less than the `reachable`

of the previous cell, or the value in the current cell. If `reachable`

goes to 0 before reaching the end of the array, the game is unwinnable. Here are three winnable games and three unwinnable games:

> (jump '(1 3 3 0 0 2 0 4 1 3 0)) #t > (jump '(2 0 3 5 0 0 3 0 0 6 3)) #t > (jump '(3 1 4 3 5 0 0 0 3 1 0)) #t > (jump '(4 4 0 3 0 1 2 2 1 0 0)) #f > (jump '(3 2 0 1 4 3 1 0 0 0 0)) #f > (jump '(5 2 0 0 1 0 6 0 0 2 9)) #f

You can run the program at http://ideone.com/aPTEbc.

Advertisements

Pages: 1 2

In winnablep, return-from is used to shortcut the exit when the result is known.

On the other hand, in winnable-path, we use O(log(n)) stack space to avoid allocating O(n) temporary cons cells, and instead we cons the path only once we found it.

Two solutions in Python. The first models the problem as finding the shortest path in a DAG (function dag_sp is omitted). You have to set up the weights for all possible jumps.

A Haskell version. If we’re looking at an empty list then either the initial list was empty, which we treat as a win, or we’ve made it to the end of a non-empty list, which is by definition a win. If we ever land on a 0 then we’re on a losing path. Otherwise, if any of the paths within n jumps of our current position is a winner then we’ve won.

Here’s another Haskell program that prints out all winning paths. It has a similar structure to the previous program.