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

  • @[email protected]
    link
    fedilink
    81 year ago

    Python 3

    I had some trouble getting Part 2 to work, until I realized that there could be overlap ( blbleightwoqsqs -> 82).

    spoiler
    import re
    
    def puzzle_one():
        result_sum = 0
        with open("inputs/day_01", "r", encoding="utf_8") as input_file:
            for line in input_file:
                number_list = [char for char in line if char.isnumeric()]
                number = int(number_list[0] + number_list[-1])
                result_sum += number
        return result_sum
    
    def puzzle_two():
        regex = r"(?=(zero|one|two|three|four|five|six|seven|eight|nine|[0-9]))"
        number_dict = {
            "zero": "0",
            "one": "1",
            "two": "2",
            "three": "3",
            "four": "4",
            "five": "5",
            "six": "6",
            "seven": "7",
            "eight": "8",
            "nine": "9",
        }
        result_sum = 0
        with open("inputs/day_01", "r", encoding="utf_8") as input_file:
            for line in input_file:
                number_list = [
                    number_dict[num] if num in number_dict else num
                    for num in re.findall(regex, line)
                ]
                number = int(number_list[0] + number_list[-1])
                result_sum += number
        return result_sum
    

    I still have a hard time understanding regex, but I think it’s getting there.

  • @[email protected]
    link
    fedilink
    6
    edit-2
    1 year ago

    A new C solution: without lookahead or backtracking! I keep a running tally of how many letters of each digit word were matched so far: https://github.com/sjmulder/aoc/blob/master/2023/c/day01.c

    int main(int argc, char **argv)
    {
    	static const char names[][8] = {"zero", "one", "two", "three",
    	    "four", "five", "six", "seven", "eight", "nine"};
    	int p1=0, p2=0, i,c;
    	int p1_first = -1, p1_last = -1;
    	int p2_first = -1, p2_last = -1;
    	int nmatched[10] = {0};
    	
    	while ((c = getchar()) != EOF)
    		if (c == '\n') {
    			p1 += p1_first*10 + p1_last;
    			p2 += p2_first*10 + p2_last;
    			p1_first = p1_last = p2_first = p2_last = -1;
    			memset(nmatched, 0, sizeof(nmatched));
    		} else if (c >= '0' && c <= '9') {
    			if (p1_first == -1) p1_first = c-'0';
    			if (p2_first == -1) p2_first = c-'0';
    			p1_last = p2_last = c-'0';
    			memset(nmatched, 0, sizeof(nmatched));
    		} else for (i=0; i<10; i++)
    			/* advance or reset no. matched digit chars */
    			if (c != names[i][nmatched[i]++])
    				nmatched[i] = c == names[i][0];
    			/* matched to end? */
    			else if (!names[i][nmatched[i]]) {
    				if (p2_first == -1) p2_first = i;
    				p2_last = i;
    				nmatched[i] = 0;
    			}
    
    	printf("%d %d\n", p1, p2);
    	return 0;
    }
    
    • @[email protected]
      link
      fedilink
      31 year ago

      And golfed down:

      char*N[]={0,"one","two","three","four","five","six","seven","eight","nine"};p,P,
      i,c,a,b;A,B;m[10];main(){while((c=getchar())>0){c==10?p+=a*10+b,P+=A*10+B,a=b=A=
      B=0:0;c>47&&c<58?b=B=c-48,a||(a=b),A||(A=b):0;for(i=10;--i;)c!=N[i][m[i]++]?m[i]
      =c==*N[i]:!N[i][m[i]]?A||(A=i),B=i:0;}printf("%d %d\n",p,P);
      
  • @[email protected]
    link
    fedilink
    4
    edit-2
    11 months ago

    I feel ok about part 1, and just terrible about part 2.

    day01.factor on github (with comments and imports):

    : part1 ( -- )
      "vocab:aoc-2023/day01/input.txt" utf8 file-lines
      [
        [ [ digit? ] find nip ]
        [ [ digit? ] find-last nip ] bi
        2array string>number
      ] map-sum .
    ;
    
    MEMO: digit-words ( -- name-char-assoc )
      [ "123456789" [ dup char>name "-" split1 nip ,, ] each ] H{ } make
    ;
    
    : first-digit-char ( str -- num-char/f i/f )
      [ digit? ] find swap
    ;
    
    : last-digit-char ( str -- num-char/f i/f )
      [ digit? ] find-last swap
    ;
    
    : first-digit-word ( str -- num-char/f )
      [
        digit-words keys [
          2dup subseq-index
          dup [
            [ digit-words at ] dip
            ,,
          ] [ 2drop ] if
        ] each drop                           !
      ] H{ } make
      [ f ] [
        sort-keys first last
      ] if-assoc-empty
    ;
    
    : last-digit-word ( str -- num-char/f )
      reverse
      [
        digit-words keys [
          reverse
          2dup subseq-index
          dup [
            [ reverse digit-words at ] dip
            ,,
          ] [ 2drop ] if
        ] each drop                           !
      ] H{ } make
      [ f ] [
        sort-keys first last
      ] if-assoc-empty
    ;
    
    : first-digit ( str -- num-char )
      dup first-digit-char dup [
        pick 2dup swap head nip
        first-digit-word dup [
          [ 2drop ] dip
        ] [ 2drop ] if
        nip
      ] [
        2drop first-digit-word
      ] if
    ;
    
    : last-digit ( str -- num-char )
      dup last-digit-char dup [
        pick 2dup swap 1 + tail nip
        last-digit-word dup [
          [ 2drop ] dip
        ] [ 2drop ] if
        nip
      ] [
        2drop last-digit-word
      ] if
    ;
    
    : part2 ( -- )
      "vocab:aoc-2023/day01/input.txt" utf8 file-lines
      [ [ first-digit ] [ last-digit ] bi 2array string>number ] map-sum .
    ;
    
  • Tom
    link
    fedilink
    4
    edit-2
    1 year 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));
        }
    }
    
    
  • @[email protected]
    link
    fedilink
    English
    4
    edit-2
    1 year ago
    import re
    numbers = {
        "one" : 1,
        "two" : 2,
        "three" : 3,
        "four" : 4,
        "five" : 5,
        "six" : 6,
        "seven" : 7,
        "eight" : 8,
        "nine" : 9
        }
    for digit in range(10):
        numbers[str(digit)] = digit
    pattern = "(%s)" % "|".join(numbers.keys())
       
    re1 = re.compile(".*?" + pattern)
    re2 = re.compile(".*" + pattern)
    total = 0
    for line in open("input.txt"):
        m1 = re1.match(line)
        m2 = re2.match(line)
        num = (numbers[m1.group(1)] * 10) + numbers[m2.group(1)]
        total += num
    print(total)
    

    There weren’t any zeros in the training data I got - the text seems to suggest that “0” is allowed but “zero” isn’t.

  • @[email protected]
    link
    fedilink
    English
    4
    edit-2
    1 year 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(&self, input: &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(&self, input: &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 = &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 = &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()
        }
    }
    
    • @[email protected]
      link
      fedilink
      2
      edit-2
      1 year ago

      there where only two rules about posting here and you managed to break one of them

      edit: oh sry, only one rule

  • @[email protected]
    link
    fedilink
    41 year 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")]))

  • bugsmith
    link
    fedilink
    4
    edit-2
    1 year ago

    Part 02 in Rust 🦀 :

    use std::{
        collections::HashMap,
        env, fs,
        io::{self, BufRead, BufReader},
    };
    
    fn main() -> io::Result<()> {
        let args: Vec = env::args().collect();
        let filename = &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(), &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: &HashMap<&str, &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 < 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 < chars.len() {
                if chars[ptr2].is_digit(10) {
                    sample.clear();
                    break;
                }
                sample.push(chars[ptr2]);
                if number_map.contains_key(&sample.as_str()) {
                    let str_digit: char = number_map.get(&sample.as_str()).unwrap().parse().unwrap();
                    digits.push(str_digit);
                    sample.clear();
                    break;
                }
                ptr2 += 1;
            }
            ptr1 += 1;
        }
    
        digits
    }
    
    • @[email protected]
      cake
      link
      fedilink
      21 year ago

      Thanks, used this as input for reading the Day 2 file and looping the lines, just getting started with rust :)

  • @mykl
    link
    4
    edit-2
    1 year ago

    Dart solution

    This has got to be one of the biggest jumps in trickiness in a Day 1 puzzle. In the end I rolled my part 1 answer into the part 2 logic. [Edit: I’ve golfed it a bit since first posting it]

    import 'package:collection/collection.dart';
    
    var ds = '0123456789'.split('');
    var wds = 'one two three four five six seven eight nine'.split(' ');
    
    int s2d(String s) => s.length == 1 ? int.parse(s) : wds.indexOf(s) + 1;
    
    int value(String s, List digits) {
      var firsts = {for (var e in digits) s.indexOf(e): e}..remove(-1);
      var lasts = {for (var e in digits) s.lastIndexOf(e): e}..remove(-1);
      return s2d(firsts[firsts.keys.min]) * 10 + s2d(lasts[lasts.keys.max]);
    }
    
    part1(List lines) => lines.map((e) => value(e, ds)).sum;
    
    part2(List lines) => lines.map((e) => value(e, ds + wds)).sum;
    
  • @[email protected]
    link
    fedilink
    41 year 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 < 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(&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 < len(line); i += 1) :found {
    			for (let num = start; num < len(numbers); num += 1) {
    				const start = strings::sub(line, i, strings::end);
    				if (first is void && 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 && strings::hasprefix(end, numbers[num].0)) {
    					last = numbers[num].1;
    				};
    				if (first is int && last is int) {
    					break :found;
    				};
    			};
    		};
    		sum += first as int * 10 + last as int;
    	};
    	fmt::printfln("{}", sum)!;
    };
    
    export fn main() void = {
    	solve(9);
    	solve(0);
    };
    
  • @[email protected]
    link
    fedilink
    4
    edit-2
    1 year ago

    Solution in C: https://github.com/sjmulder/aoc/blob/master/2023/c/day01-orig.c

    Usually day 1 solutions are super short numeric things, this was a little more verbose. For part 2 I just loop over an array of digit names and use strncmp().

    int main(int argc, char **argv)
    {
    	static const char * const nm[] = {"zero", "one", "two", "three",
    	    "four", "five", "six", "seven", "eight", "nine"};
    	char buf[64], *s;
    	int p1=0,p2=0, p1f,p1l, p2f,p2l, d;
    	
    	while (fgets(buf, sizeof(buf), stdin)) {
    		p1f = p1l = p2f = p2l = -1;
    
    		for (s=buf; *s; s++)
    			if (*s >= '0' && *s <= '9') {
    				d = *s-'0';
    				if (p1f == -1) p1f = d;
    				if (p2f == -1) p2f = d;
    				p1l = p2l = d;
    			} else for (d=0; d<10; d++) {
    				if (strncmp(s, nm[d], strlen(nm[d])))
    					continue;
    				if (p2f == -1) p2f = d;
    				p2l = d;
    				break;
    			}
    
    		p1 += p1f*10 + p1l;
    		p2 += p2f*10 + p2l;
    	}
    
    	printf("%d %d\n", p1, p2);
    	return 0;
    }
    
  • @nichobi
    link
    English
    31 year ago

    Part 1 felt fairly pretty simple in Haskell:

    import Data.Char (isDigit)
    
    main = interact solve
    
    solve :: String -> String
    solve = show . sum . map (read . (\x -> [head x, last x]) . filter isDigit) . lines
    

    Part 2 was more of a struggle, though I’m pretty happy with how it turned out. I ended up using concatMap inits . tails to generate all substrings, in order of appearance so one3m becomes ["","o","on","one","one3","one3m","","n","ne","ne3","ne3m","","e","e3","e3m","","3","3m","","m",""]. I then wrote a function stringToDigit :: String -> Maybe Char which simultaneously filtered out the digits and standardised them as Chars.

    import Data.List (inits, tails)
    import Data.Char (isDigit, digitToInt)
    import Data.Maybe (mapMaybe)
    
    main = interact solve
    
    solve :: String -> String
    solve = show . sum . map (read . (\x -> [head x, last x]) . mapMaybe stringToDigit . concatMap inits . tails) . lines
    --                             |string of first&last digit| |find all the digits |   |all substrings of line|
    
    stringToDigit "one"   = Just '1'
    stringToDigit "two"   = Just '2'
    stringToDigit "three" = Just '3'
    stringToDigit "four"  = Just '4'
    stringToDigit "five"  = Just '5'
    stringToDigit "six"   = Just '6'
    stringToDigit "seven" = Just '7'
    stringToDigit "eight" = Just '8'
    stringToDigit "nine"  = Just '9'
    stringToDigit [x]
      | isDigit x         = Just x
      | otherwise         = Nothing
    stringToDigit _       = Nothing
    

    I went a bit excessively Haskell with it, but I had my fun!

  • snowe
    link
    fedilink
    3
    edit-2
    1 year ago

    Ruby

    https://github.com/snowe2010/advent-of-code/blob/master/ruby_aoc/2023/day01/day01.rb

    Part 1

    execute(1, test_file_suffix: "p1") do |lines|
      lines.inject(0) do |acc, line|
        d = line.gsub(/\D/,'')
        acc += (d[0] + d[-1]).to_i
      end
    end
    

    Part 2

    map = {
      "one": 1,
      "two": 2,
      "three": 3,
      "four": 4,
      "five": 5,
      "six": 6,
      "seven": 7,
      "eight": 8,
      "nine": 9,
    }
    
    execute(2) do |lines|
      lines.inject(0) do |acc, line|
        first_num = line.sub(/(one|two|three|four|five|six|seven|eight|nine)/) do |key|
          map[key.to_sym]
        end
        last_num = line.reverse.sub(/(enin|thgie|neves|xis|evif|ruof|eerht|owt|eno)/) do |key|
          map[key.reverse.to_sym]
        end
    
        d = first_num.chars.select { |num| numeric?(num) }
        e = last_num.chars.select { |num| numeric?(num) }
        acc += (d[0] + e[0]).to_i
      end
    end
    

    Then of course I also code golfed it, but didn’t try very hard.

    P1 Code Golf

    execute(1, alternative_text: "Code Golf 60 bytes", test_file_suffix: "p1") do |lines|
      lines.inject(0){|a,l|d=l.gsub(/\D/,'');a+=(d[0]+d[-1]).to_i}
    end
    

    P2 Code Golf (ignore the formatting, I just didn’t want to reformat to remove all the spaces, and it’s easier to read this way.)

    execute(1, alternative_text: "Code Golf 271 bytes", test_file_suffix: "p1") do |z|
      z.inject(0) { |a, l|
        w = %w(one two three four five six seven eight nine)
        x = w.join(?|)
        f = l.sub(/(#{x})/) { |k| map[k.to_sym] }
        g = l.reverse.sub(/(#{x.reverse})/) { |k| map[k.reverse.to_sym] }
        d = f.chars.select { |n| n.match?(/\d/) }
        e = g.chars.select { |n| n.match?(/\d/) }
        a += (d[0] + e[0]).to_i
      }
    end
    
    • @[email protected]
      link
      fedilink
      31 year ago

      Thank you for sharing this. I also wrote a regular expression with \d|eno|owt and so on, and I was not so proud of myself :). Good to know I wasn’t the only one :).

      • @[email protected]
        link
        fedilink
        11 year ago

        I was trying so hard to avoid doing this and landed on a pretty nice solution (for me). It’s funny sering everyone’s approach especially when you have no problem running through that barrier that I didn’t want to 😆

      • snowe
        link
        fedilink
        11 year ago

        haha it’s such a dumb solution, but it works. i’ve seen several others that have done the same thing. The alternatives all sounded too hard for my tired brain.