ruby - 使用一对值作为键

标签 ruby algorithm hash time-complexity

我经常需要散列一对值。通常,我只生成 num1 和 num2 之间的范围并将其散列为键,但这非常慢,因为这两个数字之间的距离可能非常大。

如何将一对值散列到表中?例如,假设我正在遍历一个数组,并希望将每对可能的值散列到散列表中,其中键是 nums 对,值是它们的总和。执行此操作的有效方法是什么?我也考虑过将一个数组散列为键,但这行不通。

此外,如何将其扩展到 3、4 或 5 个数字?

编辑: 我指的是哈希表中 O(1) 查找的哈希。

最佳答案

就去做吧。

你可以简单地在数组上散列...

验证

让我展示一个小实验:

array = [ [1,2], [3,4], ["a", "b"], ["c", 5] ]

hash = {}

array.each do |e|
  e2 = e.clone

  e << "dummy"
  e2 << "dummy"

  hash[e] = (hash[e] || 0) + 1 

  hash[e2] = (hash[e2] || 0) + 1

  puts "e == e2: #{(e==e2).inspect}, e.id = #{e.object_id}, e.hash = #{e.hash}, e2.id = #{e2.object_id}, e2.hash = #{e2.hash}"
end

puts  hash.inspect
    

如你所见,我拿了几个数组,克隆它们,分别修改它们;在此之后,我们确定 ee2 是不同的数组(即不同的对象 ID);但它们包含相同的元素。之后,将两个不同的数组用作散列键;由于它们具有相同的内容,因此被散列在一起。

e == e2: true, e.id = 19797864, e.hash = -769884714, e2.id = 19797756, e2.hash = -769884714
e == e2: true, e.id = 19797852, e.hash = -642596098, e2.id = 19797588, e2.hash = -642596098
e == e2: true, e.id = 19797816, e.hash = 104945655, e2.id = 19797468, e2.hash = 104945655
e == e2: true, e.id = 19797792, e.hash = -804444135, e2.id = 19797348, e2.hash = -804444135
{[1, 2, "dummy"]=>2, [3, 4, "dummy"]=>2, ["a", "b", "dummy"]=>2, ["c", 5, "dummy"]=>2}

如您所见,您不仅可以将数组用作键,而且它还可以将它们识别为“相同”(而不是一些奇怪的对象标识,它也可能是)。

警告

显然这只在一定程度上有效。数组的内容 必须递归地明确定义哈希。即,您可以使用正常的东西,例如字符串、数字、其他数组,甚至可以在其中使用 nil

引用

来自 http://ruby-doc.org/core-2.4.0/Hash.html :

Two objects refer to the same hash key when their hash value is identical and the two objects are eql? to each other.

来自 http://ruby-doc.org/core-2.4.0/Array.html#method-i-eql-3F :

eql?(other) → true or false

Returns true if self and other are the same object, or are both arrays with the same content (according to Object#eql?).

hash → integer

Compute a hash-code for this array.

Two arrays with the same content will have the same hash code (and will compare using eql?).

强调我的。

关于ruby - 使用一对值作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401877/

相关文章:

algorithm - 这种将坐标映射到数字的算法叫什么?

javascript - 在 Javascript 中对图像进行哈希处理

c# - 使用 MD5 或 sha-256 C# 散列密码

algorithm - 我什么时候应该重新哈希整个哈希表?

ruby-on-rails - rails : I would like to apply a totally custom search to activerecord - is Rails fast enough?

c# - 是否有任何算法可以根据某些模式对数组进行分类?

ruby-on-rails - Rails ActiveResource 检测 HTTP 206 响应代码

r - 将转录矩阵转换为基因矩阵的任何智能解决方案?

ruby - 正确的设计 : Including module in ActiveRecord or helper method

ruby - 是否有日志可以查看来自 bundler 的 git 命令?