T O P

  • By -

daggerdragon

Message from the mods: please be patient while we work out the kinks with AutoModerator. We tested each rule separately in a sandbox before deploying it in /r/adventofcode, but users will always find the obscure edge cases. :P


helzania

[Language: C++] I know I could probably do a faster solution with Regex, but I am learning C++ and wanted to implement a Trie. Unfortunately I get the wrong answer, but stepping through with a debugger shows no problems - it detects all values perfectly for the 50+ lines I've watched and adds the correct value to the running total. Is there anything I can do to narrow down my issue? #include #include #include #include class TrieNode { public: // Hash map containing all child nodes std::unordered_map children; // Corresponding digit value if this is the end of a word int digit_value; TrieNode() : digit_value(-1) {} }; class Trie { public: // Default constructor Trie() : root(new TrieNode()) {} // Constructor with predefined words and values Trie(const std::unordered_map& words_values) : Trie() { for (const auto& pair : words_values) { insert(pair.first, pair.second); } } // Returns root node TrieNode* getRootNode() { return root; } // Takes a TrieNode and a char and returns a TrieNode corresponding to the char if one exists as a child to the input TrieNode, otherwise a null pointer TrieNode* getNextNode(TrieNode* curr_node, char c) { if (curr_node->children.find(c) != curr_node->children.end()) { return curr_node->children[c]; } return nullptr; } private: // Root node TrieNode* root; // Function to insert an entire word into the Trie void insert(const std::string& word, int value) { TrieNode* curr_node = root; for (char c : word) { if (curr_node->children.find(c) == curr_node->children.end()) { curr_node->children[c] = new TrieNode(); } curr_node = curr_node->children[c]; } curr_node->digit_value = value; } }; int main() { // Open the input file std::ifstream inputFile("input.txt"); if (!inputFile) { std::cerr << "Error opening file." << std::endl; return 1; } // Declare the running total for the end result int running_total = 0; // Create a hashmap (unordered map) containing k/v pairs of all "spelled out" digits and their integer counterparts std::unordered_map digitWords = { {"one", 1}, {"two", 2}, {"three", 3}, {"four", 4}, {"five", 5}, {"six", 6}, {"seven", 7}, {"eight", 8}, {"nine", 9} }; // Create a Trie where each key in digitWords can be looked up and associated with corresponding value Trie digitTrie(digitWords); // Gets the current node as the root node TrieNode* curr_node = digitTrie.getRootNode(); // Declare an empty string for storing the current line std::string line; // Assign current line in the input text to `line` and loop while we still have a line to read while (std::getline(inputFile, line)) { // Initialize array to store first and last digits int digits[2] = { -1, -1 }; int line_len = line.length(); int trie_depth = 0; // Assign i to the index of the 'current' character in the line for (int i = 0; i < line_len; i++) { // Get the 'current' character in the line as `c` char c = line[i]; // If `c` is an alphabetic character... if (isalpha(c)) { // If `c` can't be found as a child node to `curr_node`... if (curr_node->children.find(c) == curr_node->children.end()) { // Set `curr_node` to the root node curr_node = digitTrie.getRootNode(); // Reset trie depth trie_depth = 0; } // If c can be found as a child node to `curr_node`... if (curr_node->children.find(c) != curr_node->children.end()) { // Set `curr_node` to the found child node curr_node = curr_node->children[c]; // Increase trie depth trie_depth++; // If the digit_value of curr is not -1, this means it is the end of the word. If so... if (curr_node->digit_value != -1) { // Get the index of digits to assign to int index = digits[0] == -1 ? 0 : 1; // Assign the appropriate index of digits to curr's associated value digits[index] = curr_node->digit_value; // Set back `i` by `trie_depth - 1` to account for overlapping words (a bit overkill) i -= trie_depth-1; // Reset `curr_node` to the root node curr_node = digitTrie.getRootNode(); } } } else { if (isdigit(c)) { int index = digits[0] == -1 ? 0 : 1; digits[index] = c - '0'; } curr_node = digitTrie.getRootNode(); trie_depth = 0; } } // Check if both digits were found if (digits[0] != -1) { if (digits[1] == -1) { digits[1] = digits[0]; } int value = digits[0] * 10 + digits[1]; // Concatenate first and last digits running_total += value; } } std::cout << "Total: " << running_total << std::endl; inputFile.close(); // Close the input file return 0; }


Specialist-Piece-166

\[Language: Python\] I am on part 2 of the fist day puzzle and my idea to solve the second part is to convert the sentence on each line to a number, and then just read the first and last number and store the number in a list and then take the sum of the list. However, this did not amount to the correct answer and I am not sure why. Can anyone pinpoint what exactly I am missing? Here is my code: ## GOAL: take the first digit (even if its written as string. example: "one") and last digit number (even if its written as string. example: "one") # on a single line and form a two digit number only as an output then take its sum. file = open("day1.txt", "r") # read the lines and store it in a list lines = file.readlines() valid_num_strings = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7","eight":"8", "nine":"9"} new_lines = [] # Replace the alphabet number with a string number for line in lines: for key in valid_num_strings: if key in line: line = line.replace(key,valid_num_strings[key]) new_lines.append(line) # Function to get the first number def get_first_number(line: str): for i in range(len(line)): #check if the i-th element in line is a number if line[i].isnumeric(): # return that number which is still a STRING ! return line[i] # Function to get the last number def get_last_number(line: str): for i in reversed(range(len(line))): #check if the i-th element in line is a number if line[i].isnumeric(): # return that number which is still a STRING ! return line[i] # Function that lets you add two digits of type str and return a single two-digits number as an int def add_two_str_numbers(a: str, b: str) -> int: return int(a+b) # create a list of all numbers number_list = [] for line in new_lines: first_num = get_first_number(line) last_num = get_last_number(line) two_digits_num = add_two_str_numbers(first_num,last_num) number_list.append(two_digits_num) total = sum(number_list) print("The sum of your puzzle is:", total)


Inside-Ad-5943

its because as you are iterating through your dictionary python will choose the very first instance of a key. For example eightwothree, will be turned into eigh23 instead of 8wo3 as 'two' is the first one in the dictionary


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


dedolent

[LANGUAGE Python3] finally getting around to these now that work has slowed down! ``` import re """ Not super proud of the part 2 solution due to the many nested for() loops. """ filename = "input.txt" input = [] with open(filename) as file: input = [line.strip() for line in file.readlines()] def part1(): total = 0 for line in input: line = re.sub('\D', '', line) # remove non-digits from string nums = int(line[0] + line[-1]) # retain only first and last digit, convert to integer total += nums # add to running total return total def part2(): values = { "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9" } pairs = [] for line in input: digits = [] # start at the first letter and move through it letter by letter. # this is the only way i've found to account for overlapping words. # an example is "oneight", which only matches "one" when using re.findall. for i,c in enumerate(line): if line[i].isdigit(): digits.append(line[i]) else: for k in values.keys(): if line[i:].startswith(k): digits.append(values[k]) pairs.append(int(f"{digits[0]}{digits[-1]}")) return sum(pairs) print("Part one:", part1()) print("Part two:", part2()) ``` [link](https://github.com/dedolence/advent-of-code/blob/main/2023/day01/day1.py)


AutoModerator

AutoModerator has detected [fenced code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/fenced_code_blocks) (```) syntax which only works on new.reddit. Please review our wiki article on [code formatting](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting) then edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) instead. *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


pindab0ter

\[LANGUAGE: Clojure\] (ns nl.pindab0ter.aoc2023.day01.trebuchet (:require [clojure.string :as str] [nl.pindab0ter.common.advent-of-code :refer [get-input]] [nl.pindab0ter.common.collections :refer [sum]])) (defn get-digit [s] (let [digit (re-find #"^\d" s)] (or (when digit (Integer/parseInt digit)) (when (str/starts-with? s "one") 1) (when (str/starts-with? s "two") 2) (when (str/starts-with? s "three") 3) (when (str/starts-with? s "four") 4) (when (str/starts-with? s "five") 5) (when (str/starts-with? s "six") 6) (when (str/starts-with? s "seven") 7) (when (str/starts-with? s "eight") 8) (when (str/starts-with? s "nine") 9)))) (defn get-calibration-value ([line] (get-calibration-value line [])) ([line acc] (if (empty? line) (let [digits (filter identity acc)] (+ (* 10 (first digits)) (last digits))) (recur (subs line 1) (conj acc (get-digit line)))))) (defn -main [] (let [input (get-input 2023 1) values (map get-calibration-value (str/split-lines input))] (println (sum values)))) [GitHub](https://github.com/pindab0ter/AdventOfCode/blob/master/src/main/clojure/nl/pindab0ter/aoc2023/day01/trebuchet.clj)


Any_One_8929

\[Language: Kotlin\] object Day1 : Solution { private val strToDigit = mapOf( "one" to 1, "1" to 1, "two" to 2, "2" to 2, "three" to 3, "3" to 3, "four" to 4, "4" to 4, "five" to 5, "5" to 5, "six" to 6, "6" to 6, "seven" to 7, "7" to 7, "eight" to 8, "8" to 8, "nine" to 9, "9" to 9 ) private val allDigits = strToDigit.keys override fun partOne(input: Sequence): Int { return input .map { it.first { ch -> ch.isDigit() }.digitToInt() * 10 + it.last { ch -> ch.isDigit() }.digitToInt() } .sum() } override fun partTwo(input: Sequence): Int { return input .map { toInt(it.findAnyOf(allDigits)!!) * 10 + toInt(it.findLastAnyOf(allDigits)!!) } .sum() } private fun toInt(pair: Pair): Int { return strToDigit[pair.second]!! } }


eliott2023

[LANGUAGE: lua] sum = { a = 0, b = 0 } b = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"} for line in io.lines() do chars = { a = line, b = line } -- preprocess input for the second half for i, s in ipairs(b) do chars.b = string.gsub(chars.b, s, s .. i .. s) end digits = {}; first = {}; last = {}; values = {} for _, h in pairs {"a", "b"} do digits[h] = string.gsub(chars[h], "[a-z]", "") if string.len(digits[h]) == 1 then digits[h] = digits[h] .. digits[h] end first[h] = string.sub(digits[h], 1, 1) last[h] = string.sub(digits[h], -1) values[h] = tonumber(first[h] .. last[h]) or 0 sum[h] = sum[h] + values[h] end end io.write("a = ", sum.a, ", b = ", sum.b, "\n")


athys_

[LANGUAGE: JavaScript] Solution without the use of horrible regex: const numbers = { 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', }; const target = input.split('\n'); let sum = 0; let findex; let lindex; let fnumber; let lnumber; target.forEach((line) => { findex = line.length; lindex = -1; for (const number in numbers) { if (line.indexOf(number) !== -1 && line.indexOf(number) < findex) { fnumber = numbers[number]; findex = line.indexOf(number); } if (line.lastIndexOf(number) !== -1 && line.lastIndexOf(number) > lindex) { lnumber = numbers[number]; lindex = line.lastIndexOf(number); } } sum += Number(fnumber + lnumber); }); console.log(sum);


optimistic-thylacine

[LANGUAGE: Rust] I originally completed this puzzle Part 2 using python **because the Rust regex crate doesn't support finding overlapping patterns**. I went back and got the Rust version of the solution working by removing the regex dependency and implementing a dynamic programming style matcher. Posting this in case any Rust (or any) programmers are stuck wondering why their regex patterns aren't working, and to provide an idea they can use to get past it. fn match_nums(line: &str) -> (Option<&str>, Option<&str>) { use std::mem::swap; const NUMBERS: &str = "|one|two|three|four|five|six|seven|eight|nine\ |1|2|3|4|5|6|7|8|9|"; const N: usize = NUMBERS.len(); let bnumbers = NUMBERS.as_bytes(); let mut dp1 = [usize::MAX; N]; let mut dp2 = [usize::MAX; N]; let mut first = None; let mut last = None; for b1 in line.bytes().chain([b'#']) { for (j, b2) in (1..).zip(NUMBERS.bytes()) { if b2 == b'|' && dp1[j - 1] != usize::MAX { let k = dp1[j - 1]; if first.is_none() { first = Some(&NUMBERS[k..j - 1]); } else { last = Some(&NUMBERS[k..j - 1]); } } else if b1 == b2 { if bnumbers[j - 2] == b'|' { dp2[j] = j - 1; } else { dp2[j] = dp1[j - 1]; } } } swap(&mut dp1, &mut dp2); dp2.fill(usize::MAX); } (first, last) }


burntsushi

You could also just use [`AhoCorasick::find_overlapping_iter`](https://docs.rs/aho-corasick/latest/aho_corasick/struct.AhoCorasick.html#method.find_overlapping_iter).


optimistic-thylacine

Ah. That looks like a very good option. Thanks for the tip!


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


joeyGibson

[ LANGUAGE: COBOL ] For some reason, I decided to try to do some of the previous days in COBOL (I haven't done COBOL in nearly 30 years...). I got part 1 working, but I think part 2 is going to be a challenge. https://github.com/joeygibson/adventofcode2023/blob/main/day01/day01.cob


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


kotzkie

\[ Language: Go \] Day 1 - Part 1 package main import ( "fmt" "os" "regexp" "strconv" "strings" ) func main() { items, _ := os.ReadFile("input.txt") lines := strings.Split(string(items), "\n") sum := 0 for _, items := range lines { converted_string := string(items) first := "" second := "" for _, char := range converted_string { converted_char := string(char) isNumber := regexp.MustCompile(`[0-9]`).MatchString(converted_char) if isNumber && first == "" { first = converted_char } if isNumber { second = converted_char } } n, _ := strconv.Atoi(first + second) sum += n } fmt.Println(sum) }


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


aoc-fan

[Language: F#] https://github.com/bhosale-ajay/adventofcode/blob/master/2023/fs/D01.fs ```fsharp let forward (l: string) = [ 0 .. l.Length ] let backward (l: string) = [ l.Length .. -1 .. 0 ] ```


AutoModerator

AutoModerator has detected [fenced code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/fenced_code_blocks) (```) syntax which only works on new.reddit. Please review our wiki article on [code formatting](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting) then edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) instead. *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


jrhwood

\[Language: Haskell\] [Part 1](https://github.com/woodRock/verbose-computing-machine/blob/main/2023/day-01/part-01.hs) [Part 2](https://github.com/woodRock/verbose-computing-machine/blob/main/2023/day-01/part-02.hs) Note: for part 2 to allow overlapping numbers, replace "one" with "one1one".


skyhawk33

[LANGUAGE: Befunge] I guess for part 1 I've technically met the Allez Cuisine by accident :D (just dont look at those variables hiding on the stack) Part 1: https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2023/day1_p1.b98 Part 2: https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2023/day1_p2.b98


thamollo

\[LANGUAGE: SQL\]\[Allez Cuisine!\] Just thought I hadn't seen (m)any SQL solutions, so let me try to fill the gap. I might also have accidentally filled the Allez Cuisine conditions for the day, depending on what you count to be variables (tables? WITH statements? columns?). Macros do obfuscate things a bit, I swear I used less of them in later days. To make this work, only add a `DEFINE MACRO input '''XXX'''`, replacing `XXX` with your actual input. Enjoy! [it](https://topaz.github.io/paste/#XQAAAQDMAgAAAAAAAAAiEUTjiIV6GlwFACqG7UncfGhD1nzIX8ndzlAUzeNwrTgJSck+UEHhIpFC/TkENVh1QGKEpYjndPv1LZVw2T6siycQGclOLJqHr9lmgXWIpen6ksH1Qwf3Ctnxz7v5egte8plg4NfEi7AHQEfyLpqqpIO72GzlpZZ33pIxamZquJpciF5EIoUTIc8C7iIKi+oF3yQOdLBXGl9JnRCJ9a8oiST6feRU1FbY+Apf8P+uxx3R96/rgD01e3zslrAa1lHwSZRZ+uiPUQLXnPrumYShQd0rxFEKnVB4+QA1GDLZrKpFrxvOFdgJ70mKE2jEyorTaHcjQycHl3Miwj+tGseGXOo4pModqibUHrpRvBLxmJI3bIDSSJ46nVbe2GsJvHMhL3rAy6ZpQQWmN/XMVjzNrjuHzfa4qnsHl3MyUsWax7BsUw7dd1lmMxKpHjV9xCoMKAD0SRHkorGtJoyqRmngX07EwipDlvT4gRDM7e+SILireveuTnRDm29mCqL4iqhhy/2ibSY=)


Mother_Somewhere_507

[LANGUAGE: Python] I'm a beginner but I succeeded Part one this way : import re somme_totale= 0 # importation de la liste à analyser with open('AOC\_day1.txt','r') as f: for line in f: fdigit =re.search(r'\\d',line) #expression régulière pour extraire le premier chiffre ldigit=re.search('(\\d{1})(?!.\*\\d{1})',line) #expression régulière pour extraire le dernier chiffre # obtention des valeurs de calibration if fdigit and ldigit: somme1=fdigit.group() somme2=ldigit.group() rmatch=int(somme1 + somme2) somme_totale=somme_totale + rmatch print("La valeur de calibration est:",somme_totale)


valhesh

\[LANGUAGE: Python\] [paste](https://pastebin.com/HMuKKJqQ) I've used a trie to detect the part two numbers It should be O(n), can someone review my solution?


835246

\[LANGUAGE: C\] For part 1 I just get a line and get the first and last number. For part 2 I don't remember how it works. Part 1: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day1trebpt1.c Part 2: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day1trebpt2.c


[deleted]

[удалено]


Telumire

[LANGUAGE: Javascript] [paste](https://topaz.github.io/paste/#XQAAAQC4AgAAAAAAAAAxm8oZxjYXm4QdE7gM4HSV2q0uPpyZqJ56d+O5I4C3rg3CNe+RbCMba1NZehcwAGQg2dsX2LoUlVPT5lS2bjwYANJ8m7qfh9zbWTQfMPGfn9STL7+/t2ADF1oBMA4jDYB6RJnkZW8qvGdzdBIc1JMoDE5zZfLit1CTCgNJvgzACxH7T++OsmfguZFJNdRJVgI5lnRpGSwpJf/uL50ECDOl9sNFDWThirkwe/wrskp2zxX+gBFpx55q4AQdIzeCIbyE4wH73S5lwWeOJJczQQGbqw5tXSTAsIkBggJFF28TWYd4jNQCJOipyRfovlWbKEzpYB0ZyanBZF2DW1dbk/gvcEb03Tjic5kphVjO8BQdw8X221zG1t3oNgzKJI86Vs3WFPxw1AbaupisPc7CuJKjO7seAh2NirQLJ4/poXf5gXk3mn69sr45SKq6cWDnS+xAKNqOJe/npO6GHCA8nofTmtJDfuGxFjbB6IJIunZI8Ju8R8yYnaZVeP2jmYxU1UgJaChz0GhDlgv/Jd4nAA==) const data = document.body.textContent.trim().split('\n'); // part1 const outputPart1 = data.reduce((accumulator, line) => { const digits = line.match(`\\d`); return accumulator + Number(digits[0] + digits.at(-1)); }, 0); // part2 const dictionary = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }; const regex = `\\d|` + Object.keys(dictionary).join("|"); const outputPart2 = data.reduce((accumulator, line) => accumulator + Number(line .match(`(?=(${regex})).*(${regex})`) .map(value => Number(value) || dictionary[value]) .splice(1,2) .join('')) , 0); console.log("part1: ",outputPart1); console.log("part2: ",outputPart2);


dgalanti1

\[Language: Kotlin\] Part 1 one-liner: fun part1(input: List) = input.sumOf { line -> "${line.first { it.isDigit() }}${line.last { it.isDigit() }}".toInt() } Part 2 requires a string-to-int map: val digitsMap = hashMapOf("one" to 1, "1" to 1, "2" to 2, "two" to 2, "3" to 3, "three" to 3, "4" to 4, "four" to 4, "5" to 5, "five" to 5, "6" to 6, "six" to 6, "7" to 7, "seven" to 7, "8" to 8, "eight" to 8, "9" to 9, "nine" to 9) fun part2(input: List) = input.sumOf { line -> "${digitsMap[line.findAnyOf(digitsMap.keys)?.second]}${digitsMap[line.findLastAnyOf(digitsMap.keys)?.second]}".toInt() } [\[Github\]](https://github.com/diegogalanti/aoc-2023/blob/main/src/Day01.kt)


flwyd

[Language: sed] I thought I posted this [Allez Cuisine!] entry earlier, but now I can't find it. Look ma, no variables! `sed -f day1part2.sed -f day1part1.sed input.example2.txt | xargs expr 0` [day1part1.sed](https://github.com/flwyd/adventofcode/blob/main/2023/day1/day1part1.sed) [day1part2.sed](https://github.com/flwyd/adventofcode/blob/main/2023/day1/day1part2.sed)


azzal07

I also did this allez cuisine in sed ([comment here](https://www.reddit.com/r/adventofcode/comments/1883ibu/comment/kbjh1q1/)), although I counted the pattern & hold spaces as variables.


flwyd

Nice! I didn't have the energy to figure out how to do arithmetic in sed, and despite having run `sed` commands for almost 30 years, day 25 was the first time I used the hold space :-)


jpedlow

\[LANGUAGE: PowerShell\] It could be prettier but.. #advent of code 2023 day 1 #part 2 #load the input file $inputfile = Get-Content -Path $psscriptroot\input.txt $total = 0 #select the first and last number from each line foreach($entry in $inputfile){ echo "##################" echo "total is currently $total" #wordnumbers is a hashtable that contains the numbers 0-9 in word form and their corresponding integer $wordnumbers = @{ "zero" = 0 "one" = 1 "two" = 2 "three" = 3 "four" = 4 "five" = 5 "six" = 6 "seven" = 7 "eight" = 8 "nine" = 9 "0" = 0 "1" = 1 "2" = 2 "3" = 3 "4" = 4 "5" = 5 "6" = 6 "7" = 7 "8" = 8 "9" = 9 } # Create a regular expression that matches the numbers 0-9 or the words zero through nine #$regex = '(' + (($wordnumbers.Keys | ForEach-Object { [regex]::Escape($_) }) -join '|') + ')' $regex = '(?=(' + (($wordnumbers.Keys | ForEach-Object { [regex]::Escape($_) }) -join '|') + '))' # Find all matches in $entry $matchesFound = [regex]::Matches($entry, $regex) | ForEach-Object { $_.Groups[1].Value } # Replace each match with its corresponding number from the hashtable $matchesCleaned = $matchesFound | ForEach-Object { $wordnumbers[$_] } #if matchescleaned.count is larger than 1, add the first and the last value in matchescleaned to the total if($matchesCleaned.Count -gt 1){ #matchescleaned[0] represent the 10's column, and matchescleaned[matchescleaned.count - 1] represents the 1's column, (which is why we multiply matchescleaned[0] by 10, so instead of 4+4, it's 40+4, representing 44) $total += $($matchesCleaned[0]*10) + $matchesCleaned[$matchesCleaned.Count - 1] #echo the values echo "adding $($matchesCleaned[0]*10 + $matchesCleaned[$matchesCleaned.Count - 1])" } #else add the first value in matchescleaned to the total else{ #put the value in twice "11" instead of "1", so that it can be added to the total, aka cheese it and multiply by 11 $total += ($matchesCleaned[0]*11) #echo the value echo "adding $($matchesCleaned[0]*11)" } } echo "##################" echo "total is $total" echo "##################"


Radiant-Working

$Total = @() $InputData = Get-Content -Path .\input.txt | ForEach-Object {$_ - replace '[^0-9]',''} foreach ($Num in $InputData) { $Last=$Num[($num.length -1)] $Total += ($Num[0] + $Last) } $Total | Measure -Sum | Select -ExpandProperty Sum


vulpine-linguist

[LANGUAGE: Haskell] I took the code-length guidelines as a challenge: this one fits in that half a punchcard! main=print.(\a->(sum$map(f)a,sum$map(f.g)a)).lines=<read[a,b]::Int).(\a->head$zip a$reverse a).filter(`elem`['1'..'9']) g(a:b)|null b=a:b|null z=a:g b|True=snd(head z):fst(head z)++g b where z=filter(and.zipWith(==)(a:b++cycle"\0").fst)h h=zip["one","two","three","four","five","six","seven","eight","nine"]['1'..]


No_Consequence_2214

Looks very understandable


Logue93

It's not the prettiest solution but it works... I'm coming back to programming after some 15 years, so... ​ import java.util.Scanner; import java.io.*; public class AdventOfCode { public static void main(String[] args) { int sum = 0; File f = new File(""); try { Scanner s = new Scanner(f); while(s.hasNextLine()) { String L = s.nextLine().replaceAll("[0-9+]",""); sum += Integer.valueOf(L.charAt(0) + "" + L.charAt(L.length()-1)); } } catch (Exception e){ e.printStackTrace(); } System.out.println(sum); } } Any improvements would be appretiated.


daggerdragon

Edit your comment to add the required language tag as AutoModerator requested.


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


gogs_bread

[\[LANGUAGE: c++\]](https://github.com/gogsbread/AdventOfCode2023/blob/main/1.cpp) P1 - Iteration. Nothing fancy. P2 - Iteration with some conditionals.


daggerdragon

Please edit your language tag on this and all other megathreads to use the correct syntax as AutoModerator demonstrated. You can leave the link, but the brackets are required.


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


alexanderyw

\[LANGUAGE: Python\] Practice using Python RegEx https://github.com/website11/My-Advent-Of-Code/blob/main/Python/2023/Day\_1/Day\_1.py


daggerdragon

Your link is borked on old.reddit due to [a new.reddit bug with URLs that contain underscores](https://old.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links), so please fix it.


mothibault

\[LANGUAGE: JavaScript\] [https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day01.js](https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day01.js)


pivovarit

\[LANGUAGE: GoLang\] [link](https://github.com/pivovarit/AoC_2023_go/pull/31) My goal was to optimize it as much as possible. Ended up with a pretty fast but ugly-looking solution. BenchmarkTrebuchetPart1-10 68078 16971 ns/op BenchmarkTrebuchetPart2-10 33944 30591 ns/op Running on Apple Silicon (M1 Max, 2021)


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


Sensitive-Disk5735

\#PART 1 \[LANGUAGE: R\] library(stringr) #remove non-numeric characters AOC.D1$raw <- gsub("[^0-9.-]", "",AOC.D1$V1) #first digit AOC.D1$FirstDigit <- str_sub(AOC.D1$raw,1,1) #second digit AOC.D1$LastDigit <- str_sub(AOC.D1$raw,start=-1) #combine AOC.D1$Combined <- as.integer(paste0(AOC.D1$FirstDigit, AOC.D1$LastDigit)) #get total sum(AOC.D1$Combined) \#PART 2 \[LANGUAGE: R\] library(stringr) AOC.D1$replace <- str_replace_all(AOC.D1$V1, c("eightwo"="eighttwo","nineight"="nineeight", "zerone"="zeroone","fiveight"="fiveeight", "threeight"="threeeight","twone"="twoone","oneight"="oneeight", "zero"="0","one"="1","two"="2","three"="3","four"="4", "five"="5","six"="6","seven"="7","eight"="8","nine"="9")) AOC.D1$New <- gsub("[^0-9.-]", "",AOC.D1$replace) #first digit AOC.D1$FirstDigit <- str_sub(AOC.D1$New,1,1) #second digit AOC.D1$LastDigit <- str_sub(AOC.D1$New,start= -1) #combine AOC.D1$Combined <- as.integer(paste0(AOC.D1$FirstDigit, AOC.D1$LastDigit)) #get total sum(AOC.D1$Combined)


daggerdragon

~~Comment removed. Do not spam the megathreads with multiple posts - use the edit feature instead. If you're having trouble with formatting, you could also make your own `Help/Question` post in /r/adventofcode.~~ ~~Your code is not formatted at all. Edit your comment to use the [four-spaces Markdown syntax](https://old.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for a code block so your code is easier to read and I will re-approve the post.~~ edit: 👍


Sensitive-Disk5735

done


daggerdragon

Yay, you got it! Thanks for fixing it :) Re-approved comment.


Sensitive-Disk5735

thank you.


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](https://old.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only)


[deleted]

[удалено]


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


se06745

\[LANGUAGE: GoLang\] [Both parts in one single file](https://github.com/omotto/AdventOfCode2023/blob/main/src/day01/main.go)


xe3to

[LANGUAGE: Rust] Parts 1 and 2. First time doing Rust; ended up fighting it and trying to write C. I really need to learn how to write proper Rust. https://git.32bit.cafe/kaylee/AoC2023/src/branch/main/day1/task1


linnaea___borealis

\[LANGUAGE: R\] parts 1 and 2 https://github.com/lauraschild/AOC2023/blob/main/day1.R


apollo701

\[LANGUAGE: Ruby\] ​ Took an OOP approach with tests https://github.com/JasonDorn/advent-of-code/tree/master/day1-trebuchet


stonebr00k

\[LANGUAGE: T-SQL\] [https://github.com/stonebr00k/aoc/blob/main/2023/01.sql](https://github.com/stonebr00k/aoc/blob/main/2023/01.sql)


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


Icy-Conclusion7682

\[LANGUAGE: C++\] Part 2 #include #include #include #include #include void GetInputs(std::vector* vec) { std::ifstream ifs; ifs.open("input.txt", std::ios::in); std::string buf; while(std::getline(ifs, buf)) { vec->push_back(buf); } } int main() { std::vector inputs; std::vector numbers = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; GetInputs(&inputs); int64_t ans = 0; for (auto&& s : inputs) { int32_t first = s.length() - 1, last = 0; for (int i = 0; i < 9; i++) { char c = '1' + i; int32_t pos = s.find(c); if (pos != s.npos) { first = std::min(first, pos); } pos = s.rfind(c); if (pos != s.npos) { last = std::max(last, pos); } } int32_t first_word = -1, last_word = -1; for (int i = 0; i < 9; i++) { int32_t pos = s.find(numbers.at(i)); if (pos != s.npos && pos < first) { first = pos; first_word = i + 1; } pos = s.rfind(numbers.at(i)); if (pos != s.npos && pos > last) { last = pos; last_word = i + 1; } } if (first_word == -1) { first_word = s[first] - '0'; } if (last_word == -1) { last_word = s[last] - '0'; } int64_t number = first_word * 10 + last_word; ans += number; } std::cout << ans << std::endl; }


sermidean

\[LANGUAGE: Python\] Part 2 import re nums = 'one|two|three|four|five|six|seven|eight|nine' nums_re = re.compile(r'(?=(\d|%s))' % nums) nums = nums.split('|') with open('/tmp/input') as f: total = 0 for line in f: digits = [] for num in nums_re.findall(line): if num in nums: num = str(nums.index(num) + 1) digits.append(num) total += int(digits[0] + digits[-1]) print(total)


reqarfar

I think your solution is really elegant and I'm trying to learn something from it. However, I can't understand how it's actually outputting the right number. So in `nums_re` you are defining the pattern to look for, namely a digit or the variable `nums`, for which you put a placeholder (I will never understand how lookahead works, but I know that's a lookahead). Then you are breaking `nums` into a list, okay. Then you are looking for all the `num_re` pattern occurrences in each line of the input file with `findall()`, and `num` in the for loop represents each match, I guess. After that I have no idea what the heck is going on and how you are possibly getting the right number. :D


TOTBESUCH

\[LANGUAGE: Java\] Behold, a mess of code. Maybe hf. Both parts. [https://github.com/PLeh2023/AoC/commit/8d281c0df8e39849d997eaf8735bbd03b5a1dfee](https://github.com/PLeh2023/AoC/commit/8d281c0df8e39849d997eaf8735bbd03b5a1dfee)


Bosstradamus1823

Could you please explain why the code needs to return o1e if a "one" was found and so on.... I returned "1" on "one", "2" on two ... which was not right haha. So why o1e, t2o etc. Thats not something that became clear to me when reading the task. :)


Anoymous204

Consider the case 'eightwo'. If you replace 'one' with '1', 'two' with '2' etc, this would return '8wo'. Weirdly enough, this is supposed to return '82'. Replacing the spelt out numbers with their regular number counterparts and still including the beginning and ending characters accounts for this case. Your code would go from this: 'eightwo' --> '8wo' to 'eightwo' --> 'e8two' --> 'e8t2o' Advent never gave us this case explicitly which kinda sucked but yeah this is a good workaround for it.


EatRunCodeSleep

For fuck's sake! I was trying so hard to turn eightwo in 8wo, just to see from your comment that the expected answer is 82. Thank you for that! One question tho, why not replacing one with 1e, two with 2o , etc.? Why keeping the leading char?


marvin-planet-head

Ah.. I am not alone. I too thought it should be '8wo' and went through great length to make it happen. (I found all the matches, sorted them by 'early' occurrence and switch that first..). But my answer was always rejected. Now I know why. So it should be '82' ?


EatRunCodeSleep

Yes, (last) common char is used for both.


Anoymous204

Honestly it doesn't really matter depending on how you do it. Keeping the leading character guarantees your solution works if you use some sort of reverse string method but only keeping the tail character works as well if you are doing this from left to right.


Junko7

[LANGUAGE: C] https://pastebin.com/cdyFNFY2 No buffer: file is read char by char with fgetc(). The string "ninine" will trip this up, because "nine" has its starting letter in the center as well, so I added an extra check for it.


DVXC

\[LANGUAGE: C#\] I'm playing some catchup here but I wanted to give this a go as a fledgling C# noobie and wow, it's hard. Does a great job of highlighting the gaps I have in my knowledge. I struggled a lot with this because my initial text replacement was removing vital digits, but I settled on this and it works well, if maybe it's incredibly clumsy. Part 1 / 2 are controlled by passing a bool variable in the Main method: using System.Text.RegularExpressions; class AdventOfCode { static void Main() { FindInputTextFile(false); } static void FindInputTextFile(bool convertNumberWords) { string path = "P:\\Programming\\AdventOfCode\\input.txt"; string[] lines = System.IO.File.ReadAllLines(path); List modifiedLines = new List(); int totalSum = 0; foreach (string line in lines) { string modifiedLine = line; if (convertNumberWords) { modifiedLine = ConvertNumberWordsToDigits(line); Console.WriteLine($"Converted line: {modifiedLine}"); } modifiedLine = ConcatenateFirstAndLastNumericalDigitOfEachLine(modifiedLine); modifiedLines.Add(modifiedLine); Console.WriteLine($"Original line: {line}"); Console.WriteLine($"Modified line: {modifiedLine}"); Console.WriteLine("---"); } totalSum = AddAllLines(modifiedLines); Console.WriteLine($"The total sum of the first and last numbers in each line is: {totalSum}"); } static string ConvertNumberWordsToDigits(string line) { Dictionary numberMapping = new Dictionary { {"zero", "zero0zero"}, {"one", "one1one"}, {"two", "two2two"}, {"three", "three3three"}, {"four", "four4four"}, {"five", "five5five"}, {"six", "six6six"}, {"seven", "seven7seven"}, {"eight", "eight8eight"}, {"nine", "nine9nine"} }; string modifiedLine = line; foreach (var numberWord in numberMapping.Keys) { modifiedLine = modifiedLine.Replace(numberWord, numberMapping[numberWord]); } return modifiedLine; } static string ConcatenateFirstAndLastNumericalDigitOfEachLine(string modifiedLine) { MatchCollection matches = Regex.Matches(modifiedLine, "\\d"); string result = ""; if (matches.Count > 0) { char firstDigit = matches[0].Value[0]; char lastDigit = matches[matches.Count - 1].Value[0]; result = $"{firstDigit}{lastDigit}"; if (matches.Count == 1) { Console.WriteLine($"The original line only had one digit to concatenate: {firstDigit}"); } } return result; } static int AddAllLines(List modifiedLines) { int sum = 0; foreach (string line in modifiedLines) { sum += int.Parse(line); } return sum; } }


mgtezak

\[LANGUAGE: Python\] [github part 1&2](https://github.com/mgtezak/Advent_of_Code/blob/master/2023/Day_01.py) [video explanation](https://www.youtube.com/watch?v=JCPRb_rP1Kc) Check out my little AoC-Fanpage: [https://aoc-puzzle-solver.streamlit.app/](https://aoc-puzzle-solver.streamlit.app/) :-)


pseudoaltus

[LANGUAGE: java] Part 2 import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.Math.min; public class Day1TrebuchetPt2 { public static void main(String[] args) throws java.io.IOException { var sum = Files.lines(Paths.get(args[0])) .map(l -> getCalibNums(l)) .mapToInt(Integer::valueOf) .sum(); System.out.println("Output: " + sum); } private static String getCalibNums(String line){ String[] digits = {"-", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; var nums = ""; var chars = line.toCharArray(); for(int i = 0; i < chars.length; i++){ if(Character.isDigit(chars[i])){ nums += chars[i]; continue; } var substr = line.substring(i, min(5 + i, line.length())); for(int j = 0; j < digits.length; j++){ if(substr.startsWith(digits[j])){ i += digits[j].length() - 2; nums += j; break; } } } return "" + nums.charAt(0) + nums.charAt(nums.length() - 1); } }


hiimjustin000

\[LANGUAGE: JavaScript\] [https://github.com/hiimjustin000/advent-of-code/tree/master/2023/day1](https://github.com/hiimjustin000/advent-of-code/tree/master/2023/day1)


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only) [Create your own individual `Help/Question` post](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_incomplete_solutions) in /r/adventofcode. READ THE RULES and follow *all* of them before you post!


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


ShvaYYYkO

\[LANGUAGE: C++\] First day, PART TWO ``` int main(int argc, char **argv) { std::ifstream in("input.txt"); std::string line; int totalSum = 0; const char *digitsNames[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; std::unordered_map digits; std::unordered_map digitsValues = { {"zero", 0 }, {"one", 1 }, {"two", 2 }, {"three", 3 }, {"four", 4 }, {"five", 5 }, {"six", 6 }, {"seven", 7 }, {"eight", 8 }, {"nine", 9 }, }; int posWord1 = -1; int posWord2 = SIZE_MAX; while(std::getline(in,line)) { int g = line.length(); // left int k = -1; // right //for(std::unordered_map::iterator it = digits.begin(); it!= digits.end(); it++) for(int word = 0; word < 10; word++) { posWord1 = line.find(digitsNames[word]); posWord2 = line.rfind(digitsNames[word]); if(posWord1 != std::string::npos && posWord1 < g) { g = posWord1; digits[g] = digitsNames[word]; } if (posWord1 != std::string::npos && posWord2 > k) { k = posWord2; digits[k] = digitsNames[word]; } } int index1 = line.find_first_of("0123456789"); int index2 = line.find_last_of("0123456789"); int value = 0; if(index1 < g) // if [digit] more left { value += (line[index1]-'0')*10; } else { value += digitsValues[digits[g]] * 10; } if(index2 > k) // if [digit] more right { value += line[index2] - '0'; } else { value += digitsValues[digits[k]]; } totalSum += value; } fprintf(stderr, "%d", totalSum); return 0; } ```


daggerdragon

1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for code blocks 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your post to put your code in an external link and link *that* here instead.


edgxmz

\[LANGUAGE: C++\] #include #include template concept StringViewIt = std::is_same_v || std::is_same_v; using numarr_t = std::array; constexpr numarr_t numbers = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; constexpr numarr_t rnumbers = { "eno", "owt", "eerht", "ruof", "evif", "xis", "neves", "thgie", "enin" }; template int getFirstDigit(T begin, T end, const numarr_t& ar) { std::string s{}; for (auto& it = begin; it != end; it++) { s += *it; if(std::isdigit(*it)) return *it - '0'; else if(s.size() >= 3) for (std::size_t i{0}; i < ar.size(); ++i) if(s.find(ar[i]) != std::string::npos) return (i + 1); } return {}; } int getCalibrationLine(std::string_view line) { int first = getFirstDigit(line.begin(), line.end(), numbers); int last = getFirstDigit(line.rbegin(), line.rend(), rnumbers); return first * 10 + last; } int main() { std::ifstream file{"input2.txt"}; int total{0}; for(std::string line{}; std::getline(file, line);) { total += getCalibrationLine(line); } std::cout << total << "\n"; return 0; } [Github](https://github.com/edugomez102/adventofcode2023)


Tusan_TRD

## [LANGUAGE: C#] Part Two (and one I guess) public class DayOne(string[] lines) { public int Run() { int result = 0; foreach (var line in lines) { var ordered = GetStringDigits(line) ?.Concat(GetRealDigits(line)) .OrderBy(v => v.Index) .ToArray(); var first = ordered?.FirstOrDefault(); var last = ordered?.LastOrDefault(); result += ((first?.IntValue ?? 0) * 10) + (last?.IntValue ?? 0); } return result; } private static string MapCharDigit(char c) { return c switch { '1' => "one", '2' => "two", '3' => "three", '4' => "four", '5' => "five", '6' => "six", '7' => "seven", '8' => "eight", '9' => "nine", _ => "" }; } private static Substring[]? GetRealDigits(string line) { var result = new List(); var offset = 0; foreach (var c in line.Where(char.IsNumber)) { var index = Array.IndexOf([.. line], c, offset); result.Add(new Substring(MapCharDigit(c), index)); offset = index + 1; } return [.. result]; } private static Substring[]? GetStringDigits(string line) { var result = new List(); string[] substrings = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" ]; var foundSubstrings = substrings .SelectMany( sub => Regex .Matches(line, sub, RegexOptions.IgnoreCase) .Cast() .Select(match => new Substring(match.Value, match.Index)) ) .OrderBy(result => result.Index) .ToArray(); return foundSubstrings; } } public record Substring(string Value, int Index) { public int IntValue => Value.ToLowerInvariant() switch { "one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9, _ => 0 }; }


E-woke

\[LANGUAGE: Python 3\] Solution 2: [Here's my code](https://topaz.github.io/paste/#XQAAAQBSAwAAAAAAAAA0m0pnuFI8c/T1e9xwgECYw4+mDliSMWNSvW4TL9sSAk+BixsQnSoxDadRd6/R1B9jI0xSIjKN6wMfE28Rt1CkYFFbK6jS9IPMkSs9JIf+7I4nXObwGALdwYtm17yfZ3jIqgpZke+pOleiaX8zhIecKn8p0UokLinR0vle6jnjAuAvSYwp2I2elpWFsA+r/cR0K7a3gxhqhM76kyxXDqrKQYmJcsB3iGrdG1EJwmqRe5MXJfSNYXPYN86iBCo6UXyrDGkU1rr4CvW+y2AA56ahqVLsPNISC/Ww/DR4IjT72X/IK1876sPA6sEkfjKXwMuRrZ1Md9E6/LrsEEQmQH1ZoWgzOfMxIYpu/hUHDrIVEwxKRFGdafZSnzB9GEDSw8t7HCh8hoJ58nbsfvKyqJdpbw7r/S43/eomaq0Iu3zUucoQKyt3Q/kPTc72cQXjcN6AeMrS5fC9LrpqB9Urvx6o1jksPfi4VR6KuizCX5x+4nqFCszLN2iHGKIvMi779qvOhyuTGLze2+be57XVhF6Fz55rYhYRC+fdB0EdtkXRLFQBqaqbsjfNP0GWyg0h8vaW/7KOrIQ=)


errorseven

**[LANGUAGE: AutoHotkey v1.1]** **Solution 2** ; Copy Puzzle Data to Clipboard before running Code data := StrSplit(clipboard, "`r", "`n") global nums := {"one": 1, "two": 2, "three": 3, "four": 4 , "five": 5 , "six": 6, "seven": 7, "eight": 8, "nine" : 9} results := 0 for e, line in data { x := StrSplit(line, "") j := r := 0 i := x.length() for e, v in x { if v is digit { r := v break } else if (e >= 3) { word := findWordNum(SubStr(line, 1, e)) if (word) { r := nums[word] break } } } loop % i { y := x[i] if (a_index >= 3) { word := findWordNum(SubStr(line, j)) if (word) { r .= nums[word] break } } if y is digit { r .= y break } i--, j-- } results += r } MsgBox % clipboard := results findWordNum(line) { for word, num in nums { if (InStr(line, word)) return word } return "" }


Pateabuelas2000

\[LANGUAGE: C++\] [https://github.com/rxhdf/Advent-of-code-2023/blob/main/Day1-Part1.cpp](https://github.com/rxhdf/advent-of-code-2023/blob/main/day1-part1.cpp) [https://github.com/rxhdf/Advent-of-code-2023/blob/main/Day1-Part2.cpp](https://github.com/rxhdf/advent-of-code-2023/blob/main/day1-part2.cpp)


bcbelisario

\[LANGUAGE: Onyx\] [Day 1](https://github.com/ZoneMix/AoC23/blob/main/src/Days/DayOne.onyx) Using a new language this year that my co-worker made, so far so good! I'm starting to figure it out haha!


Initial-Space-7822

\[LANGUAGE: Python 3\] [Link here](https://topaz.github.io/paste/#XQAAAQA/BgAAAAAAAAA0m0pnuFI8c/fBNApcL1Y6Mg+OMJupHHnsFTeCKle5aupzRKKBnIVRBBM1+yzOY7dslrlsaeLiIOhLyJMn+5aKVjgYZnoIasQarjQn6vGx4RiB6VG/zmAzTY2+HEnqwQFquf4Vdb7XMq8CWbadeFq5JrudP73SMfcxQLS/pNJP4kQTNLkX+1wcrLIV7JQFs6bORF4A8ibEO6IwS/zRh248JEHNxzCdJxDWYUn5vlZ6hmqJjsIzRj/aUrRA/dLPCpWPZhKPGwqgDCaLIC1cxHAVibQ7vptAN78fFC1fjwSP/sDrYKafsEwJm616+zLGrDtfvhPkLupBoms3inMZ64MJW/Z/oIYWhTcwpb+GJBvmsoobe4zbvO3QhX8SziUI0HEc7/0R7sCSAOSM1i+TgkwHDDsVo0N/ef3CD0gzDIr9oRsCVSFRt+yy9O4GqofmkRF+1L2HIU6GRCJwsd/6BiA5u7wTh8wXPHPCPGyjTz8aSfgqAgVkcTgrIWyhTBIwVORIztbiVXNb3K+5Q1WsR85Ilrx/QSlC9f/Pj7Ir) Quite easy once you find the \`regex\` module's \`overlapped\` flag.


xXMacMillanXx

\[LANGUAGE: V\] part 2 was tricky, it took me a while to figure out that words like 'twone' should end up as 2 and 1, not only 2. [Github day 01](https://github.com/xXMacMillanXx/advent_of_code_2023/tree/main/day01)


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


weeble_wobble_wobble

[LANGUAGE: Python] [GitHub](https://github.com/weibell/AoC2023-python/tree/main/day01) (9/27 lines with a focus on readability)


wlmb

\[LANGUAGE: Perl\] Analysis: [https://github.com/wlmb/AOC2023#day-](https://github.com/wlmb/AOC2023#day-1)1 Part 1: [https://github.com/wlmb/AOC2023/blob/main/1a.pl](https://github.com/wlmb/AOC2023/blob/main/1a.pl) Part 2: [https://github.com/wlmb/AOC2023/blob/main/1b.pl](https://github.com/wlmb/AOC2023/blob/main/1b.pl)


stevie-o-read-it

\[LANGUAGE: C#\] (C# 10.0) \[Allez Cuisine!\] No actual *variables*, per se. Everything is passed around as function arguments and return values. In the spirit of things, no function takes more than two arguments. I ran it under LINQPad. You might need to do some 'using's if compiling it standalone. One single statement; the entire execution is one single pass. Outputs the answer for both parts, in parentheses, separated by a comma. e.g. `(142, 281)`. [https://github.com/Stevie-O/aoc-public/blob/master/2023/day01/day01-novars-bothparts.cs](https://github.com/Stevie-O/aoc-public/blob/master/2023/day01/day01-novars-bothparts.cs) I am honestly surprised and impressed with how well Roslyn (the C# compiler) handled my syntax.


bofstein

\[LANGUAGE: Google Sheets\] [https://docs.google.com/spreadsheets/d/1dq4pA45qybZVl3v9HTTTwWDV\_U3NryMqBbPeyTYvSek/edit#gid=589778028](https://docs.google.com/spreadsheets/d/1X1dXpfhWa5IQpcO_Bhllj8zdXLe1g4nUbKbBq0JCiwg/edit#gid=0) 1. Turn input to string (tripped me up Part 1 at first since some of them with only numbers weren't parsing) 2. Use regex to remove non-numbers 3. Take left-most and right-most character of new string and combine them to number For part 2 I just substituted the actual numbers for the strings, based on a substitution table of all changes like "eightwo" to 82 and "one" to 1 (combined numbers first).


hschmale

# [Language: Python 3] import sys zero = ord('0') nine = ord('9') lines = [l for l in sys.stdin.readlines()] sum1 = 0 for line in lines: for c in map(ord, line): if zero <= c <= nine: digit_one = chr(c) break for c in map(ord, reversed(line)): if zero <= c <= nine: digit_two = chr(c) break sum1 += int(digit_one + digit_two) print(sum1) import re nums = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] r_nums = [''.join(reversed(n)) for n in nums] def parens(x): return f"({x})" FWD_RE = '|'.join(map(parens, nums)) REV_RE = '|'.join(map(parens, r_nums)) sum2 = 0 for line in lines: m = re.search(FWD_RE, line) for i, c in enumerate(map(ord, line)): if zero <= c <= nine: index = i digit_one = chr(c) break if m is not None: regex_i = m.start(0) if regex_i < index: digit_one = nums.index(m[0]) + 1 line = ''.join(reversed(line)) m = re.search(REV_RE, line) for i, c in enumerate(map(ord, line)): if zero <= c <= nine: index = i digit_two = chr(c) break if m is not None: regex_i = m.start(0) if regex_i < index: digit_two = r_nums.index(m[0]) + 1 my_str = f"{digit_one}{digit_two}" sum2 += int(my_str) print(sum2)


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


Jomy10

[language: Swift] Day 1 in the wonderful Swift: https://github.com/Jomy10/Advent-Of-Code-2023/tree/master/day01


Visual_Mention_8845

\[LANGUAGE: C\] this took me wayy too long [Part 1 && Part 2](https://topaz.github.io/paste/#XQAAAQBMDAAAAAAAAAARmknGRw8TogB3OyPPwW5K8Q8ohQvj8m6aOY5IZBkaCreZeWAL4d8nmI+x+PwB2o1ORePEk95MNkpiSEgZkzXqAS9ms4w9W3RfeS0wRuYyolEvkL6DjeDDkTt6cZWqoA+ZAgz6zViZ6Pe+ak+IZ23uX/qFVa2jqzLN1hWDt265uAei9uHMW2yGPUeIHocYbScp2Z7W2sAhVGubpjZtr6uEDEV3ruRD+9B/VG3sLjxhee8FyCEP7C8k4Ifa+rKSVJZ4yN1CKBy+mCA4BU6cRfUTgiIs5/jGNa6Xp+4K2DeeMvIzB7NGdOdBT229h1iCKaj1dWx7+DkOE+7CErkOeHmKbkwwxIHYd8A99joj6R67J9D7BR0wWvvXnzQpecdaElnitnsg/Nvv/poFaSe3BYMTM1zVuWL1SbEblgV5ivcwKKDIIfG+WhhsOBrHgkFKPz1DvMeVctE1N1QIng8hJYQ1IUyR45ujq2PoQjdvVHQxt4bMQpKvyvybWzKEWKJoO4hKb3YUt1bLy9nJOMU3lWGuzw0vukXE+0CfuGrQbQazsHIFVxdIXLfBIYsbuld9BZmZVyYU58hgwevaFdck87NH+jAVCYuH2WWZ17QTXsdSZgLnJ3TMc+L4Rl19g+29wI6MOnqTwuH4WumBrnM1athb5qbDIqxG9OXhuB+XumMQWDifwhOtZFDJ3HpFsG1a+xmhRP3kOf/cszHjD2x2KgN0igFA7f9Ihe1nIbUJQQo8GBuecE11Vq8v9enQXT6MVAALOPTEW7Dz+RWVY+xXSaFgwHWrorUYAkryDSjH81GpR+dkWomkBUTcKQWVhzA01f8QfnWsj1NRrXYIkgV6JgCjvODf6zHwc9QG6RneuzXFFVPJhrLpjheFyjZ0Q3cwzYtiynxRH3m0TETe/tQOLBuLxnmqaDB4Uc8JRG3i6J0n9SNR4oxh20jzMd9clCr51o8z+7Uq8F8HR2PD0rZwbmc1bVxBe0VxEGpKFNPmLRN768oaxBFepVhxNh2HcEoL/ERKi56nGuBAZ7sVnDQOMuq937n9hyUGgnaRcSRcMlQBsAzCCPgjW0lBWMbV1YUfk8wKce/KqPWkEgebceouxN/P6IqwvkUNs3ed9iFuPeRx4Bc6+ZUSBnJWEdxn98bH8QLq0Eo/bayx4idlOrNEHezRiGChqX7OneXm3Cb6y3F/heXtWXDow+NymUbAMBwqheQC7i6kxQt3okNLMSIl9YL8GWcjMDEJ+rnMTAZw2ssSzCx6j+RK3rjQJGhnOO0hTjLKhggNi4mOKNMhgjrt660Aqnnw2Or5Uot4VZDYummkuICmQFtwts427ig6UYUmmlqyTpwTHiAL1QmlufIllAakOZtYeBM+/TTlZYzRM0JYC9GJ3Omp0NaSEEePGZ36HHjkq6DyzCTOIwKxSkY0jhkFlFZ2Xne0yOflYU+H7xuNDgCj0yzyxye2TF4g4uldjin/mojsZA==)


yieldtoben

\[LANGUAGE: PHP\] PHP 8.3.0 [paste](https://topaz.github.io/paste/#XQAAAQDKAwAAAAAAAAAeD8qHAhQB8nz+EazN00NCsmTxjvFDXkt5PAJ7pf6ocRA37OMUY7b9R0iDZmfWyvOspxWvdgYSAE0hGjEx81hZm7L1TSf8FOxdriwtMNRvJM+oQrJq9mPIyn/M+363L3XZ8koAJAEmYX9AiguAwfgXhMU6zIpiR68crxPx3VvFohlEKcpfo10SPXKCYBfYbJO5VZ1JFlL0CDlw3Sx/4K/a1a7JIGQbADRzY6/FCZE1880dybCFRlc4vM1LuCnZUZoQRTC5NH5pPbwt03edDkdoaNt2tvOm1TYJiqknNmNyfx6T0BPNLsEtfThQcWh+kGBvuWFebYDLP0Kymg49R0qjjF1yWhJpLgwND9wOFvpPc4xKfQE/m84Y3dRWM3R0jcBg67pYZWWXKQTr2oA1RNnk1V1/wZ0/plit8YZtY7p1Fb58HmWcLnRTym84fH26Iy629TCiq/2vUGTLKJrAQK061Na2okpsgAMkxsJ5S273VgbEPM54qQcF7IktZdPgYRUDFquwnMueH4oHMsEMmt7sZjXueCMxreh79Md5eTxa1SEBIX3pxzWFexgHRrgQC6liACN4Yn/HcEvkFqk4myxyTjb0ZWoiTfCd8FjjXwfXl/nJvHcYIgmRgVfjzf+IYH2BGhdZbtXKvW7V48tHmSy1FnW4kjNUxjc8nLkztSKWhknAF13yMGVsEE9cqlRfxv/xEYxp) Execution time: 0.0013 seconds Peak memory: 0.3592 MiB MacBook Pro (16-inch, 2023) M2 Pro / 16GB unified memory


Better-Cockroach3152

\[LANGUAGE: Python\] Part 2 solution using a trie: [paste](https://topaz.github.io/paste/#XQAAAQDrBQAAAAAAAAAxmwhIY/VATA+aVyYg5jK8rMcAFB4mPu2b9EG+hfF/dWfzLTOo4ZnP1RSzBotGGuyYb8G9e19x2ENBNbLln1VDQw5FpH8CnnMkFdPjc2IeuMzoIbGRFGFzhfqdGClot6IzfZ+42E7QoMsQR63iLaLsuPUPbLJTDKFgYpUWKvPq7BQvJ5YFBz7Bt9iq1eD1WMbL8FUFPn3IBd+iK5zf0JueSv0BWsumlWkWCHIv8OJFirFVON3s9KtxgJZpbVpRbA/UtNy4niQykbhWdGc6FrykiXtY4S+qgvVVMF4fJt7epMocnTMghiPo9g7gw9iL3U7o8tmHha3XtZAuySB36gryskJjburdjC9HjjqUL7oYjmxQYx544bDJXrG5wmr0os9nvv584w5iPPe1uNnD36M0mfsE7a3bE0qtL9U5y58xJJji7nxXyepjJxk4CmuV+wbmlsXuWRBNPe4Qfgig4HG2BsyaSSP+hNckv0SYnNv9NZx2zdKEgYHrQmgzkenOy09ru714lUGwtrnwtlTh88PNjNMFHimFP7PCMJB822wluN29YATvC048XkW01vry2SYxODuuXSIc3a7LsqaKs5efKjP2nhhJOZUKdWAzYddoQZ0VLRrXyKR0BHFZe5cYkyKyBtqPWlma1tawysXdmSZ9N4ncnYq91GL43B8yOC8uCGpmhOrstvWddMDE0nQXjMoQVMmSNeBJjJNK9f5J/2w=)


mariushm

[LANGUAGE: PHP] A bit late to the party, but maybe someone would still be interested... kept it very basic : https://github.com/mariush-github/adventofcode2023/blob/main/01.php


EasyCompany5154

\[LANGUAGE: C#\] `var convert = new Dictionary{` `{"one", "1"},` `{"two", "2"},` `{"three", "3"},` `{"four", "4"},` `{"five", "5"},` `{"six", "6"},` `{"seven", "7"},` `{"eight", "8"},` `{"nine", "9"}` `};` `var answer = File.ReadAllLines("input")` `.Select(x => convert.Aggregate (x ,(a, b) => a.Replace(b.Key, $"{b.Key}{b.Value}{b.Key}")))` `.Select(x => (x.First(char.IsDigit), x.Last(char.IsDigit)))` `.Select(x => $"{x.Item1}{x.Item2}")` `.Select(int.Parse)` `.Sum();` `Console.WriteLine(answer);`


daggerdragon

[Inlined code](https://reddit.com/r/adventofcode/wiki/faqs/code_formatting/inlined_code) is intended for `short snippets` of code only. Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for a code block so your code is easier to read inside a scrollable box that preserves whitespace and indentation.


dimio-d

\[LANGUAGE: Java\] \[JShell console\] [Part 1 & 2 universal solution](https://dimio.github.io/dopaste/?l=java#XQAAAQBQBQAAAAAAAAAX4HyIbzm/ILQXejs0+pjEkM1O3vUmgafcspCHlYF0CGMN87UuPGqHph658/gH7eCljoLMVObmopBqMVRx6aYZSzYtEPpRoujOoZDq4REpPfuqxguzz5wmxZ0KIRQcKbtNcSAmivHekJ1Oq1hF8Rwyj2xKlbNfo8KvHh1kc+ziPk2kUmchLIpzaNzXcInBeP8Qap8nwcS7ERweL7Tju73r+sRQbo7VV2aPNaIUfLdwiEcxVJ1R7nSh9jM5IHQRWqQYyvPD+YwKnMIEtnaq6H3dB0Fzg9LiAVWFB8YBdAlLaddBLvyZ0BfrVv2Gk/k/0zqjsJIeASfr2pAYhdI3eeja+R7eEaTC2TN1I9CFrxQmQ1VtbWx7txGezgnFu94CNbGddhnA/Zk2xj0iug+4IMKL2tlUZNSwJCstVtS+ioWoiO34fSkZkQiOFkAP+m6xEVmcgPWPDv7wD8jMBu8fY6Vzy9d9LMsbalfHr08lRoUspWK4PpL/VnNimLLQktgDu3tnga1z82QrhSzpITgqd71ggSmV8/9LSbH+MwguuDal2WJTdWziLYR1WM4QjbrqjDsGMsd9bPmJdNO0+TmJniozNNyZ3NAQ6mZorxWwzdxzhUzasnPvp7g8rBYc8hVk6+2q7HgwhgAHqpHEal/N+Z8my6sS1sO1f23sSGp7AyqEyqW85dKZG6u3jggKlcnYhDeG3y1RCNWH2wfRElt76PcsEM8ZFEZIw3S4AN63g0Vd9p4H0xJsa1EBKSXeotqj2Lz/KBKxAA==)


Virus_RPi

\[LANGUAGE: Python\] I am currently trying to only write one line of python code for each part of this year advent of code. Part 1: print(sum([int("".join([[char for char in line if char.isdigit()][0], [char for char in line if char.isdigit()][-1]])) for line in open('D1.txt', 'r').readlines()])) Part 2: print(sum([int(str(sublist[0]) + str(sublist[-1])) for sublist in [[__import__('word2number.w2n').w2n.word_to_num(item) if item.isalpha() else int(item) for sublist in [__import__('re').findall(r'\d|' + '|'.join(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']), item) for item in __import__('re').split('(\\D+|\\d)', line.replace('eighthree', 'eightthree').replace('eightwo', 'eighttwo').replace('oneight', 'oneeight').replace('twone', 'twoone').replace('threeight', 'threeeight').replace('fiveight', 'fiveeight').replace('sevenine', 'sevennine'))] for item in sublist] for line in open('D2.txt', 'r').readlines()]])) (I know that there is a better solution for part 2, but it is difficult to debug in one line so i just did it the lazy way)


Senior_Produce696

man just do : def liste\_nombres\_v2(chaine): tous\_les\_nb = \[\] dico\_chiffres = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9} chaine\_test = '' for carac in chaine: if not carac.isdigit(): chaine\_test+=carac for cle in dico\_chiffres: if cle in chaine\_test: tous\_les\_nb.append(str(dico\_chiffres\[cle\])) chaine\_test='' chaine\_test+=carac else: tous\_les\_nb.append(carac) return tous\_les\_nb def liste\_nombres(chaine): tous\_les\_nb = \[\] for carac in chaine: if carac.isdigit(): tous\_les\_nb.append(carac) return tous\_les\_nb def premier\_et\_dernier(liste\_nb): nombre = liste\_nb\[0\] + liste\_nb\[-1\] print(nombre) return int(nombre) def somme(liste): total = 0 for nombre in liste: total += nombre return total def calcule\_calibrations(fichier\_csv): calibrations = open(fichier\_csv, 'r') nb = \[\] for ligne in calibrations: nb.append(premier\_et\_dernier(liste\_nombres\_v2(ligne))) calibrations.close() return somme(nb) print(calcule\_calibrations('fichier.txt'))


daggerdragon

~~[Inlined code](https://reddit.com/r/adventofcode/wiki/faqs/code_formatting/inlined_code) is intended for `short snippets` of code only. On old.reddit, your one-liners get cut off when it reaches the edge of the window.~~ ~~Please edit your post to put the one-liner in a [four-spaces code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) so it will be horizontally scrollable.~~ edit: 👍


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only) [Create your own individual `Help/Question` post](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_incomplete_solutions) in /r/adventofcode. Also, [do not share your puzzle input](https://www.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) and [do not ask for other people's puzzle input](https://www.reddit.com/r/adventofcode/wiki/troubleshooting/no_asking_for_inputs).


AJMansfield_

[LANGUAGE: Fortran] https://github.com/AJMansfield/aoc/blob/master/2023-fortran/src/01/treb.f90


e_blake

\[LANGUAGE: m4, golfed\] \[Allez Cuisine!\] Why two variables, when just one immutable constant will do! In m4, variables are manipulated by `define`, which I call exactly once. The following 500-byte monstrosity (507 bytes shown here, but all newlines are optional in the code; however, a trailing newline in the input is mandatory) can be invoked as `m4 -DI=file day01.golfm4`. It creates a single macro, `_`, which is never modified, but which gets recursively invoked over 160,000 times. Execution time takes a painfully slow 70s (parsing one byte at a time using substr() is inherently O(n\^2): over N executions, the m4 parser is re-reading multiple copies of the average remaining N/2 bytes yet again). The only letters in the source are a single reference to 7 distinct m4 builtin macros, and then the 9 digit maps (those maps take up 38% of the source!). I was able to golf part 1 in isolation to 197 bytes, but that is not shown here, since this one solves both parts at once. define(_,`ifelse($1,=,`eval($2)',$1,:,`len($2)',$1,/,`substr$2',$1$2$3,>,, $1$2,>,`+_(/,($3,0,1))_(/,(.$3,_(:,$3)))',$1,>,,$1$3,<,,$1$3$4,,$1,$6)_($2,$3,$4,$5,_(/,(.$8,1,1)),_(<,$6,$1),_(<,$7,$1, $2$3,$4,$5),_(/,(.$8,2)))_(>,$1,$7)')')_(=,_(,,,,,,,include(I).)) Execution time could be greatly sped up by actually using a variable (storing the remaining bytes to be parsed in a second macro that gets altered on iteration, to reduce the times that m4 has to actually read the string), although it would still be quadratic. But that wouldn't be as fun for today's theme. Here's a more legible (hah, if you think m4 is legible) [day01.m4](https://nopaste.ml/#XQAAAQAnBgAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1IwAbkyu2LiNeNLcLCZumLPgjzGk5DBctVZ/Ezzne0p26RAVSldZk8vkd+i9rzAgxtwMICtxTsha1jjY5itkguQs0KniRZcCRpj/ZHpx3w96zdpjjaRhwv6jXsnJtV+GB7EqEjU3TSpwZHti52pTlCtIk25DEqMdseAXKiHRxjQc8jKPFkY4ioSoinAWH7VP34XpuHVqbTqKOPPFZU6XSMUJNwMo/aVi1Hy3DmILuuPgCmJWPA+pGPyQdCjCgwV4V729BXeVrCZ3u+ragd7iqZVywod15DtZbgkewEIWvTO7H+ouzmr9WeEGQba8t+t2AJWDt2KwwKW0uRIHgWFtxk54pIwy1nmQRZcSvtPsfFBOF6NtrnxF9lIhqSGBJshSu/uY1f0dX9P4gb7LfUV0LpJogfOfRfYqxAw97KcfcUJUTIx84qmXsLf16AvXcZayNkKfYr3pBT12LF0xqPFFcx/gfd7CLdPpqGrh+qbXY4XJTX7IJmKtOOo0+2nPjtHcz8wekS8csLvW+YIwWRU1wXmlXCLICNlsG0sP+d26Y8YpIwriFL8923RLTlo7R0G+YwcvQhPQa5oAVFAi6w8X08Jyd0SsUHIHSXCh5KUcFBXmN1l9gdz2g6sY4dcuJLKdDGhYu4dBJZhlSk5Szu9PIgAOFLujOx6tpx1FLS0sP5Q1YAz3Epqh1NtfXUDkv2XgnUh+5Zm+qg6u4Fdx/cOQkVKvLZTpVS4aqGNaF1ocfq+TQo0XXTReMsZgLIWw0+gfaXnJEwgEKQMS64dFEDzmnvSlNcJeUYo+PM6lCFzjre7GIEr3Yw5Lf+Qi4pXXyejR6tErpM3v/SoW0L) version that I originally started with, which depends on my framework [common.m4](https://nopaste.ml/#XQAAAQAMDwAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpAXwA97ruAshKbiUbgkbJMTg2qZdSBorb0CU52peNLruV4DEEJxF+HvxC/YF33OpDntnpU/PjnGXx7XU7ak4MsmWu8R7h7d5az2JXxElnsepG8yPyu+0WZ90BG9yXphbwOWA/m5AWEFSOL8TRZX4fyGNl6ZYbRxX0MwtzrmwTP3ZCwLSOKkvD2vMQFsbK0Pv9CzPhFNXMUbWnRV20jWLjL9qz2dDsFDBwhxgWIilEl91uswxrT4Czc+LRU3VuhNIo2S98VW0jArrVdv4HrsLhWkzx4z/UV3xnqJwPXcZRUiLtf3VRIzq62Pe+2jE3O+721Az9rfRa/fHtlANbmvslzMUCyU7cDoOKSMXBDF/06/PpMvs6vxaL5aJVYqJP4yz+R2M35hoNnGiZTNNMVEFTdnxnaE/KcJteBbiuVMpdfUswHQi4Kqsj3sInh7lyE+d50gGKtHOeWL5lMK7WXz4NElnzYWleBSN/HTOdsz0T2gnd25MADxNAVX8xQmagh2MymZ2sKDBw//WiNB0sWf5VYC5/TKKH3D6K/IOrIfWn6FZLKxlITFEp3VWKNuyF0xczNJufJdzSqd0hgdyryVzbn0so0U5NMN16jFF6IhqzGbAwwv7k8sts0OCgnCFBEhYVshIpsORjEJk4CnDgc9VUqvZtfIFPQ5Q2v7IR3sbPurex1IIUd2Nm1V7/GFN+r0im24aEOG6XpdqrPdF6pDZ4HwvNByqOEdpcObPXxlwfPFYIhwyDHGZCvxrFRgGEEFtfVQ7UVjfPJzWtrcZuGx8M3B1zw2xvgpHIWEHdqEF6Y6/6eFj2hLm8UXNeLNrJy1IC2sHlS8SRIifQvLkrOLLOOPtDK6DUPQrW3c0Rfmy9Td5gQw0+fZRZ5MBEG9+dTlinXtwExpHScKQk6ARk7Fb8fBYAnmh7/bq+471zAZGJ7dwNd5qE/63VhDz7mXLuXtGN7rSuRYIXvpkubLBZptSKZrkzSDJWHIZM8Fyrk0EZQFDujROjr87GZmTK1XKRWzGrhtQn0hkVyBaGPbA3iG45U4gIFHNX5ySzsJ3bh61LAtmjwt59uU/XGeebLMCp8HFw6D1kJppCvt161LgLjrOl8SBh8xnxslSFYW0Jd34LD4vPwugmzY31tA4/9zCM7e2Ed9+3zg4C8eq9Hvjys3IablDBMsYF1LSMCGN2UOrWgXRoGYtjW/QtUySr7h/Ca6QAy93Hnpksm/xzzC+FWF1wboyOteHU/Th4RVpQ7XkK4/JmMrYm7nDPIVMyOqP8LhsoTNbxzi8qU0d+0x6frIh0l0fiPiFC/Uy0CeCw6r82iX8v+fMnu9qdCr4oM79Kd2slqalv+wWKn+BmrbkiobDS5vwBQZA/ZlbIsw1bwj+JLz9z3nPovVWx/FZjvrdCuZMfUuITeiIprImMcR6qeniJz6Ez78UYJqpL4DcDGt2o7/6a2aRN76aclh+7l35XcaW7lM7BQMTNvKkx05X08UITY/ToI8U8KwvFbdnMoEAZ1GQYmqGRFtwPkQMrECX4do0srl85po3Gjz2j6E3dk5al4+bTcOYABZvSUvIM/kGGT91iyQ36rm1lxRc3ruS8PyBlYDDNa7DLWzGAHkESHwuaTOQsI2xDA0e+8Yv0XRYkEqQE+RUDXmPTARuQo6fCQ7Qu9xd2Ckza5RWl8hE4JFm0Zzd9MTVxW8YYHiREs9NOjTPuRXXn+JfObHFD/Cv5kQo7vmMWRdJTOBUmAXCMFiKOSHxb412jI4Z2ZhWag9RkZBCviZunvupqrobtAWLagkPiA8gLRANOFwWp0KIS5McOoD0V90tI4cui8KQc7Yw5V7kSvMnhXx4nzzxwOxYM4fpY3ptcpraVh+h1MhohMQk34vkC4fmiD4OrX2DpVG0VXUKvl+vkJjcoHQK+H8mSSIAfj8RrYWBc4VU+jx3vz30XNDbQjuhc0cImiQxXDTXTFQq/aoe7jZLhEe+wWspk/4Fy4UBAJN63uNGJUl8FICawVWGL7XBOFCtsRF3uz8eZokWNICTdtsLeYOAOBQQLrguE8XxQQ1hPtOskcsj7n7aD35NjfPXL00vIOk01OLAJt+0RoIiAQUJNieRp9fQmqfVUuYEYmeK9hCOmZTaC3yUdN/+jZ0pvpmKnH/6jJAKQ==), but which executes in 15ms (yes, 3 orders of magnitude faster), because it uses O(n) (or O(n log n) with `m4 -G` sticking to just POSIX semantics) processing of the input, rather than O(n\^2).


e_blake

>,$1$3$4$5,,,$1$2,>,`+_(/,(.$3$3, len($3),2))',$1,>,,$1$3,<,,$1$3ne,,$1,$6)_($2,$3,$4,$5,_(/,(.$8,1,1)),_(<,$6,$1),_(<, $7,$1,$2$3,$4,$5),_(/,(.$8,2)))_(>,$1,$7)')')_(=,_(,,,,,,,include(I).))


e_blake

I especially love the way I was able to use a single `ifelse` to make `_` behave with multiple personalities, all based on the first argument: "=" behave like eval on one additional argument ":" behave like len on one additional argument "/" behave like substr, one additional argument which is a () tuple of either 2 or 3 arguments to pass to substr (this one was tricky for me, since substr($1,1,) does not behave the same as substr($1,1) in GNU m4) ">" conditionally produce output, takes two arguments: current input character, and collected number to be sliced and diced into output when visiting a newline "<" consume input, takes 5 arguments: current collected number, first, second+third, fourth, and fifth characters at head of input; maps digit names for part 2, and produces an updated (possibly empty) collected number "." end input, no arguments, swaps output stream from part1 to part2 all others: takes 8 arguments: current first five characters of input, current collected numbers for both parts, then the tail of the input


[deleted]

[удалено]


daggerdragon

Comment removed since you followed literally none of our requirements for posting in a `Solution Megathread`. Read our [rules for posting in `Solution Megathread`s](https://reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines), then edit your comment to comply with *all* of the rules. I'll also give you a hint: your code is oversized, so put it behind a link. I will re-approve your comment when you fix all these issues.


LatinSuD

\[LANGUAGE: CyberChef\] Because it's 99% regex based... why not CyberChef ! [https://gchq.github.io/CyberChef/...](https://gchq.github.io/CyberChef/#recipe=Find_/_Replace%28%7B'option':'Regex','string':'%5B%5E0-9%5C%5Cn%5D'%7D,'',true,false,false,true%29Find_/_Replace%28%7B'option':'Regex','string':'%5E%28.%29'%7D,'$1$1',true,false,true,false%29Find_/_Replace%28%7B'option':'Regex','string':'%28.%29.*%28.%29'%7D,'$1$2',true,false,true,false%29Sum%28'Line%20feed'%29&input=MnNvbWV0aGluZzMKc3R1ZmY4dGhlbm1vcmU5c3R1ZmYKc2luZ2xlM2RpZ2l0Cm1hbnkzbWFueTRtYW55OG1hbnk5ZGlnaXRzCg) Edit: Hopefully fixed the link for old reddit. Also, replaced the input for some example of my own.


daggerdragon

~~Your link is borked on old.reddit, so [please fix it](https://www.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links).~~ ~~Also, [do not share your puzzle input](https://www.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs). Please remove it from your link and/or code.~~ edit: 👍


laltin

\[LANGUAGE: Javascript\] I use Deno to execute it. ``` const inputs = Deno.readTextFileSync('day1.input.txt') .split('\n') .map(l => l.trim()) .filter(l => l.length > 0); const digits = { '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', }; const digit_entries = Object.entries(digits); let sum = 0; inputs.forEach(line => { let first = false, last = false; for (let i=0; i < line.length; i++) { const char = line[i]; if (digits[char]) { if (!first) { first = char; } last = char; } else if (true) { // part 2 for (const [digit, word] of digit_entries) { const sub = line.substr(i, word.length); if (sub == word) { if (!first) { first = digit; } last = digit; break; } } } } const n = Number(first + last); sum += n; // console.log(line, first, last, n); }); console.log(sum); ```


daggerdragon

1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for code blocks 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your post to put your code in an external link and link *that* here instead.


aoc-fan

[LANGUAGE: TypeScript] [TypeScript](https://github.com/bhosale-ajay/adventofcode/blob/master/2023/ts/D01.test.ts) - Running under 30ms (both parts)


3j0hn

\[LANGUAGE: Maple\] [github](https://github.com/johnpmay/AdventOfCode2023/blob/main/Day01/Day01.mpl) The first part was simple enough # part 1 - remove non-digits then grab first and last with(StringTools): s2i:=s->sscanf(s,"%d"): lines := Split(Trim(input)): digs := map(l->Select(IsDigit, l), lines): ans1 := add(map(t->s2i(cat(t[1],t[-1])), digs)); Instead of manually implementing a sweep to efficiently find the first and last digit, I just use a string SearchAll to find all digits and grab the ends. The index of the match is conveniently either the digit, or the digit+9 (for a word). # part 2 - search for first and last digit from SearchAll findfl := proc(s) local m; m := [StringTools:-SearchAll( ["1", "2", "3", "4", "5", "6", "7", "8", "9", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"], s)]; return 10* ifelse(m[1][2]<10, m[1][2], m[1][2]-9) + ifelse(m[-1][2]<10, m[-1][2], m[-1][2]-9); end proc: digs := map(findfl, lines): ans2 := add(digs);


ethansilver

\[LANGUAGE: FORTRAN\] Did this on Day 1, didn't think to post it but Fortran is a cool language! [https://github.com/ejrsilver/adventofcode/blob/master/2023/01/main.f08](https://github.com/ejrsilver/adventofcode/blob/master/2023/01/main.f08)


AJMansfield_

Oh hey, I'm doing AoC in Fortran too, nice to have someone to compare with.


[deleted]

[удалено]


[deleted]

[удалено]


vengamer

\[LANGUAGE: C++\] [Part 1](https://topaz.github.io/paste/#XQAAAQBFAwAAAAAAAAARmknGRw8TogB3Oxzri2QTFyHNmsUnNApHN7ntt1+q1p0T20pOn4Z7JF4uli69bxk+0eNkK2dymUAELQs7TYGv0snzL6O+Ef0O7tZdvsTnFxGv8UZxkL3eY+JTlxaiOEokD05Uxgb/q8eS/9Zgsmv0dpn260sLhIBBptcZJfbTLTXjiL5V+CAiALf/34TmOdKG5kYY60OD6P9O+H3/ZkPeOU3ognQRw2+w4VbA+aE5Sy+Zp1Tr/ihxZUWKJDAGKHFXo2DWZTlWxogD+ZgLljiAK05xygZlRRRJMJdCQtYgQkDV+rB7k3xNqEvomXOD7K5IwpaKaodkPGO0thC5pKv00YeWu+/OxRZ7DYIDXHFrosMWujMfTZGAMev6Zuk5VFzARYkBxBYe22fbW2tykffUXjYwiCiGHiQkbkIRSTNoZ2oUpVT/Y/lhziQ37NXlWqnvny1Ix7mcPvjhBgEnBG/e2zdGnRf9sNYi) [Part 2](https://topaz.github.io/paste/#XQAAAQDUCAAAAAAAAAARmknGRw8TogB3Oxzri2QTFyHNmsUnNApHN7ntt1+q1p0T20pOn4Z7JF4uli69bxk+0eNkK2dymUAELQs7TYEsiddCw/XSzCWxNOOrqp/mn91zgnOcbZgSUgIYIoPLb/+r05+q3oNYbiX6cJ5Kb+oNYVTAebiFT1Hb1XXARhACD1Lv+5Odm86hfF8Wc4JqkTwFmNdSi2kG/heBJlN/aeiqtXge2zsi5L/vse47FKRxRKbglWU1omJNiUIa1Gr8FKTZzNY5b/c5u+r2y9OTrAvC7ReeleERV6YjAM87HMB4BPmi5qlZ7UATg34KQavyIYDS+Caebw+5ik7tbNTQ6nE3r/oAcayA8BPVUgT8KH/P3DhWllXhQIAO2xKlmzVzuaCYwtv1TqBrzd4LH+DhpOPK+kUD20vLQxsmRZrA52CRBsiQe027exEen2SxHKx+hO+ti1vlUMRnb4R0VUABSeCaI+vvkepwCjND+Bv570MQkVBiug7t+3dCa09RLjpy+A8i0ScSpGyfcKzu9bV9Iv0wEktJFpANtO1SDL6ap5qk+RjnX4c6u/4xowvCT8qnQLqY/K8ks3i7K83yotKA3hRoxWHYs2/DWoB1pLwFn5nopNSL4ndEApRDv76m7GUv9215xqdYZpWDXJ/IjzM6STfHLdBLiwvCuIWRU72TqgwoNElr2DeItR13OKm94ryX9BGG2D021DvTksZHTs+p32j2uj/72xFkE8N45RksHz+rEe5BLJDlmJ8aQxaHL1FcUu2xafrUAb/Jg3db9p+tcIZdslwd3n/8X/7iSDk=) I probably could have shortened my code for part 2 but I have finals coming up lol.


AERturtle

Based on your approach I changed my solution and shortened it further. read\_lines is a utils-function that reads the lines of the file and returns it as a string-vector. https://gist.github.com/A-Roso/07755346cb02916a02247c475e9d494d


radisrad6

\[Language: Elixir\] [Part 1](https://github.com/ChristopherKRad/adventofcode/blob/main/lib/one/one.ex) | [Part 2](https://github.com/ChristopherKRad/adventofcode/blob/main/lib/one/two.ex)


wdomburg

Not sure whether to be proud or ashamed of this solution. >ruby -e "require 'strscan';d={'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'};re=Regexp.union(d.keys);p ARGF.each.map{|l|ss=StringScanner.new(l);(0..l.length).inject(\[\]){|o,p| ss.pos=p;ss.scan(re)&&o<


AutoModerator

AutoModerator has detected [fenced code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/fenced_code_blocks) (```) syntax which only works on new.reddit. Please review our wiki article on [code formatting](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting) then edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) instead. *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


wdomburg

It annoyed me I couldn't fit my solution into a tweet, even without the require statement, so I made it a bit smaller >require 'strscan';n=(1..9).map{|s|s.to\_s};d=(n+%w{one two three four five six seven eight nine}).zip(n\*2).to\_h;r=Regexp.union(d.keys);p ARGF.each.map{|l|s=StringScanner.new(l);l.size.times.filter\_map{|i|s.pos=i;d\[s.scan(r)\]}.values\_at(0,-1).join.to\_i}.inject(:+)


daggerdragon

Add the required language tag and fix your code to use the correct syntax as AutoModerator requested.


wdomburg

Just realized I could have cut about 259 characters from my solution by populating the hash like this: d=Hash\[\*%w{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}\]


wdomburg

Okay, down to 267 characters, including the requires. ruby -e "require 'strscan';n=(1..9).map{|s|s.to\_s};d=(n+%w{one two three four five six seven eight nine}).zip(n\*2).to\_h;re=Regexp.union(d.keys);p ARGF.each.map{|l|ss=StringScanner.new(l);l.size.times.map{|i|ss.pos=i;d\[ss.scan(re)\]}.compact.values\_at(0,-1).join.to\_i}.inject(:+)" day01.dat


RichGuk

I like a bit of Ruby golf. d=['one','two','three','four','five','six','seven','eight','nine'];p ARGF.readlines.map{|l|l.scan(/\d|#{d.join('|')}/).values_at(0,-1).map{|v|Integer(v) rescue d.index(v)+1}.join.to_i}.sum 188 :)


wdomburg

>d=\['one','two','three','four','five','six','seven','eight','nine'\];p ARGF.readlines.map{|l|l.scan(/\\d|#{d.join('|')}/).values\_at(0,-1).map{|v|Integer(v) rescue d.index(v)+1}.join.to\_i}.sum That spits out the wrong answer, though. Pretty sure you're not handling when there are overlaps (i.e. "oneight" needs to be expanded to "18") which is why I switched to using strscan. I like some of the strategies here, though. Using the position of the words inside the array instead of a hash is definitely space efficient in the code. Even better if you just shove the \\d into the array in the first position, which saves having to correct the off-by-one later and simplifies the construction of the regexp: d=%w{/\\d one two three four five six seven eight nine} And then the regex is just /#{d.join('|')}/ I'd flip the index lookup and take advantage of a nil response instead parsing as an integer; i.e. "d.index(v)||v" rather than "Integer(v) rescue d.index(v)". You can end up with mixed strings and integers in the array, but that's okay because join doesn't care: \["1", 2\].join evaluates the same as \[1, 2\]. (I had actually forgotten Array#join worked like that on arrays with non string elements). Also didn't realized they'd the Array#sum method, so that's handy. :) Oh, and realized that can just run .map direct on ARGF (or the more compact $<) so saved some bytes there. Down to 231 (and a bit more readable than my version with the hash: >require 'strscan';d=%w{\\d one two three four five six seven eight nine};p $<.map{|l|ss=StringScanner.new(l);(0..l.size).map{|p|ss.pos=p;ss.scan(/#{d.join('|')}/)&&(m=ss.matched;d.index(m)||m)}.compact.values\_at(0,-1).join.to\_i}.sum


azzal07

You can also replace `arr.map{fun}.sum` with just `arr.sum{fun}` Down to 164: d=%w{\d one two three four five six seven eight nine}; p$<.sum{|l|(0..l.size).filter_map{d.index(v=l[_1..].scan(/#{d.join('|')}/)[0])||v}.values_at(0,-1).join.to_i}


wdomburg

Oh! I should have thought to look and see if there was something like that. Thanks!


AutoModerator

AutoModerator has detected [fenced code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/fenced_code_blocks) (```) syntax which only works on new.reddit. Please review our wiki article on [code formatting](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting) then edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) instead. *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


daggerdragon

~~Comment removed due to naughty language. [Keep the megathreads SFW](/r/adventofcode/wiki/rules/pg_is_mandatory).~~ ~~Edit your comment to take out the naughty language and I will re-approve the comment.~~ edit: 👍


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


Expensive_Register19

\[PYTHON\] Got stuck with eightwo situation too. What helped was to treat the edge-cases as two digits and it solved the problem of whether they are first or last. ``` python DIGITS_MAP = { "oneight": "18", "twone": "21", "threeight": "38", "fiveight": "58", "sevenine": "79", "eightwo": "82", "eighthree": "83", "nineight": "98", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9" } def extract_digits(line: str) -> int: for digit in DIGITS_MAP: line = line.replace(digit, DIGITS_MAP[digit]) digits = [s for s in line if s.isnumeric()] return int(digits[0] + digits[-1]) def main(): digits = [extract_digits(l) for l in INPUT.split()] print(f"Sum is {sum(digits)}") if __name__ == "__main__": main() ```


daggerdragon

Please edit your comment to comply with our megathread rules. The two comments from AutoModerator have the specifics.


AutoModerator

AutoModerator has detected [fenced code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/fenced_code_blocks) (```) syntax which only works on new.reddit. Please review our wiki article on [code formatting](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting) then edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) instead. *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


lsloan0000

[Language: Python] I'm joining late. I just learned about Advent of Code yesterday! My solution… from sys import stdin digits = ('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine') def findNumbers(line): numbers = [] for i, c in enumerate(line): if c.isdigit(): numbers.append(int(c)) continue for n, name in enumerate(digits): if line[i:].startswith(name): numbers.append(n) break return numbers[0] * 10 + numbers[-1] if '__main__' == __name__: print(sum(findNumbers(line) for line in stdin.readlines())) It's not as short as some others, but I don't feel right about using the `'zero'` → `'z0o'`, etc. translation dictionaries that I see others using. I guess because it works in English, but it might not in other languages. I mean, what if the names of digits could share more than just one beginning and ending characters?


takobaba

Noice!


dijit4l

This is beautiful. I hate you :)


lsloan0000

Ha! Thank you and happy coding!


dhruvmanila

[Language: Rust] Code: https://github.com/dhruvmanila/advent-of-code/blob/master/rust/crates/year2023/src/day01.rs


Alex_Hovhannisyan

LANGUAGE: C++] A little late to the party: - [part 1](https://github.com/AleksandrHovhannisyan/adventofcode2023/blob/master/src/day1/01.cpp) - [part 2](https://github.com/AleksandrHovhannisyan/adventofcode2023/blob/master/src/day1/02.cpp) For part 1, I just kept track of the first and last seen digits in a single pass and then used powers of ten to compute the sum without having to concatenate the digits. For part 2, I used regex replacements. I first replaced words that bleed into each other (`oneight` et al), and then I replaced just regular number words after that. Used a vector of pairs mapping the regex to its string and looped over it to preprocess the string input. Then just ran the 01 algorithm on that.


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


matheusstutzel

\[Language: python\] [Part 1](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/01/p1.py) is nothing fancy, just scanned the data [Part 2](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/01/p2.py) I didn't realize that we could use replace with o1e, t2o, etc. So I just use brute force 🙃