https://adventofcode.com/2021/day/7

Day 7's puzzle also had a comma separated list as its data, so again
no parsing routine was necessary:

sample=: 16,1,2,0,4,2,7,1,2,14

Here, you are being rescued from a whale by a bunch of crab submarines
-- each number represents the position of a crab submarine.

The puzzle is to find the one position to move them all to which
requires the least movement. Or, in puzzle terms the least "fuel" --
one crab changing its position by one unit costs one fuel. To solve
the puzzle you need to report how much fuel this "least fuel" costs.

My approach here was just plain brute force: checking every candidate position:

leastfuel=:{{
  min=.<./y
  max=.>./y
  options=.min+i.1+max-min
  fuel=. +/|y-/options
  optimum=. min+(i.<./)fuel
  optimum{fuel
}}

For part 2, the fuel cost was not constant, but increased by one each
step. 1 step is still 1 fuel, two steps is 1+2 fuel, three steps is
1+2+3 fuel. In other the sum was a triangular number: -:@(*>:)distance

So, I threw that expression into my routine:

crab=:{{
  min=.<./y
  max=.>./y
  options=.min+i.1+max-min
  fuel=. +/-:@(*>:)|y-/options
  optimum=. min+(i.<./)fuel
  optimum{fuel
}}

I am sure that there's better ways of expressing this.  That said,
plotting the fuel costs for each of the position options suggests that
brute force was the only viable approach here. If I am wrong about
that, I would love to hear an explanation.

-- 
Raul
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to