Skip to content

Instantly share code, notes, and snippets.

@salty-horse
Created December 14, 2015 22:48
Show Gist options
  • Save salty-horse/93f27beec4aa2e6d1a91 to your computer and use it in GitHub Desktop.
Save salty-horse/93f27beec4aa2e6d1a91 to your computer and use it in GitHub Desktop.
Advent of Code day 5
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex;
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
fn passes_rule_1(s: &str) -> bool {
let three_vowels = regex!("[aeiou].*[aeiou].*[aeiou]");
let bad_strings = regex!("ab|cd|pq|xy");
if bad_strings.is_match(s) {
return false;
}
if !three_vowels.is_match(s) {
return false;
}
// Look for two letters in a row.
// Rust's Regex package doesn't support backreferences so we do this the old-fashioned way.
let mut prev_char = '\0';
for c in s.chars() {
if prev_char != '\0' && c == prev_char {
return true;
}
prev_char = c;
}
false
}
fn passes_rule_2(s: &str) -> bool {
// Look for a pair of letters that appear twice in the string (no overlaps)
// Rust's Regex package doesn't support backreferences so we do this the old-fashioned way.
let mut prev_char = '\0';
let mut found = false;
for (i, c) in s.chars().enumerate() {
if prev_char == '\0' {
prev_char = c;
continue;
}
let pair = prev_char.to_string() + &c.to_string();
if s[i+1..].contains(&pair) {
found = true;
break;
}
prev_char = c;
}
if !found {
return false;
}
// Look for two letters that repeat, with one letter between them
// Rust's Regex package doesn't support backreferences so we do this the old-fashioned way.
let mut prev_char = '\0';
let mut prev_prev_char = '\0';
for c in s.chars() {
if c == prev_prev_char {
return true
}
if prev_char != '\0' {
prev_prev_char = prev_char
}
prev_char = c;
}
false
}
fn main() {
let input_fname = "day5_input.txt";
let f = File::open(input_fname).unwrap();
let reader = BufReader::new(f);
let mut nice_strings_1 = 0;
let mut nice_strings_2 = 0;
for line in reader.lines() {
let l = &(line.unwrap()[..]);
if passes_rule_1(l) {
nice_strings_1 += 1;
}
if passes_rule_2(l) {
println!("Good rule 2: {}", l);
nice_strings_2 += 1;
}
}
println!("Nice strings 1: {}", nice_strings_1);
println!("Nice strings 2: {}", nice_strings_2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment