【问题标题】:Improve Efficiency in Array comparison in Ruby提高 Ruby 中数组比较的效率
【发布时间】:2013-11-12 21:05:31
【问题描述】:

您好,我正在研究 Ruby /cucumber,并且需要开发一个比较模块/程序来比较两个文件。

以下是要求

  1. 该项目是一个迁移项目。一个应用程序中的数据被移动到另一个应用程序

  2. 需要将现有应用程序的数据与新应用程序的数据进行比较。

解决方案:

针对上述要求,我已经在 Ruby 中开发了一个比较引擎。

a) 从两个数据库中获取数据、去重和排序 b) 将数据放入带有“||”的文本文件中作为分隔符 c) 使用在 db 中提供唯一记录的键列(数字)来比较两个文件

例如 File1 有 1,2,3,4,5,6,file2 有 1,2,3,4,5,7 列 1,2,3,4,5 是关键列。我使用这些键列并比较导致失败的 6 和 7。

问题:

我们在这里面临的主要问题是,如果 100,000 条或更多记录的不匹配率超过 70%,则比较时间会很长。 如果不匹配小于 40%,则比较时间是可以的。

Diff 和 Diff -LCS 在这种情况下不起作用,因为我们需要关键列才能在两个应用程序之间进行准确的数据比较。

如果 100,000 条或更多记录的不匹配率超过 70%,是否有任何其他方法可以有效地减少时间。

谢谢

【问题讨论】:

  • 是的,使用 Hash 对象,直接访问,不需要遍历每个数组来确定元素的唯一性 ;) -- 另外,你能提供一个更好的例子吗?具体的东西会很棒
  • 程序只有在有很多不匹配时才会变慢的事实可能表明性能损失实际上发生在不匹配的后处理中,而不是实际匹配本身。

标签: ruby-on-rails ruby rubygems


【解决方案1】:

假设您的 2 个文件中有此摘录:

# File 1
id | 1 | 2 | 3
--------------
 1 | A | B | C
 2 | B | A | C

# File 2
id | 1 | 2 | 3
--------------
 8 | A | B | C
 9 | B | B | B

我们执行以下功能,使用哈希(直接访问):

def compare(data_1, data_2)
  headers = data_1.shift
  if headers.size != data_2.shift.size
    return "Headers are not the same!"
  end

  hash = {}
  number_of_columns = headers.size
  data_1.map do |row|
    key = ''
    number_of_columns.times do |index|
      key << row[index].to_s
    end
    hash[key] ||= row
  end

  data_2.each do |row|
    key = ''
    number_of_columns.times do |index|
      key << row[index].to_s
    end
    if hash[key].nil?
      # present in file 1 but not in file 2
    else
      # present in both files
    end
  end
end

# usage
data_file_1 = your_method_to_read_the_file(file_1)
data_file_2 = your_method_to_read_the_file(file_2)

compare(data_file_1, data_file_2)

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 2011-06-23
    • 2020-01-30
    • 2020-08-09
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2012-03-17
    相关资源
    最近更新 更多