Skip to content

Instantly share code, notes, and snippets.

@loganintech
Created February 3, 2019 01:35
Show Gist options
  • Save loganintech/0b609311a708a0b5034a105857d20e51 to your computer and use it in GitHub Desktop.
Save loganintech/0b609311a708a0b5034a105857d20e51 to your computer and use it in GitHub Desktop.
A small rust snippet to parse data from assignment 4 of my OSU Analysis of Algorithms class
//File parsing. Feel free to read, but totally unrelated to the algorithm
//Implementing this trait is what allows us to use the `.into()` function for conversion
impl From<File> for ActivitySet {
fn from(file: File) -> Self {
//Make a buffer to store our activities once they're parsed
let mut activities: Vec<Vec<Activity>> = vec![];
//Create a buffered reader, which allows for splitting the file by .lines()
let reader = BufReader::new(file);
//Split the file into different lines and make sure they are parsed ok. If they aren't they're discarded
let lines = reader.lines().filter_map(Result::ok);
//For every line
for line in lines {
//Split it by spaces so lines `1 2 3` become ["1", "2", "3"] and `1` becomes [1]
let parts: Vec<_> = line.split(" ").collect();
//If we're not looking at a data line
if parts.len() != 3 {
//Extrac the number of activities and parse it into a number which is the number of bits of the current architecture (used for indexing)
let num = parts[0].parse::<usize>().unwrap();
//Add the space for our list of activities with pre-determined length (to save memory and allocation time)
activities.push(Vec::with_capacity(num));
//And skip to the next line
continue;
}
//Now we split our parts into an iterator
let parts: Vec<_> = parts
.into_iter()
//Parse each number in this line into unsigned 32 bit ints, and panic if it fails
.map(|x| x.parse::<u32>().unwrap())
//Collect the iterator of converted values back into an array
.collect();
//Get the latest array we're working on building
let last_index = activities.len() - 1;
//Add a new activity from the parts we've parsed earlier
activities[last_index].push(Activity {
num: parts[0],
start: parts[1],
end: parts[2],
})
}
//Return our set of activities in the order of when they were parsed
ActivitySet(activities)
}
}
11
1 1 4
2 3 5
3 0 6
4 5 7
5 3 9
6 5 9
7 6 10
8 8 11
9 8 12
10 2 14
11 12 16
3
3 6 8
1 7 9
2 1 2
6
1 1 5
2 3 6
3 6 10
4 8 11
5 11 15
6 12 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment