Xah Talk Show 2024-08-03 Ep569, Advent of Code 2023, Day 11, Wolfram Language
toy input
...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#.....
- problem:
- given a text input. multi lines.
- each char is either a dot or a pound sign.
- first, double the row that's all dots.
- and, double any column that's all dots.
- need to find a way to identify the pound sign.
- for each pound symbol, it is identify by row number and column number.
- row start at 1, column start at 1.
- the distance between 2 galaxies is the
diff(row num) + diff(col num)
- get all possible pairs of the galaxies. order in pair no matter.
- sum up all their distances
(* solution. Turn the text into a matrix. add extra columns and rows, for any empty column and row. then use Position[ matrix, 1 ] to give a list of all indexes. then use pattern matching to get all distances. then just Total *) xinput = "...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#....."; xinput = ReadString["c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_11_input.txt"]; xmatrix = Map[ Characters , StringSplit[ xinput , "\n" ] ]; xmatrix = ReplaceAll[ xmatrix , {emptyRow:{"."..} -> Sequence[emptyRow,emptyRow] } ]; xmatrix = Transpose@ ReplaceAll[ Transpose[ xmatrix ] , {emptyRow:{"."..} -> Sequence[emptyRow,emptyRow] } ]; xcoordlist = Position[ xmatrix, "#" ]; xAllGalaxyPairs = Subsets[ xcoordlist, {2} ]; result = Total@ Replace[ xAllGalaxyPairs , {{a_, b_}, {c_, d_}} :> Abs[a-c]+Abs[b-d], {1} ]; Print[ result ] (* my solution 9742154 *)
(* Advent of Code 2023, Day 11, part 1. Wolfram Language short solution *) xinput = "...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#....."; (* xinput = ReadString["c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_11_input.txt"]; *) xinput // StringSplit // ( Characters /@ # &) // ( # /. {r:{"."..} -> Sequence[r,r] } &) // (Transpose@ (Transpose@# /. {r:{"."..} -> Sequence[r,r] }) &) // Position[ #, "#" ] & // Subsets[ #, {2} ] & // ( # /. {{a_, b_}, {c_, d_}} :> Abs[a-c]+Abs[b-d]) & // Total // Print (* my solution 9742154 *)