Welcome everyone to the 2023 advent of code! Thank you all for stopping by and participating in it in programming.dev whether youre new to the event or doing it again.

This is an unofficial community for the event as no official spot exists on lemmy but ill be running it as best I can with Sigmatics modding as well. Ill be running a solution megathread every day where you can share solutions with other participants to compare your answers and to see the things other people come up with


Day 1: Trebuchet?!


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 6 minutes

  • Tom@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    10 months ago

    Java

    My take on a modern Java solution (parts 1 & 2).

    spoiler
    package thtroyer.day1;
    
    import java.util.*;
    import java.util.stream.IntStream;
    import java.util.stream.Stream;
    
    
    public class Day1 {
        record Match(int index, String name, int value) {
        }
    
        Map numbers = Map.of(
                "one", 1,
                "two", 2,
                "three", 3,
                "four", 4,
                "five", 5,
                "six", 6,
                "seven", 7,
                "eight", 8,
                "nine", 9);
    
        /**
         * Takes in all lines, returns summed answer
         */
        public int getCalibrationValue(String... lines) {
            return Arrays.stream(lines)
                    .map(this::getCalibrationValue)
                    .map(Integer::parseInt)
                    .reduce(0, Integer::sum);
        }
    
        /**
         * Takes a single line and returns the value for that line,
         * which is the first and last number (numerical or text).
         */
        protected String getCalibrationValue(String line) {
            var matches = Stream.concat(
                            findAllNumberStrings(line).stream(),
                            findAllNumerics(line).stream()
                    ).sorted(Comparator.comparingInt(Match::index))
                    .toList();
    
            return "" + matches.getFirst().value() + matches.getLast().value();
        }
    
        /**
         * Find all the strings of written numbers (e.g. "one")
         *
         * @return List of Matches
         */
        private List findAllNumberStrings(String line) {
            return IntStream.range(0, line.length())
                    .boxed()
                    .map(i -> findAMatchAtIndex(line, i))
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .sorted(Comparator.comparingInt(Match::index))
                    .toList();
        }
    
    
        private Optional findAMatchAtIndex(String line, int index) {
            return numbers.entrySet().stream()
                    .filter(n -> line.indexOf(n.getKey(), index) == index)
                    .map(n -> new Match(index, n.getKey(), n.getValue()))
                    .findAny();
        }
    
        /**
         * Find all the strings of digits (e.g. "1")
         *
         * @return List of Matches
         */
        private List findAllNumerics(String line) {
            return IntStream.range(0, line.length())
                    .boxed()
                    .filter(i -> Character.isDigit(line.charAt(i)))
                    .map(i -> new Match(i, null, Integer.parseInt(line.substring(i, i + 1))))
                    .toList();
        }
    
        public static void main(String[] args) {
            System.out.println(new Day1().getCalibrationValue(args));
        }
    }
    
    
  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    10 months ago

    Uiua solution

    I may add solutions in Uiua depending on how easy I find them, so here’s today’s (also available to run online):

    Inp ← {"four82nine74" "hlpqrdh3" "7qt" "12" "1one"}
    # if needle is longer than haystack, return zeros
    SafeFind ← ((⌕|-.;)< ∩⧻ , ,)
    FindDigits ← (× +19 ⊠(□SafeFind∩⊔) : Inp)
    "123456789"
    ⊜□ ≠@\s . "one two three four five six seven eight nine"
    ∩FindDigits
    BuildNum ← (/+∵(/+⊂⊃(×101)(↙ 1⇌) ▽≠0.⊔) /↥)
    ∩BuildNum+,
    

    or stripping away all the fluff:

    Inp ← {"four82nine74" "hlpqrdh3" "7qt" "12" "1one"}
    ⊜□ ≠@\s."one two three four five six seven eight nine" "123456789"
    ∩(×+19⊠(□(⌕|-.;)<⊙:∩(⧻.⊔)):Inp)
    ∩(/+∵(/+⊂⊃(×101)(↙1⇌)▽≠0.⊔)/↥)+,
    
  • calvin@lemmy.calvss.com
    link
    fedilink
    arrow-up
    3
    ·
    10 months ago

    I wanted to see if it was possible to do part 1 in a single line of Python:

    print(sum([(([int(i) for i in line if i.isdigit()][0]) * 10 + [int(i) for i in line if i.isdigit()][-1]) for line in open("input.txt")]))

  • 🔻Sleepless One🔻@lemmygrad.ml
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    10 months ago

    I finally got my solutions done. I used rust. I feel like 114 lines (not including empty lines or driver code) for both solutions is pretty decent. If lemmy’s code blocks are hard to read, I also put my solutions on github.

    use std::{
        cell::OnceCell,
        collections::{HashMap, VecDeque},
        ops::ControlFlow::{Break, Continue},
    };
    
    use crate::utils::read_lines;
    
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum NumType {
        Digit,
        DigitOrWord,
    }
    
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum FromDirection {
        Left,
        Right,
    }
    
    const WORD_NUM_MAP: OnceCell> = OnceCell::new();
    
    fn init_num_map() -> HashMap<&'static str, u8> {
        HashMap::from([
            ("one", b'1'),
            ("two", b'2'),
            ("three", b'3'),
            ("four", b'4'),
            ("five", b'5'),
            ("six", b'6'),
            ("seven", b'7'),
            ("eight", b'8'),
            ("nine", b'9'),
        ])
    }
    
    const MAX_WORD_LEN: usize = 5;
    
    fn get_digit<i>(mut bytes: I, num_type: NumType, from_direction: FromDirection) -> Option
    where
        I: Iterator,
    {
        let digit = bytes.try_fold(VecDeque::new(), |mut byte_queue, byte| {
            if byte.is_ascii_digit() {
                Break(byte)
            } else if num_type == NumType::DigitOrWord {
                if from_direction == FromDirection::Left {
                    byte_queue.push_back(byte);
                } else {
                    byte_queue.push_front(byte);
                }
    
                let word = byte_queue
                    .iter()
                    .map(|&amp;byte| byte as char)
                    .collect::();
    
                for &amp;key in WORD_NUM_MAP
                    .get_or_init(init_num_map)
                    .keys()
                    .filter(|k| k.len() &lt;= byte_queue.len())
                {
                    if word.contains(key) {
                        return Break(*WORD_NUM_MAP.get_or_init(init_num_map).get(key).unwrap());
                    }
                }
    
                if byte_queue.len() == MAX_WORD_LEN {
                    if from_direction == FromDirection::Left {
                        byte_queue.pop_front();
                    } else {
                        byte_queue.pop_back();
                    }
                }
    
                Continue(byte_queue)
            } else {
                Continue(byte_queue)
            }
        });
    
        if let Break(byte) = digit {
            Some(byte)
        } else {
            None
        }
    }
    
    fn process_digits(x: u8, y: u8) -> u16 {
        ((10 * (x - b'0')) + (y - b'0')).into()
    }
    
    fn solution(num_type: NumType) {
        if let Ok(lines) = read_lines("src/day_1/input.txt") {
            let sum = lines.fold(0_u16, |acc, line| {
                let line = line.unwrap_or_else(|_| String::new());
                let bytes = line.bytes();
                let left = get_digit(bytes.clone(), num_type, FromDirection::Left).unwrap_or(b'0');
                let right = get_digit(bytes.rev(), num_type, FromDirection::Right).unwrap_or(left);
    
                acc + process_digits(left, right)
            });
    
            println!("{sum}");
        }
    }
    
    pub fn solution_1() {
        solution(NumType::Digit);
    }
    
    pub fn solution_2() {
        solution(NumType::DigitOrWord);
    }
    ```</i>
  • Joey@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    10 months ago

    My solution in rust. I’m sure there’s a lot more clever ways to do it but this is what I came up with.

    Code
    use std::{io::prelude::*, fs::File, path::Path, io };
    
    fn main() 
    {
        run_solution(false); 
    
        println!("\nPress enter to continue");
        let mut buffer = String::new();
        io::stdin().read_line(&amp;mut buffer).unwrap();
    
        run_solution(true); 
    }
    
    fn run_solution(check_for_spelled: bool)
    {
        let data = load_data("data/input");
    
        println!("\nProcessing Data...");
    
        let mut sum: u64 = 0;
        for line in data.lines()
        {
            // Doesn't seem like the to_ascii_lower call is needed but... just in case
            let first = get_digit(line.to_ascii_lowercase().as_bytes(), false, check_for_spelled);
            let last = get_digit(line.to_ascii_lowercase().as_bytes(), true, check_for_spelled);
    
    
            let num = (first * 10) + last;
    
            // println!("\nLine: {} -- First: {}, Second: {}, Num: {}", line, first, last, num);
            sum += num as u64;
        }
    
        println!("\nFinal Sum: {}", sum);
    }
    
    fn get_digit(line: &amp;[u8], from_back: bool, check_for_spelled: bool) -> u8
    {
        let mut range: Vec = (0..line.len()).collect();
        if from_back
        {
            range.reverse();
        }
    
        for i in range
        {
            if is_num(line[i])
            {
                return (line[i] - 48) as u8;
            }
    
            if check_for_spelled
            {
                if let Some(num) = is_spelled_num(line, i)
                {
                    return num;
                }
            }
        }
    
        return 0;
    }
    
    fn is_num(c: u8) -> bool
    {
        c >= 48 &amp;&amp; c &lt;= 57
    }
    
    fn is_spelled_num(line: &amp;[u8], start: usize) -> Option
    {
        let words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
    
        for word_idx in 0..words.len()
        {
            let mut i = start;
            let mut found = true;
            for c in words[word_idx].as_bytes()
            {
                if i &lt; line.len() &amp;&amp; *c != line[i]
                {
                    found = false;
                    break;
                }
                i += 1;
            }
    
            if found &amp;&amp; i &lt;= line.len()
            {
                return Some(word_idx as u8 + 1);
            }
        }
    
        return None;
    }
    
    fn load_data(file_name: &amp;str) -> String
    {
        let mut file = match File::open(Path::new(file_name))
        {
            Ok(file) => file,
            Err(why) => panic!("Could not open file {}: {}", Path::new(file_name).display(), why),
        };
    
        let mut s = String::new();
        let file_contents = match file.read_to_string(&amp;mut s) 
        {
            Err(why) => panic!("couldn't read {}: {}", Path::new(file_name).display(), why),
            Ok(_) => s,
        };
        
        return file_contents;
    }
    
    • 🔻Sleepless One🔻@lemmygrad.ml
      link
      fedilink
      English
      arrow-up
      1
      ·
      10 months ago

      One small thing that would make it easier to read would be to use (I don’t know what the syntax is called) as opposed to the magic numbers for getting the ascii code for a character as a u8, e.g. b'0' instead of 48.

      • Joey@programming.dev
        link
        fedilink
        arrow-up
        1
        ·
        10 months ago

        Oh yeah that’s a good point. I have seen that before but I didn’t think of it at the time.

  • stifle867@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    10 months ago

    My solutin in Elixir for both part 1 and part 2 is below. It does use regex and with that there are many different ways to accomplish the goal. I’m no regex master so I made it as simple as possible and relied on the language a bit more. I’m sure there are cooler solutions with no regex too, this is just what I settled on:

    https://pastebin.com/u1SYJ4tY
    defmodule AdventOfCode.Day01 do
      def part1(args) do
        number_regex = ~r/([0-9])/
    
        args
        |> String.split(~r/\n/, trim: true)
        |> Enum.map(&amp;first_and_last_number(&amp;1, number_regex))
        |> Enum.map(&amp;number_list_to_integer/1)
        |> Enum.sum()
      end
    
      def part2(args) do
        number_regex = ~r/(?=(one|two|three|four|five|six|seven|eight|nine|[0-9]))/
    
        args
        |> String.split(~r/\n/, trim: true)
        |> Enum.map(&amp;first_and_last_number(&amp;1, number_regex))
        |> Enum.map(fn number -> Enum.map(number, &amp;replace_word_with_number/1) end)
        |> Enum.map(&amp;number_list_to_integer/1)
        |> Enum.sum()
      end
    
      defp first_and_last_number(string, regex) do
        matches = Regex.scan(regex, string)
        [_, first] = List.first(matches)
        [_, last] = List.last(matches)
    
        [first, last]
      end
    
      defp number_list_to_integer(list) do
        list
        |> List.to_string()
        |> String.to_integer()
      end
    
      defp replace_word_with_number(string) do
        numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    
        String.replace(string, numbers, fn x ->
          (Enum.find_index(numbers, &amp;(&amp;1 == x)) + 1)
          |> Integer.to_string()
        end)
      end
    end
    
  • asyncrosaurus@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    10 months ago

    [Language: C#]

    This isn’t the most performant or elegant, it’s the first one that worked. I have 3 kids and a full time job. If I get through any of these, it’ll be first pass through and first try that gets the correct answer.

    Part 1 was very easy, just iterated the string checking if the char was a digit. Ditto for the last, by reversing the string. Part 2 was also not super hard, I settled on re-using the iterative approach, checking each string lookup value first (on a substring of the current char), and if the current char isn’t the start of a word, then checking if the char was a digit. Getting the last number required reversing the string and the lookup map.

    Part 1:

    var list = new List((await File.ReadAllLinesAsync(@".\Day 1\PuzzleInput.txt")));
    
    int total = 0;
    foreach (var item in list)
    {
        //forward
        string digit1 = string.Empty;
        string digit2 = string.Empty;
    
    
        foreach (var c in item)
        {
            if ((int)c >= 48 &amp;&amp; (int)c &lt;= 57)
            {
                digit1 += c;
            
                break;
            }
        }
        //reverse
        foreach (var c in item.Reverse())
        {
            if ((int)c >= 48 &amp;&amp; (int)c &lt;= 57)
            {
                digit2 += c;
    
                break;
            }
    
        }
        total += Int32.Parse(digit1 +digit2);
    }
    
    Console.WriteLine(total);
    

    Part 2:

    var list = new List((await File.ReadAllLinesAsync(@".\Day 1\PuzzleInput.txt")));
    var numbers = new Dictionary() {
        {"one" ,   1}
        ,{"two" ,  2}
        ,{"three" , 3}
        ,{"four" , 4}
        ,{"five" , 5}
        ,{"six" , 6}
        ,{"seven" , 7}
        ,{"eight" , 8}
        , {"nine" , 9 }
    };
    int total = 0;
    string digit1 = string.Empty;
    string digit2 = string.Empty;
    foreach (var item in list)
    {
        //forward
        digit1 = getDigit(item, numbers);
        digit2 = getDigit(new string(item.Reverse().ToArray()), numbers.ToDictionary(k => new string(k.Key.Reverse().ToArray()), k => k.Value));
        total += Int32.Parse(digit1 + digit2);
    }
    
    Console.WriteLine(total);
    
    string getDigit(string item,                 Dictionary numbers)
    {
        int index = 0;
        int digit = 0;
        foreach (var c in item)
        {
            var sub = item.AsSpan(index++);
            foreach(var n in numbers)
            {
                if (sub.StartsWith(n.Key))
                {
                    digit = n.Value;
                    goto end;
                }
            }
    
            if ((int)c >= 48 &amp;&amp; (int)c &lt;= 57)
            {
                digit = ((int)c) - 48;
                break;
            }
        }
        end:
        return digit.ToString();
    }
    
  • hades@lemm.ee
    link
    fedilink
    arrow-up
    2
    ·
    10 months ago

    Python

    Questions and feedback welcome!

    import re
    
    from .solver import Solver
    
    class Day01(Solver):
      def __init__(self):
        super().__init__(1)
        self.lines = []
    
      def presolve(self, input: str):
        self.lines = input.rstrip().split('\n')
    
      def solve_first_star(self):
        numbers = []
        for line in self.lines:
          digits = [ch for ch in line if ch.isdigit()]
          numbers.append(int(digits[0] + digits[-1]))
        return sum(numbers)
    
      def solve_second_star(self):
        numbers = []
        digit_map = {
          "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
          "six": 6, "seven": 7, "eight": 8, "nine": 9, "zero": 0,
          }
        for i in range(10):
          digit_map[str(i)] = i
        for line in self.lines:
          digits = [digit_map[digit] for digit in re.findall(
              "(?=(one|two|three|four|five|six|seven|eight|nine|[0-9]))", line)]
          numbers.append(digits[0]*10 + digits[-1])
        return sum(numbers)
    
  • I think I found a decently short solution for part 2 in python:

    DIGITS = {
        'one': '1',
        'two': '2',
        'three': '3',
        'four': '4',
        'five': '5',
        'six': '6',
        'seven': '7',
        'eight': '8',
        'nine': '9',
    }
    
    
    def find_digit(word: str) -> str:
        for digit, value in DIGITS.items():
            if word.startswith(digit):
                return value
            if word.startswith(value):
                return value
        return ''
    
    
    total = 0
    for line in puzzle.split('\n'):
        digits = [
            digit for i in range(len(line))
            if (digit := find_digit(line[i:]))
        ]
        total += int(digits[0] + digits[-1])
    
    
    print(total)
    
    • fhoekstra@programming.dev
      link
      fedilink
      arrow-up
      3
      ·
      10 months ago

      Looks very elegant! I’m having trouble understanding how this finds digit “words” from the end of the line though, as they should be spelled backwards IIRC? I.e. eno, owt, eerht

      • ScrewdriverFactoryFactoryProvider [they/them]@hexbear.net
        link
        fedilink
        English
        arrow-up
        2
        ·
        edit-2
        10 months ago

        It simply finds all possible digits and then locates the last one through the reverse indexing. It’s not efficient because there’s no shortcircuiting, but there’s no need to search the strings backwards, which is nice. Python’s startswith method is also hiding a lot of that other implementations have done explicitly.

  • abclop99@beehaw.org
    link
    fedilink
    arrow-up
    1
    ·
    10 months ago

    APL

    spoiler
    args ← {1↓⍵/⍨∨\⍵∊⊂'--'} ⎕ARG
    inputs ← ⎕FIO[49]¨ args
    
    words ← 'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight' 'nine'
    digits ← '123456789'
    
    part1 ← {↑↑+/{(10×↑⍵)+¯1↑⍵}¨{⍵~0}¨+⊃(⍳9)+.×digits∘.⍷⍵}
    "Part 1: ", part1¨ inputs
    
    part2 ← {↑↑+/{(10×↑⍵)+¯1↑⍵}¨{⍵~0}¨+⊃(⍳9)+.×(words∘.⍷⍵)+digits∘.⍷⍵}
    "Part 2: ", part2¨ inputs
    
    )OFF
    
  • bugsmith@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    10 months ago

    Part 02 in Rust 🦀 :

    use std::{
        collections::HashMap,
        env, fs,
        io::{self, BufRead, BufReader},
    };
    
    fn main() -> io::Result&lt;()> {
        let args: Vec = env::args().collect();
        let filename = &amp;args[1];
        let file = fs::File::open(filename)?;
        let reader = BufReader::new(file);
    
        let number_map = HashMap::from([
            ("one", "1"),
            ("two", "2"),
            ("three", "3"),
            ("four", "4"),
            ("five", "5"),
            ("six", "6"),
            ("seven", "7"),
            ("eight", "8"),
            ("nine", "9"),
        ]);
    
        let mut total = 0;
        for _line in reader.lines() {
            let digits = get_text_numbers(_line.unwrap(), &amp;number_map);
            if !digits.is_empty() {
                let digit_first = digits.first().unwrap();
                let digit_last = digits.last().unwrap();
                let mut cat = String::new();
                cat.push(*digit_first);
                cat.push(*digit_last);
                let cat: i32 = cat.parse().unwrap();
                total += cat;
            }
        }
        println!("{total}");
        Ok(())
    }
    
    fn get_text_numbers(text: String, number_map: &amp;HashMap&lt;&amp;str, &amp;str>) -> Vec {
        let mut digits: Vec = Vec::new();
        if text.is_empty() {
            return digits;
        }
        let mut sample = String::new();
        let chars: Vec = text.chars().collect();
        let mut ptr1: usize = 0;
        let mut ptr2: usize;
        while ptr1 &lt; chars.len() {
            sample.clear();
            ptr2 = ptr1 + 1;
            if chars[ptr1].is_digit(10) {
                digits.push(chars[ptr1]);
                sample.clear();
                ptr1 += 1;
                continue;
            }
            sample.push(chars[ptr1]);
            while ptr2 &lt; chars.len() {
                if chars[ptr2].is_digit(10) {
                    sample.clear();
                    break;
                }
                sample.push(chars[ptr2]);
                if number_map.contains_key(&amp;sample.as_str()) {
                    let str_digit: char = number_map.get(&amp;sample.as_str()).unwrap().parse().unwrap();
                    digits.push(str_digit);
                    sample.clear();
                    break;
                }
                ptr2 += 1;
            }
            ptr1 += 1;
        }
    
        digits
    }
    
  • Jummit@lemmy.one
    link
    fedilink
    arrow-up
    1
    ·
    10 months ago

    Trickier than expected! I ran into an issue with Lua patterns, so I had to revert to a more verbose solution, which I then used in Hare as well.

    Lua:

    lua
    -- SPDX-FileCopyrightText: 2023 Jummit
    --
    -- SPDX-License-Identifier: GPL-3.0-or-later
    
    local sum = 0
    for line in io.open("1.input"):lines() do
      local a, b = line:match("^.-(%d).*(%d).-$")
      if not a then
        a = line:match("%d+")
        b = a
      end
      if a and b then
        sum = sum + tonumber(a..b)
      end
    end
    print(sum)
    
    local names = {
      ["one"] = 1,
      ["two"] = 2,
      ["three"] = 3,
      ["four"] = 4,
      ["five"] = 5,
      ["six"] = 6,
      ["seven"] = 7,
      ["eight"] = 8,
      ["nine"] = 9,
      ["1"] = 1,
      ["2"] = 2,
      ["3"] = 3,
      ["4"] = 4,
      ["5"] = 5,
      ["6"] = 6,
      ["7"] = 7,
      ["8"] = 8,
      ["9"] = 9,
    }
    sum = 0
    for line in io.open("1.input"):lines() do
      local firstPos = math.huge
      local first
      for name, num in pairs(names) do
        local left = line:find(name)
        if left and left &lt; firstPos then
          firstPos = left
          first = num
        end
      end
      local last
      for i = #line, 1, -1 do
        for name, num in pairs(names) do
          local right = line:find(name, i)
          if right then
            last = num
            goto found
          end
        end
      end
      ::found::
      sum = sum + tonumber(first * 10 + last)
    end
    print(sum)
    
    

    Hare:

    hare
    // SPDX-FileCopyrightText: 2023 Jummit
    //
    // SPDX-License-Identifier: GPL-3.0-or-later
    
    use fmt;
    use types;
    use bufio;
    use strings;
    use io;
    use os;
    
    const numbers: [](str, int) = [
    	("one", 1),
    	("two", 2),
    	("three", 3),
    	("four", 4),
    	("five", 5),
    	("six", 6),
    	("seven", 7),
    	("eight", 8),
    	("nine", 9),
    	("1", 1),
    	("2", 2),
    	("3", 3),
    	("4", 4),
    	("5", 5),
    	("6", 6),
    	("7", 7),
    	("8", 8),
    	("9", 9),
    ];
    
    fn solve(start: size) void = {
    	const file = os::open("1.input")!;
    	defer io::close(file)!;
    	const scan = bufio::newscanner(file, types::SIZE_MAX);
    	let sum = 0;
    	for (let i = 1u; true; i += 1) {
    		const line = match (bufio::scan_line(&amp;scan)!) {
    		case io::EOF =>
    			break;
    		case let line: const str =>
    			yield line;
    		};
    		let first: (void | int) = void;
    		let last: (void | int) = void;
    		for (let i = 0z; i &lt; len(line); i += 1) :found {
    			for (let num = start; num &lt; len(numbers); num += 1) {
    				const start = strings::sub(line, i, strings::end);
    				if (first is void &amp;&amp; strings::hasprefix(start, numbers[num].0)) {
    					first = numbers[num].1;
    				};
    				const end = strings::sub(line, len(line) - 1 - i, strings::end);
    				if (last is void &amp;&amp; strings::hasprefix(end, numbers[num].0)) {
    					last = numbers[num].1;
    				};
    				if (first is int &amp;&amp; last is int) {
    					break :found;
    				};
    			};
    		};
    		sum += first as int * 10 + last as int;
    	};
    	fmt::printfln("{}", sum)!;
    };
    
    export fn main() void = {
    	solve(9);
    	solve(0);
    };
    
  • soulsource@discuss.tchncs.de
    link
    fedilink
    English
    arrow-up
    1
    ·
    edit-2
    10 months ago

    [Language: Lean4]

    I’ll only post the actual parsing and solution. I have written some helpers which are in other files, as is the main function. For the full code, please see my github repo.

    Part 2 is a bit ugly, but I’m still new to Lean4, and writing it this way (structural recursion) just worked without a proof or termination.

    Solution
    def parse (input : String) : Option $ List String :=
      some $ input.split Char.isWhitespace |> List.filter (not ∘ String.isEmpty)
    
    def part1 (instructions : List String) : Option Nat :=
      let firstLast := λ (o : Option Nat × Option Nat) (c : Char) ↦
        let digit := match c with
        | '0' => some 0
        | '1' => some 1
        | '2' => some 2
        | '3' => some 3
        | '4' => some 4
        | '5' => some 5
        | '6' => some 6
        | '7' => some 7
        | '8' => some 8
        | '9' => some 9
        | _ => none
        if let some digit := digit then
          match o.fst with
          | none => (some digit, some digit)
          | some _ => (o.fst, some digit)
        else
          o
      let scanLine := λ (l : String) ↦ l.foldl firstLast (none, none)
      let numbers := instructions.mapM ((uncurry Option.zip) ∘ scanLine)
      let numbers := numbers.map λ l ↦ l.map λ (a, b) ↦ 10*a + b
      numbers.map (List.foldl (.+.) 0)
    
    def part2 (instructions : List String) : Option Nat :=
      -- once I know how to prove stuff propery, I'm going to improve this. Maybe.
      let instructions := instructions.map String.toList
      let updateState := λ (o : Option Nat × Option Nat) (n : Nat) ↦ match o.fst with
        | none => (some n, some n)
        | some _ => (o.fst, some n)
      let extract_digit := λ (o : Option Nat × Option Nat) (l : List Char) ↦
        match l with
        | '0' :: _ | 'z' :: 'e' :: 'r' :: 'o' :: _ => (updateState o 0)
        | '1' :: _ | 'o' :: 'n' :: 'e' :: _ => (updateState o 1)
        | '2' :: _ | 't' :: 'w' :: 'o' :: _ => (updateState o 2)
        | '3' :: _ | 't' :: 'h' :: 'r' :: 'e' :: 'e' :: _ => (updateState o 3)
        | '4' :: _ | 'f' :: 'o' :: 'u' :: 'r' :: _ => (updateState o 4)
        | '5' :: _ | 'f' :: 'i' :: 'v' :: 'e' :: _ => (updateState o 5)
        | '6' :: _ | 's' :: 'i' :: 'x' :: _ => (updateState o 6)
        | '7' :: _ | 's' :: 'e' :: 'v' :: 'e' :: 'n' :: _ => (updateState o 7)
        | '8' :: _ | 'e' :: 'i' :: 'g' :: 'h' :: 't' :: _ => (updateState o 8)
        | '9' :: _ | 'n' :: 'i' :: 'n' :: 'e' :: _ => (updateState o 9)
        | _ => o
      let rec firstLast := λ (o : Option Nat × Option Nat) (l : List Char) ↦
        match l with
        | [] => o
        | _ :: cs => firstLast (extract_digit o l) cs
      let scanLine := λ (l : List Char) ↦ firstLast (none, none) l
      let numbers := instructions.mapM ((uncurry Option.zip) ∘ scanLine)
      let numbers := numbers.map λ l ↦ l.map λ (a, b) ↦ 10*a + b
      numbers.map (List.foldl (.+.) 0)
    
  • capitalpb@programming.dev
    link
    fedilink
    English
    arrow-up
    0
    ·
    edit-2
    10 months ago

    Solved part one in about thirty seconds. But wow, either my brain is just tired at this hour or I’m lacking in skill, but part two is harder than any other year has been on the first day. Anyway, I managed to solve it, but I absolutely hate it, and will definitely be coming back to try to clean this one up.

    https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day01.rs

    impl Solver for Day01 {
        fn star_one(&amp;self, input: &amp;str) -> String {
            let mut result = 0;
    
            for line in input.lines() {
                let line = line
                    .chars()
                    .filter(|ch| ch.is_ascii_digit())
                    .collect::>();
                let first = line.first().unwrap();
                let last = line.last().unwrap();
                let number = format!("{first}{last}").parse::().unwrap();
                result += number;
            }
    
            result.to_string()
        }
    
        fn star_two(&amp;self, input: &amp;str) -> String {
            let mut result = 0;
    
            for line in input.lines() {
                let mut first = None;
                let mut last = None;
    
                while first == None {
                    for index in 0..line.len() {
                        let line_slice = &amp;line[index..];
                        if line_slice.starts_with("one") || line_slice.starts_with("1") {
                            first = Some(1);
                        } else if line_slice.starts_with("two") || line_slice.starts_with("2") {
                            first = Some(2);
                        } else if line_slice.starts_with("three") || line_slice.starts_with("3") {
                            first = Some(3);
                        } else if line_slice.starts_with("four") || line_slice.starts_with("4") {
                            first = Some(4);
                        } else if line_slice.starts_with("five") || line_slice.starts_with("5") {
                            first = Some(5);
                        } else if line_slice.starts_with("six") || line_slice.starts_with("6") {
                            first = Some(6);
                        } else if line_slice.starts_with("seven") || line_slice.starts_with("7") {
                            first = Some(7);
                        } else if line_slice.starts_with("eight") || line_slice.starts_with("8") {
                            first = Some(8);
                        } else if line_slice.starts_with("nine") || line_slice.starts_with("9") {
                            first = Some(9);
                        }
    
                        if first.is_some() {
                            break;
                        }
                    }
                }
    
                while last == None {
                    for index in (0..line.len()).rev() {
                        let line_slice = &amp;line[index..];
                        if line_slice.starts_with("one") || line_slice.starts_with("1") {
                            last = Some(1);
                        } else if line_slice.starts_with("two") || line_slice.starts_with("2") {
                            last = Some(2);
                        } else if line_slice.starts_with("three") || line_slice.starts_with("3") {
                            last = Some(3);
                        } else if line_slice.starts_with("four") || line_slice.starts_with("4") {
                            last = Some(4);
                        } else if line_slice.starts_with("five") || line_slice.starts_with("5") {
                            last = Some(5);
                        } else if line_slice.starts_with("six") || line_slice.starts_with("6") {
                            last = Some(6);
                        } else if line_slice.starts_with("seven") || line_slice.starts_with("7") {
                            last = Some(7);
                        } else if line_slice.starts_with("eight") || line_slice.starts_with("8") {
                            last = Some(8);
                        } else if line_slice.starts_with("nine") || line_slice.starts_with("9") {
                            last = Some(9);
                        }
    
                        if last.is_some() {
                            break;
                        }
                    }
                }
    
                result += format!("{}{}", first.unwrap(), last.unwrap())
                    .parse::()
                    .unwrap();
            }
    
            result.to_string()
        }
    }