Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
What can I do to prevent borrowing errors?
use std::io::{BufferedReader, File};
use std::num::FromStrRadix;
#[deriving(Show)]
struct TreeNode<'a> {
value: uint,
left: Option<&'a TreeNode<'a>>,
right: Option<&'a TreeNode<'a>>,
}
impl<'a> TreeNode<'a> {
fn lsum(&self) -> uint {
let mut total = 0u;
let mut left = self.left;
loop {
match left {
Some(l) => {
total += l.value;
left = l.left;
},
None => break,
}
}
total
}
fn rsum(&self) -> uint {
let mut total = 0u;
let mut right = self.right;
loop {
match right {
Some(r) => {
total += r.value;
right = r.right;
},
None => break,
}
}
total
}
}
fn main() {
let path = Path::new("triangle.txt");
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => fail!("Could not open {}: {}", display, why.desc),
Ok(file) => BufferedReader::new(file),
};
let mut root = TreeNode{ value: 0u, left: None, right: None };
let mut previous: Vec<TreeNode> = Vec::new();
let mut current: Vec<TreeNode> = Vec::new();
for line in file.lines() {
let numbers: Vec<uint> = match line {
Err(why) => fail!("Could not read line: {}", why.desc),
Ok(nums) => nums.as_slice().trim_right_chars('\n').split_str(" ").map(|n| match FromStrRadix::from_str_radix(n, 10u) {
Some(num) => num,
None => fail!("Could not read number {}.", n),
}).collect()
};
let count = numbers.len();
match count {
0 => fail!("We don't have any numbers!"),
1 => {
root = TreeNode{ value: numbers[0], left: None, right: None };
previous = Vec::new();
previous.push(root);
}
_ => {
for n in numbers.into_iter() {
let node = TreeNode{ value: n, left: None, right: None };
current.push(node);
}
for (i, node) in previous.iter_mut().enumerate() {
node.left = Some(&current[i]);
node.right = Some(&current[i + 1]);
}
},
};
previous = current;
current = Vec::new();
}
let mut this = root;
let mut total = this.value;
loop {
match (this.left, this.right) {
(None, None) => break,
(Some(_), None) => fail!("The triangle is uneven! Missing a right value."),
(None, Some(_)) => fail!("The triangle is uneven! Missing a left value."),
(Some(&left), Some(&right)) => {
if this.lsum() > this.rsum() {
total += left.value;
this = left;
}
else {
total += right.value;
this = right;
}
}
};
};
println!("{}", total);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.