【问题标题】:Create a unique string given 2 parameters regardless of order无论顺序如何,给定 2 个参数,创建一个唯一字符串
【发布时间】:2014-02-02 19:45:15
【问题描述】:

我正在寻找一个看起来像的函数

$hash = someFunction($value1,$value2);

哈希值根据值是唯一的,但是,无论参数的顺序如何,它都应该返回相同的哈希值。所以 (3,5) 将返回与 (5,3) 相同的哈希值。

有这样的已知算法吗?

为了给出我想要实现的目标的上下文,在我的数据库中,我有一个表表示 user1 和 user2 之间的消息,其中包含一对列 user1、user2。无论顺序如何,我都想 GROUP BY 对。意思是,我想查看 2 个用户之间的完整对话。

我在想,如果我可以在表格中添加一个标识唯一对的字符串,那会让我的生活更轻松。

【问题讨论】:

  • 只是一个想法:比较两个参数并始终以相同的顺序执行您的功能会有多好。例如 hash(5,3),制定一个方案,使其始终将 hash(3,5) 转换为 hash(5,3),或者始终将 hash(4,5) 转换为 hash(5,4) ?
  • 但是我怎么知道哪个是哪个?
  • 检查我的答案@Nathan

标签: php mysql uniqueidentifier


【解决方案1】:

先对$value1$value2 进行排序,将它们连接起来,然后使用任何已知的哈希算法怎么样?

【讨论】:

  • 我用过sha1( min($value1,$value2) . '-' . max($value1,$value2) )
  • ($values 总是整数)
【解决方案2】:

好吧,我会这样做(假设两个参数的数据类型相同)

function someFunc($val1, $val2){
  if($val1>$val2){
    $val3 = $val2;
    $val2 = $val1;
    $val1 = $val3;
  }
  //if the params are string, compare the length of string and assign $val1 with the greater length, and $val2 with smaller
  //if the length of strings are equal, compare the string and assign $val1 with the string that comes ahead alphabetically,
  //if both strings are identical, you can not-care about the order of params.

//Do whatever you would like to do
}

现在即使你像这样调用函数

someFunc(5,3)

params 的值会自动交换,使调用与

someFunc(3,5)

同样的道理也适用于字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    相关资源
    最近更新 更多