Ali Onur Cinar
Articles

CALCULATE CLOSEST AND
FURTHEST POINTS TO ZERO POINT

Reads one or more points (as x and y coordinates) from a data file and then calculates the closest and furthest points to zero point.


;
; Copyright (c) 2003
;      Ali Onur Cinar &060;cinar&064;zdo.com&062;
;
; License:
;
;   Permission  to  use,  copy, modify, and  distribute  this software and its
;   documentation   for  educational   purposes  and  without  fee  is  hereby
;   granted,  provided  that the  above  copyright notice appear in all copies
;   and  that both  the  copyright  notice  and  this  permission  notice  and
;   warranty  disclaimer appear in supporting documentation, and that the name
;   of Ali Onur Cinar not be  used  in  advertising or publicity pertaining to
;   distribution of the software without specific, written prior permission.
;

(defstruct point (x 0) (y 0))

(defun point-to-string (p)
  (format nil "~s,~s"
    (point-x p) (point-y p)))

(defun distance (p1 p2)
  (let ((dx (- (point-x p2) (point-x p1)))
        (dy (- (point-y p2) (point-x p1))))
    (sqrt (+ (* dx dx) (* dy dy)))))

(defun get-data (data)
  (with-open-file (in data :direction :input)
    (let ((i 0) (x nil) (y nil) (pts nil))
      (loop for n = (read in nil) until (null n) do
        (setf i (+ i 1))
        (cond ((= i 1) (setf x n))
              ((= i 2) (setf y n))
              ('t (setq pts (cons (make-point :x x :y y) pts))
                  (setf x n)
                  (setf y nil)
                  (setf i 1))))
      (if (not (null y))
         (setq pts (cons (make-point :x x :y y) pts)))
      pts)))

(let ((pts (get-data 'data))
      (zero (make-point :x 0 :y 0))
      (closest nil)
      (furthest nil))
  (loop for p in pts until (null p) do
    (cond ((or (null closest)
           (> (distance zero closest) (distance zero p)))
            (setf closest p))
          ((or (null furthest)
           (< (distance zero furthest) (distance zero p)))
            (setf furthest p))))
  (format t "Closest point to zero is ~s (~s) ~%"
    (point-to-string closest) (distance zero closest))
  (format t "Furthest point from zero is ~s (~s) ~%"
    (point-to-string furthest) (distance zero furthest)))

Simple data set for testing.


1 5
2 6
3 9
4 2
5 8
6 1
7 4
9 3
0 1

Your Comments


12/31/69 17:00

Name:
Comment:

Valid XHTML 1.0! Valid CSS! FuseBox Inside This is my Google PageRank. - SmE Rank free service Powered by Scriptme

This page was last updated on Sun January 21 2007 06:54:49 PM