Day 11: Santa's Snowy Algorithm
"LISTEN UP, YOU MAGNIFICENT, STRESSED-OUT CODERS!" Santa bellowed. "Tomorrow, we test the sleigh again. And this time, it WILL work. No more Florida nonsense. Palm trees are NOT part of the Christmas aesthetic."
He pointed dramatically at Bernard and Pepper. “You two are coming with me. If the sleigh glitches mid-flight again, I want live debugging happening in real time. No excuses.”
The elves whispered nervously. Everyone still remembered the "Florida Incident"—last week’s failed test landing in a snowless golf course. Santa didn’t appreciate the HOA complaints.
“This time,” Santa continued, pacing, “Snowball compiled every scrap of data we need for each location. Top-notch metrics. But metrics mean nothing without an algorithm. Your job is to write a function to find the snowball-densest landing spot.”
Your mission
Snowball has provided you with a Vec<Location>, now the other elves need to write a function to find the most dense area with snow.
Here is what you need to to:
- Write a
new()associated function for theLocationstruct that takesx: f64,y: f64,z: f64,area: f64, andsnow. - The
snowparameter must be able to accept allSnowKg,SnowLbandSnowballtypes. - Implement a method for the
Locationstruct nameddensity()that gets the density of snow in the location. - Finish the
find_best_locationfunction which takes aVec<Location>and returns aResult<Location, Box<dyn Error>>.
That's it! 🎅
Hints
If you’re stuck or need a starting point, here are some hints to help you along the way!
Click here to show hints.
-
When we implemented the
From<T>trait in the previous challenge, Rust automatically implemented theInto<T>trait for us. This means that if you implementFrom<T>for a type, you can convert that type toTusing theinto()method. e.g.let snow = snow.into();. -
For the
snowparameter, you can accept anything that implements theInto<Snowball>trait. e.g.new(x: f64, y: f64, z: f64, area: f64, snow: impl Into<Snowball>) -> Self. Hereimpl Into<Snowball>means any type that implements theInto<Snowball>trait. -
Convert the
snowparameter to aSnowballtype using theinto()method. e.g.let snow = snow.into();. -
Implement the
density()method for theLocationstruct. The density of snow is calculated by dividing the snow weight by the area of the location. Make sure you handle the division by zero case. -
Use
into_iterto convert theVec<Location>to a consuming iterator. e.g.locations.into_iter(). -
Use the
max_by()method to find the location with the highest density of snow. e.g.locations .into_iter() .max_by(|a, b| { a.density() .partial_cmp(&b.density()) .unwrap_or(Ordering::Equal) }) -
Import
Ordering::Equalusinguse std::cmp::Ordering. -
Use the
ok_or()method to convert theOptionreturned bymax_by()to aResult. e.g.ok_or("No locations found".into()).
Run to execute your code and see test results here.