Xah Talk Show 2023-12-02 Advent of Code Day 1, in WolframLang

Advent of Code 2023, Day 1, Problem Description

Part 1

Given a text file, of many lines of text. Extract the first and last digit of each line. Combine the digits forming a 2-digit number. Sum them up.

example:

1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
In this examp

we have numbers 12, 38, 15, 77

sum is 142.

Part 2

if the line contains any one of digit names spelled out like this:

one, two, three, four, five, six, seven, eight, nine

they also count as valid digits.

sample input:

two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

we have, the number for each line is 29, 83, 13, 24, 42, 14, 76

sum is 281.

Speak[ "trebuchet" ]
(* advent of code 2023 day 1 part 1 solution *)

input = "1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet";

input = ReadString @ "c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_1_input.txt";

((ToExpression @ StringJoin @ StringCases[#, RegularExpression @ "[0-9]" ][[{1,-1}]]) &) /@ StringSplit@input // Total

(*
answer.
test input
142

my input
55386
 *)
(* advent of code 2023 day 1 part 2 solution *)

input =
"two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen";

input = ReadString @ "c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_1_input.txt";

(* interesting overlap situation *)
(StringCases[ "7twone", RegularExpression[ "[0-9]|one|two|three|four|five|six|seven|eight|nine" ], Overlaps -> True ] )

((ToExpression @ StringJoin @ (StringCases[ #, RegularExpression[ "[0-9]|one|two|three|four|five|six|seven|eight|nine" ], Overlaps -> True ] [[{1,-1}]] /. { "one" -> "1", "two" -> "2", "three" -> "3", "four" -> "4", "five" -> "5", "six" -> "6", "seven" -> "7", "eight" -> "8", "nine" -> "9" })) &) /@ StringSplit @ input // Total

(* 
test input solution
281

my input solution
54824
*)

Other People's Solution

/*
advent of code 2003 day 1 part 1
solution by georrg
*/

console.log(
  Deno
    .readTextFileSync("c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_1_input.txt")
    .split("\n")
    .reduce((sum, line) => {
      const { 0: first, length, [length - 1]: last } = line.match(/\d/g);
      return sum + 10 * +first + +last;
    }, 0),
);

/*
output
55386
*/

/*
xahlee's analysis.
this is a very advanced solution, involving esoteric knowledge of js.
very advanced is the line
const { 0: first, length, [length - 1]: last } = line.match(/\d/g);
it uses advanced
Destructuring Assignment
and relies on the fact that
the match method returns a array and length key,
and destructure allow latter var to have former var values,
and the use of reduce.

 */