Skip to content

Add Jarvis March in PowerShell #761

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions contents/jarvis_march/code/powershell/JarvisMarch.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
function New-Point($x, $y) {
return New-Object -TypeName PSObject -Property @{X = [int]$x; Y = [int]$y}
}

function CounterClockWise($p1, $p2, $p3) {
return (($p3.Y - $p1.Y) * ($p2.X - $p1.X)) -ge (($p2.Y - $p1.Y) * ($p3.X - $p1.X))
}

function jarvis-march($gift) {
[System.Collections.ArrayList]$gift = $gift | Get-Unique -AsString
$pointOnHull = $gift | Sort-Object -Property X | Select-Object -First 1
[System.Collections.ArrayList]$hull = @($pointOnHull)

while ($true) {
$endpoint = $gift[0]

$gift | Select-Object -Skip 1 | ForEach-Object {
if (($endpoint -eq $pointOnHull) -or (-not (CounterClockWise $_ $hull[-1] $endpoint))) {
$endpoint = $_
}
}

$pointOnHull = $endpoint

if ($hull[0] -eq $endpoint) {
return $hull
} else {
$hull.Add($pointOnHull) | Out-Null
}
}
}

$testGift = @(
(New-Point -5 2)
(New-Point 5 7)
(New-Point -6 -12)
(New-Point -14 -14)
(New-Point 9 9)
(New-Point -1 -1)
(New-Point -10 11)
(New-Point -6 15)
(New-Point -6 -8)
(New-Point 15 -9)
(New-Point 7 -7)
(New-Point -2 -9)
(New-Point 6 -5)
(New-Point 0 14)
(New-Point 2 8)
)

$hull = Jarvis-March $testGift
Write-Host "The points in the hull are: $($hull | % {"($($_.X), $($_.Y)) "})"
2 changes: 2 additions & 0 deletions contents/jarvis_march/jarvis_march.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ Since this algorithm, there have been many other algorithms that have advanced t
[import, lang:"v"](code/v/jarvis.v)
{% sample lang="rust" %}
[import, lang:"rust"](code/rust/jarvis_march.rs)
{% sample lang="ps1" %}
[import, lang:"powershell"](code/powershell/JarvisMarch.ps1)
{% endmethod %}

<script>
Expand Down