Scheme transposing matrix - scheme

I have such code in Scheme:
(define transpose2 ;1
(lambda (A T) ;2
(if (pair? (car A)) ;3
(transpose2 ;4
(map cdr A) (cons (map car A) T) ;5
) ;6
(reverse T) ;7
) ;8
) ;9
) ;10
I have trouble understanding line nr 5. How creating a pair in this line eventually leads to transposing given matrix?
(define transpose ;1
(lambda (A) ;2
(transpose2 A `()) ;3
) ;4
) ;5
previous function transpose2 is executed by this function and for example:
(display (transpose '((1 2) (3 4) (5 6))))
(display (transpose '((3 2 1) (2 1 1) (3 1 1))))
gives results:
((1 3 5) (2 4 6))
((3 2 3) (2 1 1) (1 1 1))

There are two parameters here: A, your original matrix, and T, your accumulator.
On line 3, we check if the first element of A is a list, e.g. in the form '(1). If so, then we recurse, reducing A by one column with (map cdr A) and accumulating the first member of each A into T. When we finally exhaust our list, we reverse our accumulator and return it.
The code could perhaps be made slightly clearer if the condition on line 3 was replaced with (not (empty? A)).
Example trace:
(transpose '((1 2) (3 4) (5 6)))
-> (transpose2 '((1 2) (3 4) (5 6)) '())
-> (transpose2 (map cdr A) (cons (map car A) T))
-> (transpose2 '((2) (4) (6)) '((1 3 5)))
-> (transpose2 '(() () ()) '((2 4 6) (1 3 5)))
-> (reverse '((2 4 6) (1 3 5)))
-> '((1 3 5) (2 4 6))

Related

How can I use dynamic programming in Scheme to solve the Coin Change problem?

I'm trying to learn a Lisp language and have settled on Guile and am trying to solve this problem:
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Fundamentally, I understand the basic of dynamic programming where you can use recursion and memoization in order to save calculating at lower depths, but as Lisp I would expect it to be perfect for this type of problem. The problem I am having is returning separate lists for each combination of coins.
For an example case, consider target of 6 with coins [2, 3]. The simple tree would look like this:
The correct answer would be (3 3) with the other "complete" solution being (2 2 2).
However, if I try and construct these, the form I would want to use (without memoization) would look something like this.
(define get-coins (lambda (coins target)
(cond
((= target 0) '())
; not quite sure how to "terminate" a list here
; An idea is to return (list -1) and then filter
; lists that contain -1
((< target 0) ?????)
(else
; for each coin, recurse
(map (lambda (v)
(cons v (get-coins coins (- target v))))))
)
))
However, this doesn't return more lists as it goes through. Rather, it creates nested lists. And this is my problem. Any help with this would be greatly appreciated.
I wanted to avoid nested lists, so I used a variable results:
(define (get-coins coins target)
(let ((results '()))
Then I defined the function get-coins-helper, similar to your get-coins. And whenever I found some possible result, I used set! to update results:
(letrec ((get-coins-helper
(lambda (coins target result)
(cond ((= target 0) (set! results (cons result results)))
((< target 0) '())
(else (map (lambda (value)
(get-coins-helper coins
(- target value)
(cons value result)))
coins))))))
Then I called (get-coins-helper coins target '()) to find all possible results and at the end, I checked the value of results and returned -1 (if results are empty) or the shortest element of results:
(if (null? results)
-1
(car (sort results (lambda (x y) (< (length x)
(length y))))))
Full code:
(define (get-coins coins target)
(let ((results '()))
(letrec ((get-coins-helper
(lambda (coins target result)
(cond ((= target 0) (set! results (cons result results)))
((< target 0) '())
(else (map (lambda (value)
(get-coins-helper coins
(- target value)
(cons value result)))
coins))))))
(get-coins-helper coins target '())
(if (null? results)
-1
(car (sort results (lambda (x y) (< (length x)
(length y)))))))))
Some tests:
> (get-coins '(2 3) 6)
'(3 3)
> (get-coins '(2 3) 1)
-1
Using fold to choose best solutions. The result is a list whose car is the number of coins and cdr is the list of chosen coins. In the event that no solutions are feasible, (+inf.0) is returned.
(use-modules (srfi srfi-1))
(define (get-coins coins target)
(fold (lambda (coin best)
(let [(target (- target coin))]
(cond [(zero? target)
(list 1 coin)]
[(positive? target)
(let* [(res (get-coins coins target))
(score' (1+ (car res)))]
(if (< score' (car best))
(cons score' (cons coin (cdr res)))
best))]
[(negative? target)
best])))
(list +inf.0)
coins))
(get-coins (list 2) 6)
$8 = (3 2 2 2)
(get-coins (list 2 3) 6)
$9 = (2 3 3)
(get-coins (list 9) 6)
$10 = (+inf.0)
If you read the question carefully, all you need to keep track of is the number of coins needed to reach the target amount. You don't have generate every possible combination of coins to reach the target, just the one that minimizes the number of coins. And you don't even have to remember what that particular combination is, just its length. This simplifies things a bit since there's no need to build any lists.
For each denomination of coin that can possibly be used to reach the goal (So no coins bigger than the difference between the goal and the current sum), get the counts for using one of them and for using none of them, and return the minimum (Or -1 if no options present themselves).
(define (get-coins coins target)
(calculate-coins coins 0 0 target))
;; Do all the work in a helper function
(define (calculate-coins coins coin-count amount target)
(cond
((= amount target) coin-count) ; Success
((null? coins) -1) ; Failure
((> (car coins) (- target amount)) ; Current coin denomination is too big; skip it
(calculate-coins (cdr coins) coin-count amount target))
(else
;; Cases to consider:
;; Adding one of the current coin to the total and leaving open using more
;; Not using any of the current coins
(let ((with-first
(calculate-coins coins (+ coin-count 1) (+ amount (car coins)) target))
(without-first
(calculate-coins (cdr coins) coin-count amount target)))
(cond
((= with-first -1) without-first)
((= without-first -1) with-first)
(else (min with-first without-first)))))))
If you do want to get every possible combination of coin, one way is to, for each list of combinations that use a given coin, use append to combine it with a list of previous ways:
(use-modules (srfi srfi-1))
(define (get-coins2 coins target)
(define (helper target) ; This time define a nested helper function
(fold
(lambda (coin ways)
(cond
((= coin target) (cons (list coin) ways))
((< coin target)
(append
(map (lambda (c) (cons coin c))
(helper (- target coin)))
ways))
(else ways)))
'()
coins))
(let* ((ways (helper target))
(table (make-hash-table (length ways))))
;; Store each combination as a key in a hash table to remove duplicates
(for-each (lambda (way) (hash-set! table (sort-list way <) #t)) ways)
(hash-map->list (lambda (k v) k) table)))
Examples:
scheme#(guile-user)> (load "coins.scm")
scheme#(guile-user)> (get-coins '(2) 6)
$1 = 3
scheme#(guile-user)> (get-coins2 '(2) 6)
$2 = ((2 2 2))
scheme#(guile-user)> (get-coins '(2 3) 6)
$3 = 2
scheme#(guile-user)> (get-coins2 '(2 3) 6)
$4 = ((2 2 2) (3 3))
scheme#(guile-user)> (get-coins '(9) 6)
$5 = -1
scheme#(guile-user)> (get-coins2 '(9) 6)
$6 = ()
scheme#(guile-user)> (get-coins2 '(2 3) 12)
$7 = ((3 3 3 3) (2 2 2 3 3) (2 2 2 2 2 2))
scheme#(guile-user)> (get-coins '(5 2 3 4) 21)
$8 = 5
scheme#(guile-user)> (get-coins2 '(5 2 3 4) 21)
$9 = ((2 2 2 5 5 5) (2 3 3 4 4 5) (2 4 5 5 5) (3 3 3 4 4 4) (2 2 3 4 5 5) (4 4 4 4 5) (2 2 4 4 4 5) (2 2 3 3 3 4 4) (2 2 2 2 2 3 4 4) (2 2 2 2 4 4 5) (3 3 3 3 4 5) (2 2 2 2 3 3 3 4) (2 2 2 2 2 2 2 3 4) (2 2 2 2 2 2 4 5) (3 3 3 3 3 3 3) (2 2 3 3 3 3 5) (2 2 2 2 2 2 3 3 3) (2 2 2 2 2 3 3 5) (3 3 5 5 5) (2 2 2 2 2 2 2 2 2 3) (2 2 2 2 3 5 5) (2 2 2 2 2 2 2 2 5) (2 3 4 4 4 4) (2 2 2 3 4 4 4) (2 3 3 3 3 3 4) (2 2 2 3 3 4 5) (2 2 2 3 3 3 3 3) (2 3 3 3 5 5) (3 4 4 5 5))
scheme#(guile-user)> (filter (lambda (way) (= (length way) 5)) (get-coins2 '(5 2 3 4) 21))
$10 = ((2 4 5 5 5) (4 4 4 4 5) (3 3 5 5 5) (3 4 4 5 5))
There are many ways to do it, here is a brute-force solution. It is not elegant but it is simple.
(define mk/pairs
(lambda (sum coin/list)
((lambda (s) (s s
(map (lambda (x) (iota (+ 1 (quotient sum x)))) coin/list)
(lambda (s) s) ))
(lambda (s l* ret)
(if (null? l*)
(ret '(()))
(s s (cdr l*)
(lambda (r)
(ret (apply
append
(map (lambda (x) (map (lambda (y) (cons y x)) (car l*)))
r))))))))))
(define cost
(lambda (s pair coin/list)
(let ((sum (apply + (map * pair coin/list))))
(and (= s sum) pair))))
(define solve
(lambda (sum coin/list)
(let ((pairs (mk/pairs sum coin/list)))
(let ((solutions
(sort (filter (lambda (x) x)
(map (lambda (p) (cost sum p coin/list)) pairs))
(lambda (p1 p2)
(< (apply + p1)
(apply + p2))))))
(if (null? solutions)
"fail"
(car solutions))))))
A test looks like so:
% mit-scheme < coins.scm
MIT/GNU Scheme running under GNU/Linux
1 ]=> (solve 8 '(2 3 1))
;Value: (1 2 0)
1 ]=> (solve 6 '(2 3))
;Value: (0 2)
meaning that you have 1 coin of 2 and 2 coins of 3 in the first example and 2 coins of 3 in the second example.
I have used standard R6RS, so you should be able to convert it directly from mit/scheme to guile.

How would I write a Scheme procedure that takes in a tree (represented as a list) and return that list with its elements reversed essentially?

I am having trouble writing a Scheme procedure that takes a tree (represented as a list) and returns a list whose elements are all the leaves of the tree arranged in right to left order.
For example, if I were to call: ( leaves '(((1 2) (3 4)) ((1 2) (3 4))) ) I would get: '(4 3 2 1 4 3 2 1)
I have the following so far, and the output is technically correct, but there is an issue with the parenthesis:
(define (leaves givenList)
(if (null? givenList) givenList
(if (list? (car givenList))
(append (leaves (cdr givenList)) (cons (leaves (car givenList)) '()))
(append (leaves (cdr givenList)) (list (car givenList))))))
The output when I call: ( leaves '(((1 2) (3 4)) ((1 2) (3 4))) ) is: (((4 3) (2 1)) ((4 3) (2 1)))
I need to get rid of the parenthesis on the inside and just get: '(4 3 2 1 4 3 2 1)
Any help or insight is greatly appreciated. Thanks!

Is append the identity function for map?

In doing some tests I've noticed that append always gives me the same output as input when using map:
#lang sicp
(map append '(1 2 3 4 5))
(map (lambda (x) x) '(1 2 3 4 5))
; (1 2 3 4 5)
; (1 2 3 4 5)
(map append '((1 2)(3 4)))
(map (lambda (x) x) '((1 2)(3 4)))
; ((1 2) (3 4))
; ((1 2) (3 4))
That seems pretty neat/unexpected to me. Is this in fact the case? If so, how does the append work to give the identity property?
The append procedure takes zero or more list arguments, and a final argument that can be any object. When the final argument is a list, the result of appending is a proper list. When the final argument is not a list, but other list arguments have been provided, the result is an improper list. When only one argument is provided, it is just returned. This behavior with one argument is exactly the behavior of an identity procedure.
> (append '(1 2) '(3))
(1 2 3)
> (append '(1 2) 3)
(1 2 . 3)
> (append '(1 2))
(1 2)
> (append 3)
3
The call (map append '(1 2 3 4 5)) is equivalent to:
> (list (append 1)
(append 2)
(append 3)
(append 4)
(append 5))
(1 2 3 4 5)
Here, append is just acting as an identity procedure, as described above.

printing pairs from a list in scheme

I'm trying to print pairs from one list kinda like a subset in scheme but with two elements just like this
(1 2 3 4 5)
((1 2) (1 3) (1 4) (1 5) (2 3) (2 4) (2 5) (3 4) (3 5) (4 5))
the code I wrote doesn't work
(define (subset x)
(if ( null? x) x
(map cons x (subset (cdr x)))))
this just return an empty list
I prefer to write the lambdas explicitly, makes it easier to understand what arguments are passed:
(define subset
(lambda (lst)
(if (null? lst)
lst
(append (map (lambda (el) (cons (car lst) el)) (cdr lst))
(subset (cdr lst)))
)))
(subset '(1 2 3 4 5))
=> ((1 . 2) (1 . 3) (1 . 4) (1 . 5) (2 . 3) (2 . 4) (2 . 5) (3 . 4) (3 . 5) (4 . 5))
EDIT: The explanation about map below is only valid in some versions of scheme, read Sylwester's comment to this answer.
map traverses n lists supplied to it and applies proc to the n elements in the same position in the lists. This means it can apply proc no more times than the length of the shortest list, but you keep giving it an empty list (from the last recursive call backwards).
(BTW this is in plain scheme)
In #lang racket that is very easy since we have combinations:
(combinations '(1 2 3 4 5) 2)
; ==> ((1 2) (1 3) (2 3) (1 4) (2 4) (3 4) (1 5) (2 5) (3 5) (4 5))
Now this does not print anything. To get it print to the terminal you can use displayln:
(displayln (combinations '(1 2 3 4 5) 2))
; ==> #<void>, ((1 2) (1 3) (2 3) (1 4) (2 4) (3 4) (1 5) (2 5) (3 5) (4 5)) printed to terminal as side effect
If order of items is also important, following can be used:
(define (subsets l)
(let loop ((n 0) ; run a loop for each item
(ol '())) ; start with blank output list
(cond
[(= n (length l)) (reverse ol)] ; output ol when last item reached;
[else
(let* ((x (list-ref l n)) ; get one item
(jl (for/list ((i l) ; get remaining list
(j (in-naturals))
#:unless (= j n))
i))
(kl (for/list ((i jl)) ; make combinations with each of remaining list
(list x i))))
(loop (add1 n) (cons kl ol)))])))
Testing:
(subsets '(1 2 3 4 5))
Output:
'(((1 2) (1 3) (1 4) (1 5))
((2 1) (2 3) (2 4) (2 5))
((3 1) (3 2) (3 4) (3 5))
((4 1) (4 2) (4 3) (4 5))
((5 1) (5 2) (5 3) (5 4)))

Project for the game 'Oware'

I have a project about the game "Oware", we are supposed to write the game in the program Dr.Racket.
These are the rules for the game, they explain it pretty well, illustrating with pictures: http://www.awale.info/jugar-a-lawale/les-regles-de-lawale/?lang=en
Im kinda stuck on the first exercise, i have the method, but its not giving the numbers in the right order.
The first function we have to write is called "distribute" which should re-put x grains in the holes, giving the result in a form of a list consisting of the number of grains rest and the new numbers for the holes.
This is whats expected:
(distribute 5 '(2 3 1 5 5 2)) -> (0 (3 4 2 6 6 2))
(distribute 5 '(2 3 1)) -> (2 (3 4 2))
What I wrote:
(define distribue
(lambda (n l)
(if (or (= n 0) (null? l))
(list l n)
(cons (+ (car l) 1) (distribue (- n 1) (cdr l))))))
What it gives:
(distribue 5 '(2 3 1 5 5 2)) -> (3 4 2 6 6 (2) 0)
(distribue 5 '(2 3 1)) -> (3 4 2 () 2)
I was trying to change the list cons append, but never got the expected form of answer
How about
(define (distribue n l)
(define (iterator n p q)
(if (or (= n 0) (null? q))
(list n (append p q))
(iterator (- n 1) (append p (list (+ 1 (car q)))) (cdr q))))
(iterator n '() l))
where
(distribue 5 '(2 3 1 5 5 2))
(distribue 5 '(2 3 1))
returns
'(0 (3 4 2 6 6 2))
'(2 (3 4 2))
as required.

Resources