Created
December 6, 2011 11:33
-
-
Save dmeremyanin/1437878 to your computer and use it in GitHub Desktop.
pathfinder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Input | |
def initialize(name = 'input.txt', lines = rand(10..20)) | |
File.open(name, 'w+') do |file| | |
lines.times do |i| | |
file.puts (0..i).map { rand(-50..50) }.join(' ') | |
end | |
end | |
end | |
end | |
class Pathfinder | |
attr_reader :filename, :matrix | |
def initialize(filename) | |
@filename, @matrix = filename, {} | |
File.open(filename, 'r').each.with_index do |line, index| | |
@matrix[index] = line.split(/\s/).map(&:to_i) | |
end | |
end | |
def path | |
@path ||= begin | |
offset = 0 | |
matrix.inject([]) do |path, (line, cortege)| | |
maximum = nil | |
maximum_index = 0 | |
cortege[ offset .. offset + 1 ].each.with_index do |element, column| | |
if maximum != (maximum = maximum && [ maximum, element ].max || element) | |
maximum_index = column + offset | |
end | |
end | |
path << [ line, offset = maximum_index ] | |
end | |
end | |
end | |
def to_s | |
@to_s ||= begin | |
matrix.map do |line, cortege| | |
point = path[line] | |
cortege.map.with_index do |element, index| | |
cell = element.to_s.rjust(3) | |
point.last == index ? "\033[41m#{cell}\033[0m" : cell | |
end.join(' ') | |
end.join("\n") | |
end | |
end | |
end | |
Input.new | |
puts Pathfinder.new('input.txt') |
это ruby 1.9 +
поставил с некоторыми заморочками ruby 1.9.3 на мак Lion, но все равно не компилируеся — ругается, что не может range конвертировать
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Не компилируется:
dimko1.rb:7: warning: don't put space before argument parentheses
dimko1.rb:4:in
rand': can't convert Range into Integer (TypeError) from dimko1.rb:4:in
initialize'from dimko1.rb:51:in `new'
from dimko1.rb:51