I am new to Scheme and I am using Dr.Racket to try to find the median of the list.
If the length of list L is odd, the function median returns the median element in the list. If the length of L is even, the function median returns 0. example
(median ‘(1)) returns 1
(median ‘(1 2)) returns 0
(median ‘(1 2 3)) returns 2
(median ‘( 1 2 3 4) returns 0
i am only allowed to use
- null?
- car
- cdr
- else
- =
- +
- median
- cond
- if
- user defined names (for my variables)
- integer literals
- parentheses
Any ideas?
This problem can be solved using the tortoise and hare algorithm, provided that a helper inner procedure is allowed - we need to pass two parameters for this to work. Other than that, all the restrictions are enforced:
(define (median lst)
(define (median tortoise hare)
(cond ((null? hare) 0)
((null? (cdr hare)) (car tortoise))
(else (median (cdr tortoise) (cdr (cdr hare))))))
(median lst lst))
It works as expected:
(median '(1)) ; returns 1
(median '(1 2)) ; returns 0
(median '(1 2 3)) ; returns 2
(median '(1 2 3 4)) ; returns 0
来源:https://stackoverflow.com/questions/27139794/a-function-median-in-scheme