Knight's Tour Depth First Search Backtracking - recursion

I'm working on a knight's tour implementation using DFS.
My problem is, when I run it, it works fine up to step 20, but after that the algorithm freaks out and outputs this on a 5x5 board (there is a solution for a 5x5 board starting at (0,0)):
(1 10 5 16 24)
(4 15 2 11 20)
(9 6 17 23 22)
(14 3 8 19 12)
(7 18 13 21 25)
*Legal successors must be 0 <= row < n and 0 <= column < n and not be a previous step.
My implementation involves generating *legal successors using the genSuccessors function, throwing them onto a stack and recursively running the algorithm with the item at the top of the stack as the new current position. I only increment the step_count (in charge of tracking the order of squares the knight visits) if the next position is a step not taken before. When I cannot generate any more children, the algorithm explores other alternatives in the frontier until frontier empty (fail condition) or the step_count = # squares on the board (win).
I think the algorithm in general is sound.
edit: I think the problem is that when I can't generate more children, and I go to explore the rest of the frontier I need to scrap some of the current tour. My question is, how do I know how far back I need to go?
Graphically, in a tree I think I would need to go back up to the closest node that had a branch to an unvisited child and restart from there scrapping all the nodes visited when going down the previous (wrong) branch. Is this correct? How would I keep track of that in my code?
Thanks for reading such a long post; and thanks for any help you guys can give me.

Yikes! Your code is really scary. In particular:
1) It uses mutation everywhere.
2) It tries to model "return".
3) It doesn't have any test cases.
I'm going to be a snooty-poo, here, and simply remark that this combination of features makes for SUPER-hard-to-debug programs.
Also... for DFS, there's really no need to keep track of your own stack; you can just use recursion, right?
Sorry not to be more helpful.
Here's how I'd write it:
#lang racket
;; a position is (make-posn x y)
(struct posn (x y) #:transparent)
(define XDIM 5)
(define YDIM 5)
(define empty-board
(for*/set ([x XDIM]
[y YDIM])
(posn x y)))
(define (add-posn a b)
(posn (+ (posn-x a) (posn-x b))
(+ (posn-y a) (posn-y b))))
;; the legal moves, represented as posns:
(define moves
(list->set
(list (posn 1 2) (posn 2 1)
(posn -1 2) (posn 2 -1)
(posn -1 -2) (posn -2 -1)
(posn 1 -2) (posn -2 1))))
;; reachable knights moves from a given posn
(define (possible-moves from-posn)
(for/set ([m moves])
(add-posn from-posn m)))
;; search loop. invariant: elements of path-taken are not
;; in the remaining set. The path taken is given in reverse order.
(define (search-loop remaining path-taken)
(cond [(set-empty? remaining) path-taken]
[else (define possibilities (set-intersect (possible-moves
(first path-taken))
remaining))
(for/or ([p possibilities])
(search-loop (set-remove remaining p)
(cons p path-taken)))]))
(search-loop (set-remove empty-board (posn 0 0)) (list (posn 0 0)))
;; start at every possible posn:
#;(for/or ([p empty-board])
(search-loop (set-remove empty-board p) (list p)))

Related

(Lisp program) Create a list of Pell numbers using iterative approach [duplicate]

How do I use cons or other way to print a list of Pell numbers till the Nth number?
(defun pellse (k)
(if (or (zerop k) (= k 1))
k
(+ (* 2 (pellse (- k 1)))
(pellse (- k 2)))))
(print (pellse 7))
Here is how to do it in a way that won’t be exponential:
(defun pells (n)
(loop repeat n
for current = 0 then next
and next = 1 then (+ (* 2 next) current)
collect current))
The time complexity to calculate the nth element given the two previous elements is O(log(Pn)) where Pn is the nth Pell number; you need log(Pn) bits for the answer and log(Pn) operations for the addition. We don’t actually need to work out what Pn is: It is defined by a simple linear recurrence relation so the solution must be exponential so log(Pn) = O(n). Therefore the complexity of calculating the first n Pell numbers is O(n*n) = O(n2).
One cannot[*] do better than O(n2) as one must write O(n2) bits to represent all these numbers.
[*] Although I very much doubt this, it might, in theory, be possible to represent the list in some more compact way by somehow sharing data.
Here is an approach to solving this problem which works by defining an infinite stream of Pell numbers. This is based on the ideas presented in SICP, and particularly section 3.5. Everyone should read this book.
First of all we need to define a construct which will let us talk about infinite data structures. We do this by delaying the evaluation of all but a finite part of them. So start with a macro called delay which delays the evaluation of a form, returning a 'promise' (which is a function of course), and a function called force which forces the system to make good on its promise:
(defmacro delay (form)
;; Delay FORM, which may evaluate to multiple values. This has
;; state so the delayed thing is only called once.
(let ((evaluatedp-n (make-symbol "EVALUATEDP"))
(values-n (make-symbol "VALUES")))
`(let ((,evaluatedp-n nil) ,values-n)
(lambda ()
(unless ,evaluatedp-n
(setf ,evaluatedp-n t
,values-n (multiple-value-list
(funcall (lambda () ,form)))))
(values-list ,values-n)))))
(defun force (promise)
;; force a promise (delayed thing)
(funcall promise))
(This implementation is slightly overcomplex for our purposes, but it's what I had to hand.).
Now we'll use delay to define streams which are potentially infinite chains of conses. There are operations on these corresponding to operations on conses but prefixed by stream-, and there is an object called null-stream which corresponds to () (and is in fact the same object in this implementation).
(defmacro stream-cons (car cdr)
;; a cons whose cdr is delayed
`(cons ,car (delay ,cdr)))
(defun stream-car (scons)
;; car of a delayed cons
(car scons))
(defun stream-cdr (scons)
;; cdr of a delayed cons, forced
(force (cdr scons)))
(defconstant null-stream
;; the empty delayed cons
nil)
(defun stream-null (stream)
;; is a delayed cons empty
(eq stream null-stream))
Now define a function pell-stream which returns a stream of Pell numbers. This function hand-crafts the first two elements of the stream, and then uses a generator to make the rest.
(defun pell-stream ()
;; A stream of Pell numbers
(labels ((pell (pn pn-1)
(let ((p (+ (* 2 pn) pn-1)))
(stream-cons p (pell p pn)))))
(stream-cons 0 (stream-cons 1 (pell 1 0)))))
And now we can simply repeatedly takes stream-cdr to compute Pell numbers.
(defun n-pell-numbers (n)
(loop repeat n
for scons = (pell-stream) then (stream-cdr scons)
collect (stream-car scons)))
And now
> (n-pell-numbers 20)
(0
1
2
5
12
29
70
169
408
985
2378
5741
13860
33461
80782
195025
470832
1136689
2744210
6625109)
Note that, in fact, pell-stream can be a global variable: it doesn't need to be a function:
(defparameter *pell-stream*
(labels ((pell (pn pn-1)
(let ((p (+ (* 2 pn) pn-1)))
(stream-cons p (pell p pn)))))
(stream-cons 0 (stream-cons 1 (pell 1 0)))))
(defun n-stream-elements (stream n)
(loop repeat n
for scons = stream then (stream-cdr scons)
collect (stream-car scons)))
If we define a little benchmarking program:
(defun bench-pell (n)
(progn (n-stream-elements *pell-stream* n) n))
Then it's interesting to see that this is clearly essentially a linear process (it slows down for later elements because the numbers get big and so operations on them take a long time), and that the stateful implementation of promises makes it much faster after the first iteration (at the cost of keeping quite a lot of bignums around):
> (time (bench-pell 100000))
Timing the evaluation of (bench-pell 100000)
User time = 2.020
System time = 0.803
Elapsed time = 2.822
Allocation = 1623803280 bytes
441714 Page faults
100000
> (time (bench-pell 100000))
Timing the evaluation of (bench-pell 100000)
User time = 0.007
System time = 0.000
Elapsed time = 0.006
Allocation = 1708248 bytes
0 Page faults
100000
One possible solution would be to use the LOOP macro of Common Lisp, e.g.:
(print
(loop for x in '(1 2 3 4 5 6 7)
for y = (pellse x)
collect y))
That prints out the following result:
(1 2 5 12 29 70 169)
Based on this, you can build the following function:
(defun list-of-n-pell-numbers (n)
(loop for x from 0 to n
for y = (pellse x)
collect y))
And run it like the following:
(print (list-of-n-pell-numbers 7))
(0 1 2 5 12 29 70 169)
But please be careful when using this code, because your definition of pellse function is recursive, and has the risk of a stack overflow: make it call itself repeatedly enough (e.g. for big values of N), and it might blow up the call stack, unless you do some tail recursion. You might want to check the following explanations:
http://www.lispworks.com/documentation/lcl50/aug/aug-51.html
https://0branch.com/notes/tco-cl.html

How to get the lowest integer out of a vector in Racket

I'm trying to get the lowest integer out of a vector only containing numbers. I know how to do it with lists. You compare the first two values of the list and depending on which is larger you either save your value to output it later or call the function again with the rest of the list (all elements except the first) using the cdr procedure.
But with vectors I'm completely lost. My guess would be that the way of thinking about the solution would be the same for lists and vectors. I've been reading on the racket-lang website but haven't been able to come up with a solution to the problem. The procedures I've been experimenting most with are vector-ref and vector-length as they seem to be the most useful in this problem (but this is my first time working with vectors so what do I know).
So my two questions are:
How can we get all values except the first from a vector? Is there a procedure like cdr but for vectors?
If you were working with lists you would use cons to save the values you would want to output. But is there a similar way of doing it when working with vectors?
Thanks!
The simplest solution is to use a variant of for called for/fold.
I thought there were an for/min but alas.
#lang racket
(define v (vector 11 12 13 4 15 16))
(for/fold ([m +inf.0]) ([x (in-vector v)])
(min m x))
If you like a more explicit approach:
(define (vector-min xs)
(define n (vector-length xs))
(let loop ([i 0] ; running index
[m +inf.0]) ; minimum value so far
(cond
[(= i n) ; if the end is reached
m] ; return the minimum
[else ; else
(define x (vector-ref v i)) ; get new element in vector
(loop (+ i 1) ; increment index
(min m x))]))) ; new minimum
UPDATE
(let loop ([x 1] [y 10])
(loop (+ x 1) (- y 1))
is the same as:
(let ()
(define (loop (x y)
(loop (+ x 1) (- y 1)))
(loop 1 10))
Vectors are O(1) access and indexed so it is a completely different data structure, however you have SEFI-43 which is like the SRFI-1 List library, but for vectors.
#lang racket
(require srfi/43)
(define (min-element lst)
(vector-fold min (vector-ref lst 0) lst))
(max-element #(7 8 1 2 3 4 5 12))
; ==> 1
The racket/vector module has vector-argmin for finding the minimum element of a vector (Well, the minimum after feeding the elements through a transformation function). Combine that with a function like identity from racket/function and it's trivial:
(vector-argmin identity '#(5 4 3 2 1 6))

Scheme - Recursive addition/subtraction

So, I have three procedures.
(define (addition a)
(+ a 1))
(define (subtraction b)
(- b 1))
(define (recursion a b)
(define a 10)
(define b 0)
(if (a > 0)
(sub1 a)
(add1 b))
(if (b > 0)
(sub1 b)
(add1 a))
0)
The first one takes an integer and adds 1 to it. The second one takes an integer and subtracts 1 from it. The third one is supposed to use these two methods and a recursive way, so if I give (recursion 3 0) as input, it should subtract 1 from 3 until it's 0, and add 1 to 0 until it's 3. As you can see, this code isn't running...
I think the base case would be when a reaches 0 or in the other case b reaches 0. Right?
You first two functions have no issues. They're the classic inc and dec functions. Inc for increment and dec for decrement.
Your "recursion" function should not take a and b as arguments and then set their values with define. Generally, you should not set values with define inside a function in scheme (there are lets to do this, and, in this case, it's not necessary). So drop the (define a something) (define b something).
The main problem with the function "recursion" is that it's not recursive.
A recursive function calls itself. For instance, lets say I recreate your first two functions.
(define (inc a) (+ a 1))
(define (dec a) (+ a 1))
Then I create another function called recursion, but I'll just use one variable for this demo. Let's say that "recursion" will take the number "a".
If a = 5, we just return a . <=== base case
If a < 5, we increment a AND call ourself on the new a . <= recursive case
If a > 5, we decrement a AND call ourself on the new a . <= recursive case
(define (recursion a)
(if (= a 5)
a
(if (< a 5)
(recursion (inc a))
(recursion (dec a)))))
To be really fair, moving toward a central base case is generally not what you want to do. You should be thinking about 'consuming' your input. 0, the empty list, or nil, or good base cases. Anything can be a base case, but these values tend to guild your thinking toward a clear algorithm.
Does that help?

How to write a function that raises a number to 10th power using Racket?

This is what I have:
(define (10th-power 10 y)
(if (= y 0)
1
(* 10 ((10th-power 10 (- y 1)))))
for example if I input 2 it should give out 1024.
There are a lot of errors in this short procedure. Here are the errors reported by racket:
read: expected a ')' to close '(' since you are missing ending parentheis
define: not an identifier... in 10 as 10 cannot be a variable name it cannot be in the argument list.
application: not a procedure. Double parentheses in the recursion part makes the result from 10th-power tried as a procedure as the result instead of just using the value as is.
If you fix those your procedure will work, but it will do the 10^y instead of y^10. Perhaps you need a helper where you keep how many times you have multiplied y that counts down instead of y which is the one that should be in 10's place.
You were close:
#lang racket
(define (10th-power y)
(if (= y 0)
1
(* 10 (10th-power (- y 1)))))
(10th-power 3)
Things to note: You can't insert an extra parenthesis around an expression. Example: (100) means call 100 with no arguments - and since 100 is not a function, you get the error "application: not a procedure:.
Second thing to note: You do not need the 10 as an argument.
you can write a recursion like this:
#lang racket
(define (10th-power y)
(if (= y 0 )
1
(* 10 (10th-power (- y 1)))))
by the way, if you want to improve you space efficiency from o(n) to o(1),you can write iteration:
#lang racket
(define (10th-power y)
(define (iter back times)
(if (= times 0)
back
(iter (* 10 back) (- times 1))))
(iter 1 y))
(10th-power 3)

Pascal's Triangle Row Sequence

I'm currently working on finding the row sequences of Pascal's triangle. I wanted to input the row number and output the sequence of numbers in a list up until that row. For example, (Pascal 4) would give the result (1 1 1 1 2 1 1 3 3 1).
I am trying to use an algorithm that I found. Here is the algorithm itself:
Vc = Vc-1 * ((r - c)/c)
r and c are supposed to be row and column, and V0=1. The algorithm can be specifically found on the wikipedia page in the section titled "Calculating and Individual Row or Diagonal."
Here is the code that I have so far:
(define pascal n)
(cond((zero? n) '())
((positive? n) (* pascal (- n 1) (/ (- n c)c))))
I know that's hardly anything but I've been struggling a lot on trying to find scoping the function with a let or a lambda to incorporate column values. Additionally, I've also been struggling on the recursion. I don't really know how to establish the base case and how to get to the next step. Basically, I've been getting pretty lost everywhere. I know this isn't showing much, but any step in the right direction would be greatly appreciated.
Using as a guide the entry in Wikipedia, this is a straightforward implementation of the algorithm for calculating a value in the Pascal Triangle given its row and column, as described in the link:
#lang racket
(define (pascal row column)
(define (aux r c)
(if (zero? c)
1
(* (/ (- r c) c)
(aux r (sub1 c)))))
(aux (add1 row) column))
For example, the following will return the first four rows of values, noticing that both rows and columns start with zero:
(pascal 0 0)
(pascal 1 0)
(pascal 1 1)
(pascal 2 0)
(pascal 2 1)
(pascal 2 2)
(pascal 3 0)
(pascal 3 1)
(pascal 3 2)
(pascal 3 3)
Now we need a procedure to stick together all the values up until the desired row; this works for Racket:
(define (pascal-up-to-row n)
(for*/list ((i (in-range n))
(j (in-range (add1 i))))
(pascal i j)))
The result is as expected:
(pascal-up-to-row 4)
> '(1 1 1 1 2 1 1 3 3 1)
I discussed Pascal's Triangle at my blog.
In your question, the expression for Vc is just for one row. That translates to code like this:
(define (row r)
(let loop ((c 1) (row (list 1)))
(if (= r c)
row
(loop (+ c 1) (cons (* (car row) (- r c) (/ c)) row)))))
Then you just put together a bunch of rows to make the triangle:
(define (rows r)
(let loop ((r r) (rows (list)))
(if (zero? r)
rows
(loop (- r 1) (append (row r) rows)))))
And here's the output:
> (rows 4)
(1 1 1 1 2 1 1 3 3 1)
The base case is (= r c) in the first function and (zero? r) in the second.
If you want to write subscripts clearly, you can adopt the notation used by TeX: subscripts are introduced by an underscore and superscripts by a caret, with braces around anything bigger than one character. Thus Vc in your notation would be V_c, and Vc-1 in your notation would be V_{c-1}.

Resources