Not social-democracy

I’m doing advent of code this year to fight off all of the skill atrophy from autistic burnout and mandated slop on the job. I’ll see if I can keep up posting these. I encourage anyone who wants to participate to participate.

Lucky for me, day 1 is pretty easy. These are my solutions.

spoiler
use std::collections::HashMap;

use crate::utils::{ascii_text_to_int, read_lines};

pub fn solution_1() {
    let ids = get_sorted_ids();
    let answer = multiply_ids(ids.iter().rev());

    println!("{answer}");
}

pub fn solution_2() {
    let ids = get_sorted_ids();
    let answer = multiply_ids(ids.iter());

    println!("{answer}");
}

fn get_sorted_ids() -> Vec<(u32, u32)> {
    let id_map = read_lines("src/day1/input.txt")
        .map(ascii_text_to_int)
        .fold(HashMap::new(), |mut id_map, id| {
            *id_map.entry(id).or_insert(1u32) += 1;
            id_map
        });

    let mut ids = id_map.into_iter().collect::<Vec<_>>();
    ids.sort_by_key(|(_, count)| *count);

    ids
}

fn multiply_ids<'a>(ids: impl Iterator<Item = &'a (u32, u32)>) -> u32 {
    ids.take(3).map(|(id, _)| id).product()
}

My inner perfectionist isn’t happy that had to make 2 data structures on the heap (the HashMap and Vec) just to immediately throw them out, but it is what it is. Rust has a way of bringing out my inner perfectionist.

The read_lines utility isn’t doing anything too surprising. I’m pretty happy about my ascii_text_to_int function though.

pub fn ascii_text_to_int(s: impl AsRef<str>) -> u32 {
    s.as_ref()
        .as_bytes()
        .iter()
        .rev()
        .enumerate()
        .map(|(i, &byte)| (10u32.pow(i as u32)) * ((byte - b'0') as u32))
        .sum()
}

I’m sure someone somewhere has already done a similar approach, but I still feel clever for coming up with it on my own. I make no guarantees that the string isn’t an ASCII character 0-9 since these are simply toy problems.

  • makotech222 [he/him]@hexbear.net
    link
    fedilink
    English
    arrow-up
    4
    ·
    edit-2
    45 minutes ago

    Thanks for reminding me to do this. Here’s my C# answer in 3 lines

    namespace AdventOfCode
    {
        internal class Program
        {
            async static Task Main(string[] args)
            {
                var data = (await File.ReadAllLinesAsync("Data/DayOne.txt")).Select(y => Convert.ToInt32(y)).ToList();
                var result = DayOne(data);
                Console.WriteLine(result.Item1);
                Console.WriteLine(result.Item2);
            }
    
            public static (int,int) DayOne(List<int> inputs)
            {
                var threeMostCommon =  inputs.GroupBy(x => x, x => x).OrderByDescending(x => x.Count()).Select(y => y.Key).Take(3).Aggregate((a,b) => a*b);
                var threeLeastCommon = inputs.GroupBy(x => x, x => x).OrderBy(x => x.Count()).Select(y => y.Key).Take(3).Aggregate((a, b) => a * b);
                return (threeMostCommon, threeLeastCommon);
            }
        }
    }
    
    
    
    • AppetiteOfExcess [she/her]@hexbear.netOP
      link
      fedilink
      English
      arrow-up
      1
      ·
      10 minutes ago

      Gotta love LINQ. Rust doesn’t have as many fancy iterator helpers in its standard library as C#. There is the itertools crate, but I like to challenge myself by staying away from third party libraries for challenges like these.

      I did just learn that my ascii to text method is wholly unnecessary and I could’ve just used str::parse::<u32>.