繁体   English   中英

提高Ruby中数组比较的效率

[英]Improve Efficiency in Array comparison in Ruby

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

以下是要求

  1. 该项目是一个迁移项目。 来自一个应用程序的数据被移至另一个

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

解决方案:

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

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

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

问题 :

我们在这里面临的主要问题是,如果10万条记录的不匹配率超过70%,那么比较时间就很大。 如果不匹配小于40%,则比较时间就可以了。

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

如果不匹配超过100,000条记录的70%,还有其他方法可以有效地减少时间。

谢谢

假设您在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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM