read a polynomial from input stream in lisp - sorting

Reads a polynomial from a list pl (see below for input format) and returns it as a sorted list.
Example: (ReadPolynomial2 '(99 0 17 200 3 150 8 200 0 0)) should return ((99 0) (3 150) (25 200))

I don't know if you still need it, but here it is a possible solution:
(defun ReadPolynomial2 (lst)
(let ((even-positions (loop for p in (cdr lst) by #'cddr collect p)))
(loop for p in (remove-duplicates even-positions)
collect (list (loop for x on lst by #'cddr
when (= p (second x))
sum (first x)) p))))

Related

partition of number without using consecutive integers

I am following the cs61a spring 2015 class.
One of the problem in the scheme project is:
Implement the list-partitions procedure, which lists all of the ways to
partition a positive integer total without using consecutive integers. The
contents of each partition must be listed in decreasing order.
Hint: Define a helper procedure to construct partitions. The built-in append
procedure creates a list containing all the elements of two argument lists.
The cons-all procedure in questions.scm adds a first element to each list in a list of lists.
The number 5 has 4 partitions that do not contain consecutive integers:
5
4, 1
3, 1, 1
1, 1, 1, 1, 1
The following partitions of 5 are not included because of consecutive
integers:
3, 2
2, 2, 1
2, 1, 1, 1
I found one solution but cannot understand it
;; List all ways to partition TOTAL without using consecutive numbers.
(define (apply-to-all proc items)
(if (null? items)
'()
(cons (proc (car items))
(apply-to-all proc (cdr items)))))
(define (cons-all first rests)
(apply-to-all (lambda (rest) (cons first rest)) rests))
(define (caar x) (car (car x)))
(define (cadr x) (car (cdr x)))
(define (cddr x) (cdr (cdr x)))
(define (cadar x) (car (cdr (car x))))
(define (cdar x) (cdr (car x)))
(define (partitions-r a b)
(if (= a 0) nil
(append (cons-all a (list-partitions b))
(cons-f (partitions-r (- a 1) (+ b 1))
))
))
(define (cons-f lst)
(cond
((eq? lst nil) nil)
((eq? (cdar lst) nil) lst)
((< (caar lst) (cadar lst)) (cons-f (cdr lst)))
((= (caar lst) (+ 1 (cadar lst))) (cons-f (cdr lst)))
(else (cons (car lst) (cons-f (cdr lst))))
))
(define (list-partitions total)
(cond ((= total 1) '((1)) )
((= total 0) '(()) )
(else (append nil (partitions-r total 0)))
))
; For these two tests, any permutation of the right answer will be accepted.
(list-partitions 5)
; expect ((5) (4 1) (3 1 1) (1 1 1 1 1))
(list-partitions 7)
; expect ((7) (6 1) (5 2) (5 1 1) (4 1 1 1) (3 3 1) (3 1 1 1 1) (1 1 1 1 1 1 1))
What does the function partitions-r and cons-f do? Thank you very much!
Don't know Scheme, but recursive generation in pseudocode might look like:
function Partitions(N, LastValue, list):
if N = 0
print list
else
for i from Min(LastValue, N) downto 1
if (i != LastValue - 1) //reject consecutive number
Partitions(N - i, i, list + [i]);

Transform a natural number to a specific base and return it as a list

I want to show the result of my function as a list not as a number.
My result is:
(define lst (list ))
(define (num->base n b)
(if (zero? n)
(append lst (list 0))
(append lst (list (+ (* 10 (num->base (quotient n b) b)) (modulo n b))))))
The next error appears:
expected: number?
given: '(0)
argument position: 2nd
other arguments...:
10
I think you have to rethink this problem. Appending results to a global variable is definitely not the way to go, let's try a different approach via tail recursion:
(define (num->base n b)
(let loop ((n n) (acc '()))
(if (< n b)
(cons n acc)
(loop (quotient n b)
(cons (modulo n b) acc)))))
It works as expected:
(num->base 12345 10)
=> '(1 2 3 4 5)

Josephus in Scheme

Where does this implementation of the Josephus problem fall short? For those who are unfamiliar with the Josephus Problem, the goal is to delete every 3rd entry from a circularly linked list until only one remains. In this example I am deleting every "mth" value.
(define (joseph lst)
(let ((m (+ 1 (random (length lst)))))
(define (joseph-h i xlst mlst)
(cond ((<= (length xlst) 1) xlst)
((null? (cdr mlst))
(joseph-h i xlst xlst))
((= i m)
(joseph-h 1 (delete (car mlst) xlst) (cdr mlst)))
(else
(joseph-h (+ i 1) xlst (cdr mlst)))))
(joseph-h 0 lst lst)))
(joseph (list 1 2 3 4 5 6 7))
(define (delete v lst)
(cond ((= v (car lst))
(cdr lst))
(else
(cons (car lst) (delete v (cdr lst))))))
I always end up with the last number of the list as the answer. I know that this is not right.
You're taking the algorithm too literally, by creating a list and deleting elements ("killing" people) from it. A simpler solution would be to use arithmetic operations to model the problem, here's a possible implementation, adapted from my own previous answer:
(define (joseph n k)
(let loop ([i 1]
[acc 0])
(if (> i n)
(add1 acc)
(loop (add1 i)
(modulo (+ acc k) i)))))
For example, to see which position survives in the list '(1 2 3 4 5 6 7) after killing every third person, do this:
(joseph 7 3)
=> 4
Wikipedia provides an interesting discussion regarding the possible solutions for this problem, my solution adapts the simple python function shown, after converting it to tail recursion.
I give three solutions at my blog. The most literal version deletes from a list of n items in steps of m, representing the list as a cyclic list:
(define (cycle xs)
(set-cdr! (last-pair xs) xs) xs)
(define (josephus3 n m)
(let loop ((k (- m 1)) (alive (cycle (range 0 n))) (dead '()))
(cond ((= (car alive) (cadr alive))
(reverse (cons (car alive) dead)))
((= k 1)
(let ((dead (cons (cadr alive) dead)))
(set-cdr! alive (cddr alive))
(loop (- m 1) (cdr alive) dead)))
This does the deletions by actually removing the killed elements from the alive list and placing them on the dead list. The range function is from my Standard Prelude; it returns the integers from 0 to n-1:
(define (range first past . step)
(let* ((xs '()) (f first) (p past)
(s (cond ((pair? step) (car step))
((< f p) 1) (else -1)))
(le? (if (< 0 s) <= >=)))
(do ((x f (+ x s))) ((le? p x) (reverse xs))
(set! xs (cons x xs)))))
The original Josephus problem killed 41 men in steps of 3, leaving the 31st man as the survivor, counting from 1:
(josephus3 41 3)
(2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36
40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 30)
You might also enjoy the other two versions at my blog.

find the max of Collatz sequence from a giving list

i'm new in scheme syntax.
this is the last part of the project i've been working on.
i was able to find the max from a giving Collatz sequence, but this part of the project requires finding the max length from a multiple Collatz sequences lists.
So for example giving this list : '((1 10) (10 200) (201 210) (900 1000) and the output should be like this : ‘(20 125 89 174)
i need to find the maximum length between the number 1 to 10 and then from 10 to 200 ets
here is my code :
#lang racket
; Part I
(define (sequence n)
(cond [(= n 1)
(list n)]
[(even? n)
( cons n(sequence( / n 2)))]
[(odd? n)
( cons n(sequence (+(* n 3) 1))) ] ))
(sequence 10)
; Part II
(define (find-length items)
(if (null? items)
(list )
(cons
(length (sequence(car items)))
(find-length (rest items))))
)
(find-length (list 10 16 22 90 123 169))
;Part III
(define max-in-list (lambda (ls)
(let ( (head (car ls)) (tail (cdr ls)))
(if (null? tail)
; list contains only one item, return it
head
; else find largest item in tail
(let ((max-in-tail (max-in-list tail)))
; return the larger of 'head' and 'max-in-tail'
(if (> head max-in-tail)
head
max-in-tail
)
)
)
)
))
(define (find-max i j)
( if (= i j)
(list)
(cons
(max-in-list (find-length(sequence i)))
(find-max (+ 1 i ) j)
))
)
(max-in-list(find-max 1 10))
(define (max-length-list items )
(if (null? items)
(list)
(cons
(find-max ? ?) ) ; how i can call this function ?
(max-length-list (?) ) ; how i can call this function ?
)))
(max-length-list '((1 10) (10 200) (201 210) (900 1000) ))
Each item in the list you pass to max-length-list is a list with two numbers and a nil, e.g. (cons 1 (cons 2 '())).
The first number is (car (car items)).
The second is (car (cdr (car items))).
Or, if you let ((head (car items)), then they are (car head) and (car (cdr head)).
The recursive call is trivial; you've processed the first element with find-max, now you just need to process the rest of them. You obviously already know how to accomplish that, since you've done it.

Combining a list of spaced numbers in Scheme

I have a function that takes a number such as 36, and reverses it to say '(6 3)
Is there anyway to combine that 6 3 to make it one number?
Here is the code that I have written.
(define (number->rdigits num)
(if (rdigits (/ (- num (mod num 10)) 10)))))
(define reversible?
(lambda (n)
(cond
[(null? n) #f]
[else (odd? (+ n (list (number->rdigits n))))])))
Thanks!
You can do this using an iterative function that takes each element of the list in turn, accumulating a result. For example:
(define (make-number lst)
(define (make a lst)
(if (null? lst)
a
(make (+ (* 10 a) (car lst)) (cdr lst))))
(make 0 lst))
(display (make-number '(6 3)))
The make function uses an accumulator a and the rest of the digits in lst to build up the final result one step at a time:
a = 0
a = 0*10 + 6 = 6
a = 6*10 + 3 = 63
If you had more digits in your list, this would continue:
a = 63*10 + 5 = 635
a = 635*10 + 9 = 6359
A less efficient implementation that uses a single function could be as follows:
(define (make-number lst)
(if (null? lst)
0
(+ (* (expt 10 (length (cdr lst))) (car lst)) (make-number (cdr lst)))))
This function needs to calculate the length of the remainder of the list for each iteration, as well as calling the expt function repeatedly. Also, this implementation is not properly tail recursive so it builds up multiple stack frames during execution before unwinding them all after it reaches its maximum recursion depth.

Resources