Code for the Advent of Code event
aoc
advent-of-code
1#!/usr/bin/env ruby
2# frozen_string_literal: true
3
4require_relative '../lib/astar'
5require_relative '../lib/grid'
6
7def heuristic(a, b)
8 x1, y1 = a.to_a
9 x2, y2 = b.to_a
10 (x1 - x2).abs + (y1 - y2).abs
11end
12
13diagram4 = GridWithWeights.new 10, 10
14diagram4.walls = [[1, 7], [1, 8], [2, 7], [2, 8], [3, 7], [3, 8]].map { Vector[*_1] }
15
16start, goal = Vector[1, 4], Vector[1, 9]
17came_from, cost_so_far = AStar.find_path(diagram4, start, goal, &method(:heuristic))
18diagram4.draw point_to: came_from, start: start, goal: goal
19path = AStar.reconstruct_path(came_from, start, goal)
20diagram4.draw path: path
21diagram4.draw number: cost_so_far, start: start, goal: goal
22
23puts "Shortest path has cost #{cost_so_far[goal]}"