Skip to content

Instantly share code, notes, and snippets.

@itarato
Created December 15, 2015 08:39
Show Gist options
  • Select an option

  • Save itarato/c23fac29415afd951ae3 to your computer and use it in GitHub Desktop.

Select an option

Save itarato/c23fac29415afd951ae3 to your computer and use it in GitHub Desktop.
Feeding people with fruit from dailyprogrammer 242 easy.
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