module GreenWater

Constants

VERSION

Public Class Methods

diff!(argv) click to toggle source
# File lib/green_water.rb, line 5
def diff!(argv)
  validate!(argv)
  a_file1, a_file2 = argv.collect{|f| read_array(f)}
  lcs_diff_data = raw_diff(lcs(a_file1, a_file2), a_file1, a_file2, a_file1.length, a_file2.length)
  print_formatter(lcs_diff_data).each{|f| puts f.join(' ')}
end
lcs(x, y) click to toggle source
# File lib/green_water.rb, line 98
def lcs(x, y)
  x_len = x.size
  y_len = y.size
  c = Array.new(x_len){Array.new(y_len){0}}

  x_len.times do |i|
    y_len.times do |j|
      if x[i] == y[j]
        c[i][j] = (i==0 || j==0) ? 1: (1 + c[i-1][j-1])
      else
        if i==0 && j==0
          c[i][j] = 0
        elsif i==0 && j!=0
          c[i][j] = [0,  c[i][j-1]].max
        elsif j==0 && i!=0
          c[i][j] = [0, c[i-1][j]].max
        elsif i != 0 && j != 0
          c[i][j] = [c[i-1][j], c[i][j-1]].max
        end
      end
    end
  end

  return c
end
print_formatter(r) click to toggle source
raw_diff(c, x, y, i, j, r=[]) click to toggle source
# File lib/green_water.rb, line 82
def raw_diff(c, x, y, i, j, r=[])
  if i > 0 && j > 0 && x[i-1] == y[j-1]
    raw_diff(c, x, y, i-1, j-1, r)
    r << [nil, x[i-1]]
  else
    if j > 0 && (i == 0 or c[i-1][j-2] >= c[i-2][j-1])
      raw_diff(c, x, y, i, j-1, r)
      r << [true, y[j-1]]
    elsif i > 0 && (j == 0 or c[i-1][j-2] < c[i-2][j-1])
      raw_diff(c, x, y, i-1, j, r)
      r << [false, x[i-1]]
    end
  end
  return r
end
read_array(file) click to toggle source
# File lib/green_water.rb, line 21
def read_array(file)
  array_line = []  
  File.foreach( file ) do |line|
    array_line.push line
  end
  return array_line
end
validate!(argv) click to toggle source
# File lib/green_water.rb, line 12
def validate!(argv)
  abort("Wrong number of arguments: expected - 2, got - #{argv.size}") unless argv.size == 2
  argv.each do |file|
    puts file.inspect
    abort("File #{file} doesnt exists!") unless File.exist?(file)
  end
  return true
end