Write a function ORDERED which returns true if the numbers in a list
are in ascending or descending order.
For example:
(ordered '(3 5 7 10))
returns: T
(ordered '(8 6 5 3))
returns:T
but:
(ordered '(5 4 6 7))
returns: nil
ascending-help me
-
- Posts: 47
- Joined: Fri Jun 03, 2011 5:30 am
- Location: Behind you.
- Contact:
Re: ascending-help me
Something like this?
Next time you may want to post some code though
Code: Select all
;;; Returns a string and 'T' if the list is in a desc. or asc. order, and NIL otherwise
(defun ordered (list)
(let ((list-dec (copy-list list)))
(let ((list-inc (copy-list list)))
(let ((alist (sort list-inc #'<)))
(let ((dlist (sort list-dec #'>)))
(cond
((equal list dlist)
(format nil "~%The numbers in ~a are in a descending order. ~%T" list))
((equal list alist)
(format nil "~%The numbers in ~a are in an ascending order. ~%T" list))))))))
Don't take the FUN out of DEFUN !
Re: ascending-help me
Hi, I think that for small lists there won't be significant difference, but for longer lists you would not like to create copies and sort them as that would both use up a lot of memory and processor resources.
I'd rather go with something like below, but notice, it does not consider sequences that have repeating elements as having ascending or descending order. Yet it is a simple `fix', I left it out on purpose, since, if you were doing this for a class, then you will have to put a little effort to make it work for all cases
I'd rather go with something like below, but notice, it does not consider sequences that have repeating elements as having ascending or descending order. Yet it is a simple `fix', I left it out on purpose, since, if you were doing this for a class, then you will have to put a little effort to make it work for all cases
Code: Select all
(defun asc-or-desc (x)
(if (> (length x) 1)
(funcall
(lambda (y pred)
(every (lambda (z)
(when (funcall pred y z)
(setf y z))) (cdr x)))
(first x)
(if (> (first x) (second x)) '> '<)) t))
(asc-or-desc '(1 2 3 4)) ; T
(asc-or-desc '(4 3 2 1)) ; T
(asc-or-desc '(4 3 1 2)) ; NIL