Convex hull: Difference between revisions

Added Easylang
(Added Easylang)
 
(10 intermediate revisions by 4 users not shown)
Line 13:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F orientation(p, q, r)
V val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
I val == 0
Line 71:
V hull = calculateConvexHull(points)
L(i) hull
print(i)</langsyntaxhighlight>
 
{{out}}
Line 85:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE POINTSIZE="4"
TYPE PointI=[INT x,y]
 
Line 186:
PrintE("Convex hull:")
PrintPoints(result,rLen)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Convex_hull.png Screenshot from Atari 8-bit computer]
Line 199:
=={{header|Ada}}==
{{trans|D}}
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Containers.Vectors;
 
Line 286:
Show (Find_Convex_Hull (Vec));
Ada.Text_IO.New_Line;
end Convex_Hull;</langsyntaxhighlight>
 
{{out}}
Line 296:
{{trans|Rust}}
 
<langsyntaxhighlight lang="rebol">define :point [x y][]
 
orientation: function [P Q R][
Line 363:
hull: calculateConvexHull points
loop hull 'i ->
print i</langsyntaxhighlight>
 
{{out}}
Line 382:
 
 
<langsyntaxhighlight lang="ats">//
// Convex hulls by Andrew's monotone chain algorithm.
//
Line 948:
}
 
(*------------------------------------------------------------------*)</langsyntaxhighlight>
 
{{out}}
Line 962:
=={{header|C}}==
{{trans|C++}}
<langsyntaxhighlight Clang="c">#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
Line 1,079:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 1,179:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
Line 1,185:
=={{header|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <ostream>
Line 1,272:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
Line 1,285:
 
 
<langsyntaxhighlight lang="lisp">#!/bin/sh
#|-*- mode:lisp -*-|#
#|
Line 1,455:
(terpri))
 
;;; vim: set ft=lisp lisp:</langsyntaxhighlight>
 
{{out}}
Line 1,463:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight Dlang="d">import std.algorithm.sorting;
import std.stdio;
 
Line 1,527:
auto hull = convexHull(points);
writeln("Convex Hull: ", hull);
}</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19), (-3,15)]</pre>
Line 1,538:
{{libheader| System.Generics.Defaults}}
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program ConvexHulls;
 
Line 1,648:
 
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
 
=={{header|EasyLang}}==
{{trans|Nim}}
<syntaxhighlight>
func orientation p[] q[] r[] .
return (q[2] - p[2]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[2] - q[2])
.
proc calcConvexHull . pts[][] res[][] .
res[][] = [ ]
indMinX = 1
for i to len pts[][]
if pts[i][1] < pts[indMinX][1]
indMinX = i
.
.
p = indMinX
repeat
res[][] &= pts[p][]
q = (p + 1) mod1 len pts[][]
for i to len pts[][]
if orientation pts[p][] pts[i][] pts[q][] < 0
q = i
.
.
p = q
until p = indMinX
.
.
#
pts[][] = [ [ 16 3 ] [ 12 17 ] [ 0 6 ] [ -4 -6 ] [ 16 6 ] [ 16 -7 ] [ 16 -3 ] [ 17 -4 ] [ 5 19 ] [ 19 -8 ] [ 3 16 ] [ 12 13 ] [ 3 -4 ] [ 17 5 ] [ -3 15 ] [ -3 -9 ] [ 0 11 ] [ -9 -3 ] [ -4 -2 ] [ 12 10 ] ]
calcConvexHull pts[][] res[][]
print res[][]
</syntaxhighlight>
{{out}}
<pre>
[
[ -9 -3 ]
[ -3 -9 ]
[ 19 -8 ]
[ 17 5 ]
[ 12 17 ]
[ 5 19 ]
[ -3 15 ]
]
</pre>
 
=={{header|F_Sharp|F#}}==
{{trans|C}}
<langsyntaxhighlight Flang="f#">open System
 
type Point =
Line 1,701 ⟶ 1,746:
affiche (convexHull (List.sortBy (fun (x : Point) -> x.X, x.Y) poly))
 
</syntaxhighlight>
</lang>
{{out}}
<pre>Convex Hull: [(-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19), (-3,15)]</pre>
Line 1,710 ⟶ 1,755:
 
 
<langsyntaxhighlight lang="fortran">module convex_hulls
!
! Convex hulls by Andrew's monotone chain algorithm.
Line 1,997 ⟶ 2,042:
write (*, fmt) (points(i), i = 1, n)
 
end program convex_hull_task</langsyntaxhighlight>
 
{{out}}
Line 2,005 ⟶ 2,050:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#include "crt.bi"
Screen 20
Line 2,097 ⟶ 2,142:
Next
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,111 ⟶ 2,156:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,173 ⟶ 2,218:
hull := pts.ConvexHull()
fmt.Println("Convex Hull:", hull)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,181 ⟶ 2,226:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class ConvexHull {
private static class Point implements Comparable<Point> {
private int x, y
Line 2,266 ⟶ 2,311:
println("Convex Hull: $hull")
}
}</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.List (sortBy, groupBy, maximumBy)
import Data.Ord (comparing)
 
Line 2,331 ⟶ 2,376:
, [-4, -2]
, [12, 10]
]</langsyntaxhighlight>
{{Out}}
<pre>[-3.0,-9.0]
Line 2,343 ⟶ 2,388:
=={{header|Haxe}}==
{{trans|Nim}}
<langsyntaxhighlight lang="haxe">typedef Point = {x:Float, y:Float};
 
class Main {
Line 2,435 ⟶ 2,480:
Sys.println(']');
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,444 ⟶ 2,489:
 
 
<langsyntaxhighlight lang="icon">#
# Convex hulls by Andrew's monotone chain algorithm.
#
Line 2,637 ⟶ 2,682:
end
 
######################################################################</langsyntaxhighlight>
 
{{out}}
Line 2,653 ⟶ 2,698:
Restated from the implementation at [https://web.archive.org/web/20150919194242/http://kukuruku.co/hub/funcprog/introduction-to-j-programming-language-2004] which in turn is Kukuruku Hub's [https://web.archive.org/web/20150908060956/http://kukuruku.co/] translation of Dr. K. L. Metlov's original Russian article [http://dr-klm.livejournal.com/42312.html].
 
<langsyntaxhighlight Jlang="j">counterclockwise =: ({. , }. /: 12 o. }. - {.) @ /:~
crossproduct =: 11 o. [: (* +)/ }. - {.
removeinner =: #~ (1 , (0 > 3 crossproduct\ ]) , 1:)
hull =: [: removeinner^:_ counterclockwise</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> hull 16j3 12j17 0j6 _4j_6 16j6 16j_7 16j_3 17j_4 5j19 19j_8 3j16 12j13 3j_4 17j5 _3j15 _3j_9 0j11 _9j_3 _4j_2 12j10
_9j_3 _3j_9 19j_8 17j5 12j17 5j19 _3j15
 
Line 2,693 ⟶ 2,738:
1 7
0 4
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight Javalang="java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Line 2,784 ⟶ 2,829:
System.out.printf("Convex Hull: %s\n", hull);
}
}</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
 
=={{header|Javascript}}==
<syntaxhighlight lang="javascript">
<lang Javascript>
function convexHull(points) {
points.sort(comparison);
Line 2,818 ⟶ 2,863:
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
}
</syntaxhighlight>
</lang>
 
'''For usage''':
<nowiki>convexhull.js</nowiki>
<syntaxhighlight lang="javascript">
<lang Javascript>
var points = [];
var hull = [];
Line 2,892 ⟶ 2,937:
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
}
</syntaxhighlight>
</lang>
 
<nowiki>convexhull.html</nowiki>
<langsyntaxhighlight lang="html">
<html>
 
Line 2,914 ⟶ 2,959:
 
</html>
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 2,920 ⟶ 2,965:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq"># ccw returns true if the three points make a counter-clockwise turn
def ccw(a; b; c):
a as [$ax, $ay]
Line 2,941 ⟶ 2,986:
| . + [$pt])
| .[:-1]
end ;</langsyntaxhighlight>
'''The task'''
<langsyntaxhighlight lang="jq">def pts: [
[16, 3], [12, 17], [ 0, 6], [-4, -6], [16, 6],
[16, -7], [16, -3], [17, -4], [ 5, 19], [19, -8],
Line 2,950 ⟶ 2,995:
];
 
"Convex Hull: \(pts|convexHull)"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,958 ⟶ 3,003:
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia"># v1.0.4
# https://github.com/JuliaPolyhedra/Polyhedra.jl/blob/master/examples/operations.ipynb
using Polyhedra, CDDLib
Line 2,966 ⟶ 3,011:
Pch = convexhull(P, P)
removevredundancy!(Pch)
println("$Pch")</langsyntaxhighlight>
{{out}}
<pre>convexhull([5.0, 19.0], [19.0, -8.0], [17.0, 5.0], [-3.0, 15.0], [-9.0, -3.0], [12.0, 17.0], [-3.0, -9.0])</pre>
Line 2,972 ⟶ 3,017:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
class Point(val x: Int, val y: Int) : Comparable<Point> {
Line 3,021 ⟶ 3,066:
val hull = convexHull(points)
println("Convex Hull: $hull")
}</langsyntaxhighlight>
 
{{out}}
Line 3,056 ⟶ 3,101:
=={{header|Lua}}==
{{trans|C++}}
<langsyntaxhighlight lang="lua">function print_point(p)
io.write("("..p.x..", "..p.y..")")
return nil
Line 3,125 ⟶ 3,170:
io.write("Convex Hull: ")
print_points(hull)
print()</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
Line 3,133 ⟶ 3,178:
Function are available in the geometry, ComputationalGeometry and simplex packages.
 
<langsyntaxhighlight lang="maple">pts:=[[16,3],[12,17],[0,6],[-4,-6],[16,6],[16,-7],[16,-3],[17,-4],[5,19],[19,-8],
[3,16],[12,13],[3,-4],[17,5],[-3,15],[-3,-9],[0,11],[-9,-3],[-4,-2],[12,10]]:
 
Line 3,145 ⟶ 3,190:
 
simplex:-convexhull(pts);
# [[-9, -3], [-3, -9], [19, -8], [17, 5], [12, 17], [5, 19], [-3, 15]]</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">hullPoints[data_] := MeshCoordinates[ConvexHullMesh[data]];
hullPoints[{{16, 3}, {12, 17}, {0, 6}, {-4, -6}, {16, 6}, {16, -7}, {16, -3}, {17, -4}, {5, 19}, {19, -8}, {3, 16}, {12, 13}, {3, -4}, {17, 5}, {-3, 15}, {-3, -9}, {0, 11}, {-9, -3}, {-4, -2}, {12, 10}}]</langsyntaxhighlight>
{{out}}{{12., 17.}, {5., 19.}, {19., -8.}, {17., 5.}, {-3., 15.}, {-3., -9.}, {-9., -3.}}
 
Line 3,157 ⟶ 3,202:
 
 
<langsyntaxhighlight lang="mercury">:- module convex_hull_task.
 
:- interface.
Line 3,191 ⟶ 3,236:
:- type point_list == list(point).
:- type point_array == version_array(point).
 
:- pred point_eq(point, point).
:- mode point_eq(in, in) is semidet.
point_eq(P, Q) :-
(fst(P) - fst(Q) = 0.0),
(snd(P) - snd(Q) = 0.0).
 
:- pred point_comes_before(point, point).
Line 3,312 ⟶ 3,351:
%%% mode: mercury
%%% prolog-indent-width: 2
%%% end:</langsyntaxhighlight>
 
{{out}}
Line 3,319 ⟶ 3,358:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE ConvexHull;
FROM FormatString IMPORT FormatString;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
Line 3,567 ⟶ 3,606:
DeleteNode(nodes);
ReadChar
END ConvexHull.</langsyntaxhighlight>
{{out}}
<pre>[(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
Line 3,573 ⟶ 3,612:
=={{header|Nim}}==
{{trans|Rust}}
<langsyntaxhighlight lang="nim">type
Point = object
x: float
Line 3,644 ⟶ 3,683:
let hull = calculateConvexHull(points)
for i in hull:
echo i</langsyntaxhighlight>
{{out}}
<pre>
Line 3,661 ⟶ 3,700:
 
 
<langsyntaxhighlight lang="objecticon"># -*- ObjectIcon -*-
#
# Convex hulls by Andrew's monotone chain algorithm.
Line 3,841 ⟶ 3,880:
 
every write ((!hull).to_string ())
end</langsyntaxhighlight>
 
{{out}}
Line 3,858 ⟶ 3,897:
 
 
<langsyntaxhighlight lang="ocaml">(*
* Convex hulls by Andrew's monotone chain algorithm.
*
Line 4,048 ⟶ 4,087:
;;
 
(*------------------------------------------------------------------*)</langsyntaxhighlight>
 
{{out}}
Line 4,057 ⟶ 4,096:
{{trans|Fortran}}
 
<langsyntaxhighlight lang="pascal">{$mode ISO}
 
program convex_hull_task (output);
Line 4,381 ⟶ 4,420:
{ local variables: }
{ mode: fundamental }
{ end: }</langsyntaxhighlight>
 
{{out}}
Line 4,401 ⟶ 4,440:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 4,472 ⟶ 4,511:
$list = join ' ', map { Point::print($_) } @hull_2;
say "Convex Hull (@{[scalar @hull_2]} points): [$list]";
</syntaxhighlight>
</lang>
{{out}}
<pre>Convex Hull (7 points): [(-3, -9) (19, -8) (17, 5) (12, 17) (5, 19) (-3, 15) (-9, -3)]
Line 4,481 ⟶ 4,520:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/convexhull.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo/rosetta/Convex_hull.exw
Line 4,583 ⟶ 4,622:
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,604 ⟶ 4,643:
{{libheader|Shapely}}
An approach that uses the shapely library:
<langsyntaxhighlight lang="python">from __future__ import print_function
from shapely.geometry import MultiPoint
 
if __name__=="__main__":
pts = MultiPoint([(16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2), (12,10)])
print (pts.convex_hull)</langsyntaxhighlight>
 
{{out}}
Line 4,617 ⟶ 4,656:
Also an implementation of https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain (therefore kinda {{trans|Go}}
 
<langsyntaxhighlight lang="racket">#lang typed/racket
(define-type Point (Pair Real Real))
(define-type Points (Listof Point))
Line 4,664 ⟶ 4,703:
'(5 . 19) '(19 . -8) '(3 . 16) '(12 . 13) '(3 . -4) '(17 . 5) '(-3 . 15) '(-3 . -9)
'(0 . 11) '(-9 . -3) '(-4 . -2) '(12 . 10)))
(list '(-9 . -3) '(-3 . -9) '(19 . -8) '(17 . 5) '(12 . 17) '(5 . 19) '(-3 . 15))))</langsyntaxhighlight>
 
{{out}}
Line 4,676 ⟶ 4,715:
Modified the angle sort method as the original could fail if there were multiple points on the same y coordinate as the starting point. Sorts on tangent rather than triangle area. Inexpensive since it still doesn't do any trigonometric math, just calculates the ratio of opposite over adjacent.
 
<syntaxhighlight lang="raku" perl6line>class Point {
has Real $.x is rw;
has Real $.y is rw;
Line 4,739 ⟶ 4,778:
);
 
say "Convex Hull ({+@hull} points): ", @hull;</langsyntaxhighlight>
{{out}}
<pre>Convex Hull (7 points): [(-3, -9) (19, -8) (17, 5) (12, 17) (5, 19) (-3, 15) (-9, -3)]
Line 4,751 ⟶ 4,790:
 
 
<langsyntaxhighlight lang="ratfor">#
# Convex hulls by Andrew's monotone chain algorithm.
#
Line 5,100 ⟶ 5,139:
write (fmt, '("(", I20, ''("(", F3.0, 1X, F3.0, ") ")'', ")")') n
write (*, fmt) (points(i), i = 0, n - 1)
end</langsyntaxhighlight>
 
{{out}}
Line 5,108 ⟶ 5,147:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Compute the Convex Hull for a set of points
* Format of the input file:
Line 5,572 ⟶ 5,611:
Trace ?R
Nop
Exit 12</langsyntaxhighlight>
{{out}}
<pre> 1 x= -9 yl=-3
Line 5,590 ⟶ 5,629:
===version 2===
After learning from https://www.youtube.com/watch?v=wRTGDig3jx8
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Compute the Convex Hull for a set of points
* Format of the input file:
Line 5,864 ⟶ 5,903:
*--------------------------------------------------------------------*/
If arg(2)=1 Then say arg(1)
Return lineout(g.0oid,arg(1))</langsyntaxhighlight>
{{out}}
<pre> 1 x= -9 yl=-3
Line 5,882 ⟶ 5,921:
=={{header|Ruby}}==
{{trans|D}}
<langsyntaxhighlight lang="ruby">class Point
include Comparable
attr :x, :y
Line 5,948 ⟶ 5,987:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
Line 5,954 ⟶ 5,993:
=={{header|Rust}}==
Calculates convex hull from list of points (f32, f32). This can be executed entirely in the Rust Playground.
<syntaxhighlight lang="rust">
<lang Rust>
#[derive(Debug, Clone)]
struct Point {
Line 6,021 ⟶ 6,060:
return Point {x:x as f32, y:y as f32};
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,035 ⟶ 6,074:
=={{header|Scala}}==
Scala Implementation to find Convex hull of given points collection. Functional Paradigm followed
<syntaxhighlight lang="scala">
<lang Scala>
object convex_hull{
def get_hull(points:List[(Double,Double)], hull:List[(Double,Double)]):List[(Double,Double)] = points match{
Line 6,070 ⟶ 6,109:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,092 ⟶ 6,131:
 
 
<langsyntaxhighlight lang="scheme">(define-library (convex-hulls)
 
(export vector-convex-hull)
Line 6,224 ⟶ 6,263:
 
(write (list-convex-hull example-points))
(newline)</langsyntaxhighlight>
 
{{out}}
Line 6,233 ⟶ 6,272:
<pre>$ csc -O3 -R r7rs convex-hull-task.scm && ./convex-hull-task
((-9 -3) (-3 -9) (19 -8) (17 5) (12 17) (5 19) (-3 15))</pre>
 
 
=== A second implementation ===
{{trans|Mercury}}
 
 
From the first Scheme implementation, above, I derived an implementation in [[#Standard_ML|Standard ML]]. From that I derived one in [[#Mercury|Mercury]]. Now, starting from that [[#Mercury|Mercury implementation]], I can come back and write a Scheme program more concise than the original.
 
One could pass these changes along to other languages as well.
 
If you are using CHICKEN Scheme you will need the '''srfi-1''' egg, in addition to those you needed for the first Scheme implementation.
 
 
<syntaxhighlight lang="scheme">(define-library (convex-hulls)
 
(export convex-hull)
 
(import (scheme base))
(import (only (srfi 1) fold))
(import (only (srfi 1) append!))
(import (only (srfi 132) list-sort))
(import (only (srfi 132) list-delete-neighbor-dups))
 
(begin
 
;;
;; Andrew's monotone chain algorithm for the convex hull in a
;; plane.
;;
;; For a description of the algorithm, see
;; https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=4016938
;;
 
(define x@ car)
(define y@ cadr)
 
(define (cross u v)
;; Cross product (as a signed scalar).
(- (* (x@ u) (y@ v)) (* (y@ u) (x@ v))))
 
(define (point- u v)
(list (- (x@ u) (x@ v)) (- (y@ u) (y@ v))))
 
(define (point=? u v)
(and (= (x@ u) (x@ v)) (= (y@ u) (y@ v))))
 
(define (point<? u v)
(let ((xu (x@ u))
(xv (x@ v)))
(or (< xu xv) (and (= xu xv) (< (y@ u) (y@ v))))))
 
(define (convex-hull points-list)
(let* ((points (list-delete-neighbor-dups
point=? (list-sort point<? points-list)))
(n (length points)))
(cond
((<= n 2) points)
(else
(let ((half-hull (make-vector n)))
(define (cross-test pt j)
(or (zero? j)
(let ((elem-j (vector-ref half-hull j))
(elem-j1 (vector-ref half-hull (- j 1))))
(positive? (cross (point- elem-j elem-j1)
(point- pt elem-j1))))))
(define (construct-half-hull points)
(vector-set! half-hull 0 (car points))
(vector-set! half-hull 1 (cadr points))
(fold (lambda (pt j)
(let loop ((j j))
(if (cross-test pt j)
(let ((j1 (+ j 1)))
(vector-set! half-hull j1 pt)
j1)
(loop (- j 1)))))
1 (cddr points)))
(let* ((lower-hull
;; Leave out the last point, which is the same
;; as the first point of the upper hull.
(let ((j (construct-half-hull points)))
(vector->list half-hull 0 j)))
(upper-hull
;; Leave out the last point, which is the same
;; as the first point of the lower hull.
(let ((j (construct-half-hull (reverse points))))
(vector->list half-hull 0 j))))
(append! lower-hull upper-hull)))))))
 
)) ;; end of library convex-hulls.
 
;;
;; A demonstration.
;;
 
(import (scheme base))
(import (scheme write))
(import (convex-hulls))
 
(define example-points
'((16 3) (12 17) (0 6) (-4 -6) (16 6)
(16 -7) (16 -3) (17 -4) (5 19) (19 -8)
(3 16) (12 13) (3 -4) (17 5) (-3 15)
(-3 -9) (0 11) (-9 -3) (-4 -2) (12 10)))
 
(write (convex-hull example-points))
(newline)</syntaxhighlight>
 
{{out}}
<pre>$ gosh convex-hull-task-2.scm
((-9 -3) (-3 -9) (19 -8) (17 5) (12 17) (5 19) (-3 15))</pre>
 
 
Footnote: My Mercury implementation originally had a "fold" in it, the way this Scheme program does, but that got lost during debugging. (The bug turned out to be elsewhere.) The fold and inner loop became one loop that I think is easier to understand. However, here I wanted to show it could be done with a fold.
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">class Point(Number x, Number y) {
method to_s {
"(#{x}, #{y})"
Line 6,309 ⟶ 6,461:
[-3,15], [-3,-9], [ 0,11], [-9,-3], [-4,-2], [12,10], [14,-9], [1,-9])
 
say("Convex Hull (#{hull.len} points): ", hull.join(" "))</langsyntaxhighlight>
{{out}}
<pre>
Line 6,323 ⟶ 6,475:
 
 
<langsyntaxhighlight lang="sml">(*
* Convex hulls by Andrew's monotone chain algorithm.
*
Line 6,614 ⟶ 6,766:
(* sml-indent-level: 2 *)
(* sml-indent-args: 2 *)
(* end: *)</langsyntaxhighlight>
 
{{out}}
Line 6,630 ⟶ 6,782:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">public struct Point: Equatable, Hashable {
public var x: Double
public var y: Double
Line 6,706 ⟶ 6,858:
 
print("Input: \(points)")
print("Output: \(calculateConvexHull(fromPoints: points))")</langsyntaxhighlight>
 
{{out}}
Line 6,717 ⟶ 6,869:
Translation of: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain#Python
 
<langsyntaxhighlight lang="tcl">catch {namespace delete test_convex_hull} ;# Start with a clean namespace
 
namespace eval test_convex_hull {
Line 6,769 ⟶ 6,921:
puts [convex_hull $tpoints]
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Test points:
Line 6,778 ⟶ 6,930:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports ConvexHull
 
Module Module1
Line 6,869 ⟶ 7,021:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]</pre>
Line 6,877 ⟶ 7,029:
{{libheader|Wren-sort}}
{{libheader|Wren-trait}}
{{libheader|Wren-iterate}}
<lang ecmascript>import "/sort" for Sort
<syntaxhighlight lang="wren">import "./traitsort" for Comparable, SteppedSort
import "./trait" for Comparable
import "./iterate" for Stepped
 
class Point is Comparable {
Line 6,926 ⟶ 7,080:
Point.new(-3, -9), Point.new( 0, 11), Point.new(-9, -3), Point.new(-4, -2), Point.new(12, 10)
]
System.print("Convex Hull: %(convexHull.call(pts))")</langsyntaxhighlight>
 
{{out}}
Line 6,932 ⟶ 7,086:
Convex Hull: [(-9, -3), (-3, -9), (19, -8), (17, 5), (12, 17), (5, 19), (-3, 15)]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">func real CosAng(A, B); \Return cosine of angle between vectors A and B
int A, B; \Cos(Ang) = DotProd / (|A|*|B|)
real DotProd, Magnitude;
[DotProd:= float( A(0)*B(0) + A(1)*B(1));
Magnitude:= sqrt(float( sq(B(0)-A(0)) + sq(B(1)-A(1)) ));
return DotProd / Magnitude;
];
 
proc ConvexHull(N, P);
int N, P;
int Min, I, HullI, EndI, A(2), B(2), J, SJ;
real Ang, MinAng;
[Min:= -1>>1; \find index of point with smallest X coordinate
for I:= 0 to N-1 do
if P(I,0) < Min then
[Min:= P(I,0); HullI:= I];
EndI:= HullI;
 
A(0):= 0; A(1):= -1;
repeat ChOut(0, ^();
IntOut(0, P(HullI,0)); ChOut(0, ^,); IntOut(0, P(HullI,1));
ChOut(0, ^));
MinAng:= -1e12; \find index of point with smallest diverting angle
for J:= 0 to N-1 do
[B(0):= P(J,0) - P(HullI,0); B(1):= P(J,1) - P(HullI,1);
Ang:= CosAng(A, B);
if Ang > MinAng and J # HullI then
[MinAng:= Ang; SJ:= J];
];
A(0):= P(SJ,0) - P(HullI,0); A(1):= P(SJ,1) - P(HullI,1);
HullI:= SJ;
if HullI # EndI then Text(0, ", ");
until HullI = EndI;
];
 
ConvexHull(20, [[16,3], [12,17], [0,6], [-4,-6], [16,6], [16,-7], [16,-3],
[17,-4], [5,19], [19,-8], [3,16], [12,13], [3,-4], [17,5],
[-3,15], [-3,-9], [0,11], [-9,-3], [-4,-2], [12,10]])
</syntaxhighlight>
{{out}}
<pre>
(-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19), (-3,15)</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">// Use Graham Scan to sort points into a convex hull
// https://en.wikipedia.org/wiki/Graham_scan, O(n log n)
// http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
Line 6,965 ⟶ 7,163:
fcn ccw(a,b,c){ // a,b,c are points: (x,y)
((b[0] - a[0])*(c[1] - a[1])) - ((b[1] - a[1])*(c[0] - a[0]))
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">pts:=List( T(16,3), T(12,17), T(0,6), T(-4,-6), T(16,6),
T(16, -7), T(16,-3),T(17,-4), T(5,19), T(19,-8),
T(3,16), T(12,13), T(3,-4), T(17,5), T(-3,15),
Line 6,972 ⟶ 7,170:
.apply(fcn(xy){ xy.apply("toFloat") }).copy();
hull:=grahamScan(pts);
println("Convex Hull (%d points): %s".fmt(hull.len(),hull.toString(*)));</langsyntaxhighlight>
{{out}}
<pre>
1,995

edits