ascending-help me

Discussion of Common Lisp

ascending-help me

Postby murali » Fri Jul 01, 2011 12:15 pm

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
murali
 
Posts: 15
Joined: Fri Jul 01, 2011 10:11 am

Re: ascending-help me

Postby Indecipherable » Fri Jul 01, 2011 1:31 pm

Something like this?

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))))))))


Next time you may want to post some code though ;)
Don't take the FUN out of DEFUN !
User avatar
Indecipherable
 
Posts: 47
Joined: Fri Jun 03, 2011 5:30 am
Location: Behind you.

Re: ascending-help me

Postby murali » Fri Jul 01, 2011 1:48 pm

thank u
murali
 
Posts: 15
Joined: Fri Jul 01, 2011 10:11 am

Re: ascending-help me

Postby wvxvw » Fri Jul 08, 2011 2:03 am

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 ;)
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
wvxvw
 
Posts: 125
Joined: Sat Mar 26, 2011 6:23 am

Re: ascending-help me

Postby Paul » Fri Jul 08, 2011 6:29 am

Paul
 
Posts: 106
Joined: Tue Jun 02, 2009 6:00 am


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 1 guest