Created
December 15, 2015 08:39
-
-
Save itarato/c23fac29415afd951ae3 to your computer and use it in GitHub Desktop.
Feeding people with fruit from dailyprogrammer 242 easy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::fmt; | |
| struct Plant { | |
| age: u32, | |
| } | |
| struct Garden { | |
| plants: Vec<Plant>, | |
| fruit: u32, | |
| } | |
| impl Garden { | |
| fn new(n: u32) -> Garden { | |
| Garden { | |
| plants: Vec::new(), | |
| fruit: n, | |
| } | |
| } | |
| fn plant_fruit(&mut self) { | |
| for _ in 0..self.fruit { | |
| self.plants.push(Plant{ age: 0 }); | |
| } | |
| self.fruit = 0 | |
| } | |
| fn grow(&mut self) { | |
| for p in self.plants.iter_mut() { | |
| p.age += 1; | |
| self.fruit += p.age; | |
| } | |
| } | |
| } | |
| impl fmt::Debug for Garden { | |
| fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { | |
| let mut total = 0; | |
| for p in &self.plants { | |
| total += p.age + 1 | |
| } | |
| write!(f, "Garden, fruit: {}, capacity: {}", self.fruit, total) | |
| } | |
| } | |
| fn main() { | |
| println!("Solution: {}", solve(15, 200)); | |
| println!("Solution: {}", solve(1, 50000)); | |
| println!("Solution: {}", solve(250, 150000)); | |
| } | |
| fn solve(n: u32, goal: u32) -> u32 { | |
| let mut g = Garden::new(n); | |
| let mut iter = 1; | |
| while g.fruit < goal { | |
| g.plant_fruit(); | |
| g.grow(); | |
| iter += 1; | |
| } | |
| iter | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment