mario::konrad
programming / C++ / sailing / nerd stuff
Algorithm: Area
© 2005 / Mario Konrad

Documentation

TODO:DESCRIPTION

C++

area.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
#include <algorithm>

typedef std::pair<double, double> Point;
typedef std::vector<Point> Polygon;

double area(const Polygon & polygon)
{
    if (polygon.size() < 3) return 0.0;
    double a = 0.0;
    std::for_each(polygon.begin(), polygon.end(), [&a](const Point & p)
    {
        a += p.first * p.second;
    });
    return a / polygon.size();
}

int main(int, char **)
{
    Polygon polygon =
    {
        Point(5,  5),
        Point(7,  5),
        Point(8, 10),
        Point(5, 12),
        Point(3,  7),
    };

    std::cout << "area of non-selfintersection polygon: "
        << area(polygon)
        << std::endl;

    return 0;
}

Scheme

area.scm:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(define (dot-prod v)
    (cond
        ((null? v) 0)
        ((not (list? v)) #f)
        (else
            (+ (* (car (car v)) (cadr (car v))) (dot-prod (cdr v))))))

(define (calc-area v)
    (cond
        ((null? v) 0)
        ((= (length v) 0) 0)
        (else (/ (dot-prod polygon) (length polygon)))))

(define polygon '((5  5) (7  5) (8 10) (5 12) (3  7)))

(display "area of ")
(display polygon)
(display " = ")
(display (calc-area polygon))
(newline)

(exit)