In Lisp, I have to create a program that does the following (please visit link):
http://uva.onlinejudge.org/external/103/10328.html
I have code to create the tree
(defun head-tail (n &optional (total 0))
(if (< total n)
(list(cons 'H (head-tail n (1+ total)))
(cons 'T (head-tail n (1+ total))))
nil))
and then code to check the sequence of H = heads
(defun head-search2 (tree n &optional (total 0) (check 0))
(cond ((null tree)
check)
((listp (first tree))
(+ (head-search2 (first tree) n total)
(head-search2 (rest tree) n total check)))
((and (eq (first tree) 'H)
(>= (1+ total) n))
(head-search2 (rest tree) n (1+ total) 1))
((and (eq (first tree) 'H)
(< (1+ total) n))
(head-search2 (rest tree) n (1+ total) check))
((eq (first tree) 'T)
(head-search2 (rest tree) n 0 check ))))
and a last function to combine those two
(defun head-check (m n)
(head-search2(head-tail m) n))
The code is not working with large numbers of trees, any help would be great!
There are two problems:
In the function
head-search2, second clause ofcond, first recursive call tohead-search2fails to propagate thecheckdown.Same clause, second recursive call gets
(rest tree)as first parameter, which results in an extra layer of list; it should be(second tree)instead.That said, you traverse the tree twice: first when constructing, and then counting it. With a little bit more careful thinking, you can save a lot of work traversing it just once, without constructing it explicitly:
Rewriting this further for dynamic programming is left as an exercise for the reader. 😉