Wednesday, December 26, 2018

Advent of Code 2015 - Day 9: All in a Single Night

Part 1

Description

Solution

This problem is also known as traveling salesman problem, with exception, that Santa doesn't go back to the starting point. I don't have any better solution than this. First, I paste and split the input.

Then, I put those numbers into a table. Because there are eight locations, I made an 8×8 table, pairing each of them.

As you can see, the table shows all the distance between those locations, marked with numbers 1-8. There are 8! (40320) possibilities of routes taken. Or precisely, there are just half of it, because the distance of route 1-2-3-4-5-6-7-8 is the same as route 8-7-6-5-4-3-2-1. So, I made a list of all possible permutation from these numbers.

Here is the way to do it. I went to a blank sheet and paste the following formula:

=IF(ROW()<=FACT(COLUMN()-1),COLUMN(),
INDIRECT(ADDRESS(ROW()-FACT(SUMPRODUCT(((ROW()-1)>=FACT(ROW($A$2:$A$10)))+0)+1),
IF(COLUMN()=(SUMPRODUCT(((ROW()-1)>=FACT(ROW($A$2:$A$10)))+0)+2),1,COLUMN()+1))))

Then, by dragging the formula to 8 columns and 40320 rows, I get the permutation I need. Next, I put another formula in seven columns (Q-X), one for each distance between two adjacent places, and sum them up. The formula is:

=INDEX($H$4:$O$11,H13,I13) 

And, finally a formula to return the smallest value of the sum of the distances:

=SMALL(X13:X40332,1)

Part 2

Description

Solution

For the part 2, I just need to modify the formula to get the longest route.

=LARGE(X13:X40332,1)

Share:

0 komentar:

Recent Posts

Categories

Blog Archive