How to resolve the algorithm Shoelace formula for polygonal area step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Shoelace formula for polygonal area step by step in the D programming language

Table of Contents

Problem Statement

Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: (Where abs returns the absolute value) Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:

Show the answer here, on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Shoelace formula for polygonal area step by step in the D programming language

Source code in the d programming language

import std.stdio;

Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}];

void main() {
    auto ans = shoelace(pnts);
    writeln(ans);
}

struct Point {
    real x, y;
}

real shoelace(Point[] pnts) {
    real leftSum = 0, rightSum = 0;

    for (int i=0; i<pnts.length; ++i) {
        int j = (i+1) % pnts.length;
        leftSum  += pnts[i].x * pnts[j].y;
        rightSum += pnts[j].x * pnts[i].y;
    }

    import std.math : abs;
    return 0.5 * abs(leftSum - rightSum);
}

unittest {
    auto ans = shoelace(pnts);
    assert(ans == 30);
}


  

You may also check:How to resolve the algorithm Guess the number/With feedback step by step in the PHP programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the Nim programming language
You may also check:How to resolve the algorithm Function prototype step by step in the Go programming language
You may also check:How to resolve the algorithm Angle difference between two bearings step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Sum of squares step by step in the Pop11 programming language