Last active
March 1, 2017 06:00
-
-
Save jmagnuson/ecf10784bb198d366258 to your computer and use it in GitHub Desktop.
parseEq
This file contains 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
#![feature(fnbox)] | |
extern crate itertools; | |
use std::io::prelude::*; | |
use std::io::BufReader; | |
use std::fs::File; | |
use std::collections::HashMap; | |
use std::boxed::FnBox; | |
fn parseEq<'a>(tok: &String, opMap: &HashMap<String, Vec<String>>, valMap: &mut HashMap<String, i32>) -> i32 { | |
if valMap.contains_key(tok) { | |
return *valMap.get(tok).unwrap(); | |
} | |
let ref eqArray: Vec<String> = *opMap.get(tok).unwrap(); | |
let eqSize: usize = eqArray.len(); | |
let retVal: i32 = | |
match eqSize { | |
3 => eqArray[0].parse::<i32>().unwrap_or_else(|_| parseEq(&eqArray[0], opMap, valMap)), | |
4 => !eqArray[1].parse::<i32>().unwrap_or_else(|_| parseEq(&eqArray[1], opMap, valMap)), | |
5 => { | |
let (op, opstr): (Box<Fn(i32, i32) -> i32>, &str) = match &*eqArray[1] { | |
"AND" => (Box::new(|x: i32, y: i32| x & y), "AND"), | |
"OR" => (Box::new(|x: i32, y: i32| x | y), "OR"), | |
"LSHIFT" => (Box::new(|x: i32, y: i32| x << y), "LSHIFT"), | |
"RSHIFT" => (Box::new(|x: i32, y: i32| x >> y), "RSHIFT"), | |
_ => (Box::new(|x: i32, y: i32| 0), "DUNNO") | |
}; | |
op(eqArray[0].parse::<i32>().unwrap_or_else(|_| parseEq(&eqArray[0], opMap, valMap)), | |
eqArray[2].parse::<i32>().unwrap_or_else(|_| parseEq(&eqArray[2], opMap, valMap)) | |
) | |
}, | |
_ => 0 | |
}; | |
valMap.insert(tok.clone(), retVal); | |
return retVal; | |
} | |
fn main() { | |
let f = File::open("input7-1.txt").unwrap(); | |
let br = BufReader::new(f); | |
let mut valMap: HashMap<String, i32> = HashMap::with_capacity(100); | |
let mut opMap: HashMap<String, Vec<String>> = HashMap::with_capacity(100); | |
for l in br.lines() { | |
let line = l.unwrap(); | |
let linev = line.split(' ').map(|l| l.to_string()).collect::<Vec<String>>(); | |
let len = linev.len()-1; | |
let key = linev[len].clone(); | |
//println!("{} -> {:?}", key, linev); | |
opMap.insert(key, linev); | |
} | |
let tok1: String = "a".to_string(); | |
println!("Testing for a..."); | |
let eq1: i32 = parseEq(&tok1, &opMap, &mut valMap); | |
println!("a1 = {}", eq1); | |
let tok2: String = "b".to_string(); | |
valMap.clear(); | |
valMap.insert(tok2, eq1); | |
println!("Testing for a again..."); | |
let eq2: i32 = parseEq(&tok1, &opMap, &mut valMap); | |
println!("a1 = {}", eq2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment