r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

54 Upvotes

407 comments sorted by

View all comments

Show parent comment

2

u/bwinton Dec 02 '18 edited Dec 02 '18

I ended up with something very similar, but I wonder if it would be better to test the length of the first string, then look for something of length n-1, and return it?

use std::collections::HashMap;

static INPUT : &'static str = include_str!("data/q02.data");

fn get_counts(line: &str) -> HashMap<char, u32> {
    let mut seen = HashMap::new();
    for char in line.chars() {
      let entry = seen.entry(char).or_insert(0);
      *entry += 1;
    }
    seen
}

fn process_data_a(data: &str) -> i32 {
  let mut two_count = 0;
  let mut three_count = 0;
  for line in data.lines() {
    let counts = get_counts(line);
    if counts.values().any(|x| x == &2) {
      two_count += 1;
    }
    if counts.values().any(|x| x == &3) {
      three_count += 1;
    }
  };
  two_count * three_count
}

fn process_data_b(data: &str) -> String {
  for (skip, line) in data.lines().enumerate() {
    let target = line.len() - 1;
    for test in data.lines().skip(skip + 1) {
      let answer: String = line.chars().zip(test.chars())
        .filter_map(|x| {
        if x.0 == x.1 {
          Some(x.0)
        } else {
          None
        }}).collect();
      if answer.len() == target {
        return answer;
      }
    }
  }
  "".to_string()
}