Reputation: 21
I am new to Scheme and I am using Dr.Racket to try to find the median of the list.
For example, (median 2 1 3)
should return 2
and (median 1 1 5 5 2 3)
should return 2.5
.
I am using the R6RS scheme specification and am allowed to use get-line
.
Here is what I have so far:
#!r6rs
(import (rnrs))
(define (median-interactive lst)
(display "Enter input:")
(let ((input (get-line (current-input-port))))
(list-sort < lst)))
Can anyone help me?
Upvotes: 1
Views: 4345
Reputation: 5372
Here is a simplistic implementation. Since the median is just the point at which half the values are above and half are below, you can sort the list and find the middle point. Depending on whether the number of elements is odd or even you can either take the middle point in the sorted list (odd) or the average of the two middle points (even)
(define (median lst)
(let ((len (length lst))
(nlst (sort lst >)))
(if (even? len)
(/ (+ (list-ref nlst (/ len 2))
(list-ref nlst (- (/ len 2) 1))) 2)
(list-ref nlst (truncate (/ len 2))))))
If this is homework, such a nasty version might get you a 'D', but it does work.
> (median (list 5 2 6 2))
3 1/2
> (median (list 5 2 6 3 1))
3
>
Upvotes: 1
Reputation: 17223
Thing one: shouldn't 'median-interactive' call 'median'?
Thing two: I strongly urge you to develop 'median' totally independently of 'median-interactive'.
Thing three: can you provide examples of what median does? Specifically, concrete examples of how you might call 'median' and what it should return?
Thing four: I'm guessing this is homework?
Upvotes: 2