<< 前 ホーム 次 >>

bakaid: 200710191

class Bag
  def initialize
    @hashs = [{}]
  end

  def [](key)
    results = []
    @hashs.each{|h| h.has_key?(key) and results << h[key]}
    return results
  end

  def []=(key, value)
    @hashs.each do |h|
      if h.has_key?(key)
        h[key] == value and return value
      else
        h[key] = value
        return value
      end
    end
    h = {}
    h[key] = value
    @hashs << h
    return value
  end

  def values
    results = @hashs.map{|h| h.values}
    results.flatten!
    return results
  end
end

class Uline
  def initialize(pos, line)
    @pos = pos
    @size = line.size
    @code = line.hash
  end
  attr_reader :pos, :size, :code

  def uniq?(input, ulines, line)
    founds = ulines[@code]
    founds.empty? and return true
    curr = input.tell
    begin
      founds.each{|f| f.readline(input) == line and return false}
      return true
    ensure
      input.seek(curr)
    end
  end

  def readline(input)
    input.seek(@pos)
    return input.read(@size)
  end
end

def uniq_read(input)
  ulines = Bag.new
  loop do
    pos = input.tell
    line = input.gets
    !line and break
    newline = Uline.new(pos, line)
    !newline.uniq?(input, ulines, line) and next
    ulines[newline.code] = newline
  end
  return ulines
end

def uniq_write(input, ulines)
  input.seek(0)
  lines = ulines.values
  lines.sort!{|a, b| a.pos <=> b.pos}
  lines.each{|uline| print(uline.readline(input))}
end

File.open(ARGV[0]) do |input|
  ulines = uniq_read(input)
  uniq_write(input, ulines)
end

本家Permlink

<< 前 ホーム 次 >>


Copyright © 1905 tko at jitu.org

バカが征く on Rails