My submission for Ruby Challenge #3: Short Circuit
rubylearning.com/blog/2009/10/30/rpcfn-short-circuit-3/
-
100% RSpec test coverage
-
Works in both Ruby 1.8 and 1.9
class Circuit | |
def initialize(resistors) | |
@resistors = resistors | |
@final_node = 0 | |
@resistors.each do |(source, destination, resistance)| | |
@final_node = [@final_node, source, destination].max | |
end |
require 'set' | |
class ClosedCircuit | |
Infinity = 1/0.0 | |
def initialize(input, source, dest) | |
@graph = GraphParser.parse(input) | |
@source = source | |
@dest = dest | |
end |
require "test/unit" | |
class TestFindRedundantResistors < Test::Unit::TestCase | |
def test_find_redundant_resistors | |
actual = find_redundant_resistors [ | |
[ 'A', 'B', 50], | |
[ 'A', 'D', 150], | |
[ 'B', 'C', 250], | |
[ 'B', 'E', 250], | |
[ 'C', 'E', 350], | |
[ 'C', 'D', 50], |
class Graph | |
require 'set' | |
INFINITY = 1 << 64 | |
# Constructor | |
def initialize | |
@graph = magic_hash | |
# The graph // {node => { edge1 => weight, edge2 => weight}, node2 => ... | |
@nodes = Set.new | |
end |
require 'set' | |
class ClosedCircuit | |
Infinity = 1/0.0 | |
def initialize(input, source, dest) | |
@graph = GraphParser.parse(input) | |
@source = source | |
@dest = dest | |
end |
EDGES = [ | |
[ 'A', 'B', 50], | |
[ 'A', 'D', 150], | |
[ 'B', 'C', 250], | |
[ 'B', 'E', 250], | |
[ 'C', 'E', 350], | |
[ 'C', 'D', 50], | |
[ 'C', 'F', 100], | |
[ 'D', 'F', 400], | |
[ 'E', 'G', 200], |
############ | |
#Class Hash# | |
############ | |
#Dijkstra's algorythm requires a priority queue, the easiest way to make one is to add a method | |
#to hash that pops the key/value pair with the lowest value. | |
class Hash | |
#Return the key/value pair with the lowest value as an array, deletes the pair. | |
def pop_lowest_value! | |
smallest_pair = self.min{ |a,b| a[1] <=> b[1]} | |
self.delete(smallest_pair[0]) if smallest_pair |
#!/usr/bin/env ruby | |
class CircuitSegment | |
attr_accessor :startNode, :endNode, :ohmage | |
def initialize(startNode, endNode, ohmage) | |
@startNode=startNode | |
@endNode=endNode | |
@ohmage=ohmage | |
end | |
end |
class Polynomial | |
def initialize(arg) | |
raise ArgumentError.new('We expect an array at least') unless arg.is_a? Array | |
raise ArgumentError.new('Need at least 2 coefficients') if arg.length < 2 | |
@exponents = [] | |
arg.reverse.inject(0) do |index,item| | |
@exponents.push( { "factor" => item, "exponent" => index }) unless item == 0 | |
index + 1 | |
end |