Code for the Advent of Code event
aoc advent-of-code
at main 54 lines 1.3 kB view raw
1# frozen_string_literal: true 2 3# Implementations from https://github.com/msayson/weighted_graph 4# Licensed under the MIT License. 5# Copyright (c) 2017 Mark Sayson 6 7# Some parts modified with input from 8# https://www.redblobgames.com/pathfinding/a-star/implementation.html 9 10class WeightedGraph 11 def initialize(edges = Hash.new(0)) 12 @edges = edges 13 end 14 15 def add_edge(source, destination, weight) 16 if @edges.key? source 17 @edges[source][destination] = weight 18 else 19 @edges[source] = { destination => weight } 20 end 21 end 22 23 def add_undirected_edge(vertex_a, vertex_b, weight) 24 add_edge(vertex_a, vertex_b, weight) 25 add_edge(vertex_b, vertex_a, weight) 26 end 27 28 def remove_edge(source, destination) 29 @edges[source].delete(destination) if @edges.key?(source) 30 end 31 32 def remove_undirected_edge(vertex_a, vertex_b) 33 remove_edge(vertex_a, vertex_b) 34 remove_edge(vertex_b, vertex_a) 35 end 36 37 def contains_edge?(source, destination) 38 @edges.key?(source) && @edges[source].key?(destination) 39 end 40 41 def cost(source, destination) 42 if contains_edge?(source, destination) 43 @edges[source][destination] 44 else 45 Float::INFINITY 46 end 47 end 48 49 def neighbors(source) 50 adjacent = [] 51 adjacent = @edges[source].map { |dst, _weight| dst } if @edges.key?(source) 52 Set.new(adjacent) 53 end 54end