Skip to content

Rust implementation of the jarvis march algorithm #723

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

Merged
merged 3 commits into from
Jul 11, 2020
Merged
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
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,4 @@ This file lists everyone, who contributed to this repo and wanted to show up her
- Jonathan D B Van Schenck
- James Goytia
- Amaras
- Jonathan Dönszelmann
64 changes: 64 additions & 0 deletions contents/jarvis_march/code/rust/jarvis_march.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

type Point = (i64, i64);

// Is the turn counter clockwise?
fn turn_counter_clockwise(p1: Point, p2: Point, p3: Point) -> bool {
(p3.1 - p1.1) * (p2.0 - p1.0) >= (p2.1 - p1.1) * (p3.0 - p1.0)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@berquist I saw that in another implementation of Jarvis (I believe maybe Julia?) someone wanted this function to return an integer because the text says so. Should I do this in rust too?

Copy link
Contributor Author

@jdonszelmann jdonszelmann Jul 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember, it was in the Graham scan in rust (#479 )

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or maybe an enum?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Jarvis March, these implementations have a function that returns a float:

  • C
  • Haskell
  • Java

and these implementations have a function that returns a boolean:

  • C#
  • C++ (inline lambda)
  • Common Lisp
  • Go
  • JavaScript
  • Python
  • Vlang

and these implementations do something else:

  • Julia

As for which should be used, being consistent is best. I made that comment about returning a number in Graham Scan because of what the text describes, but here there is no such description in the text, despite this part of the algorithm being the same.

Regarding the enum, what advantage would that bring? This is really about getting an ordering between points, which you represent either as

  1. < 0, == 0, or > 0 for two points, or
  2. true/false for some condition, say p1 <= p2.

My response is that either a bool or a float is fine, and if we decide to standardize later on one or the other, it's an easy change.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding floats, some algorithms (including this one, but also c# and V) can't even deal with floating point input coordinates. Any thoughts about that?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And for the enum, in rust it's not uncommon to use an Ordering as a return type here (https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally the allowed input is any number type (maybe not complex), but if it's restricted to just ints or floats, it's fine as long as the code is correct. If you want to make Point generic over Signed + Float, that's up to you.

If you can write a clean version that uses Ordering, that would be cool.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ordering won't be clean. I'll just leave it at a boolean. I tried to convert the code to allow for floats, but this really messes the clarity up a lot because in rust, floats don't implement Ord and Eq

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The part where I find the leftmost point would change from a simple min_by_key() to this:

    let leftmost_point = gift
        // Iterate over all points
        .iter()
        // Find the point with minimum x
        // Unfortunately, we can't use min_by_key here because floats in rust
        // do not implement Ord.
        .fold((f64::NAN, f64::NAN), |acc, val| if acc.0.partial_cmp(&val.0) == Some(Ordering::Less){
            acc
        } else {
            val
        })
        // If there are no points in the gift, there might
        // not be a minimum. Unwrap fails (panics) the program
        // if there wasn't a minimum, but we know there always
        // is because we checked the size of the gift.
        .unwrap()
        .clone();

}

fn jarvis_march(gift: &[Point]) -> Option<Vec<Point>> {
// There can only be a convex hull if there are more than 2 points
if gift.len() < 3 {
return None;
}

let leftmost_point = gift
// Iterate over all points
.iter()
// Find the point with minimum x
.min_by_key(|i| i.0)
// If there are no points in the gift, there might
// not be a minimum. Unwrap fails (panics) the program
// if there wasn't a minimum, but we know there always
// is because we checked the size of the gift.
.unwrap()
.clone();

let mut hull = vec![leftmost_point];

let mut point_on_hull = leftmost_point;
loop {
// Search for the next point on the hull
let mut endpoint = gift[0];
for i in 1..gift.len() {
if endpoint == point_on_hull || !turn_counter_clockwise(gift[i], hull[hull.len() - 1], endpoint) {
endpoint = gift[i];
}
}

point_on_hull = endpoint;

// Stop whenever we got back to the same point
// as we started with, and we wrapped the gift
// completely.
if hull[0] == endpoint {
break;
} else {
hull.push(point_on_hull);
}
}

Some(hull)
}

fn main() {
let test_gift = vec![
(-5, 2), (5, 7), (-6, -12), (-14, -14), (9, 9),
(-1, -1), (-10, 11), (-6, 15), (-6, -8), (15, -9),
(7, -7), (-2, -9), (6, -5), (0, 14), (2, 8)
];

let hull = jarvis_march(&test_gift);

println!("The points in the hull are: {:?}", hull);
}
2 changes: 2 additions & 0 deletions contents/jarvis_march/jarvis_march.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Since this algorithm, there have been many other algorithms that have advanced t
[import, lang:"go"](code/golang/jarvis.go)
{% sample lang="v" %}
[import, lang:"v"](code/v/jarvis.v)
{% sample lang="rust" %}
[import, lang:"rust"](code/rust/jarvis_march.rs)
{% endmethod %}

<script>
Expand Down