Skip to content

Instantly share code, notes, and snippets.

@dmeremyanin
Created December 6, 2011 11:33
Show Gist options
  • Save dmeremyanin/1437878 to your computer and use it in GitHub Desktop.
Save dmeremyanin/1437878 to your computer and use it in GitHub Desktop.
pathfinder
#!/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')
@gchesakov
Copy link

поставил с некоторыми заморочками ruby 1.9.3 на мак Lion, но все равно не компилируеся — ругается, что не может range конвертировать

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment