Skip to content

Instantly share code, notes, and snippets.

@flada-auxv
Created August 23, 2013 18:22
Show Gist options
  • Save flada-auxv/6322404 to your computer and use it in GitHub Desktop.
Save flada-auxv/6322404 to your computer and use it in GitHub Desktop.
抵抗の合計を求める
class Circuit
def initialize(circuit)
@circuit = analyze(circuit)
end
def calc
@circuit.inject(0) {|memo, item| memo + item.val}.truncate
end
def analyze(circuit)
circuit.map { |resistance| Resistance.new(resistance) }
end
end
class Resistance
attr_accessor :str, :val
def self.set_hash(resistances)
@@hash = resistances
end
def initialize(str)
@str = str
@val = set_val
end
def set_val
return @@hash[str] if series?
1 / (str.split('').map {|a| 1 / @@hash[a] }.inject(:+))
end
def series?
@str.length == 1
end
def parallel?
!series?
end
end
class InputParser
def initialize(input_file)
@lines = input_file.readlines.map { |line| line.split(' ') }
end
def parse
n = @lines[0].first.to_i
resistances = @lines[1..n].each_with_object({}) { |(type, resistance), result|
result[type] = resistance.to_f
}
circuit = @lines[n + 1]
return resistances, circuit
end
end
resistances, circuit = InputParser.new(ARGF).parse
Resistance.set_hash(resistances)
p Circuit.new(circuit).calc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment