Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function that takes two values, lets f(x,y) == f(y,x), and the output is otherwise unique?

I am wondering if there is a way to generate a key based on the relationship between two entities in a way that the key for relationship a->b is the same as the key for relationship b->a.

Desirably this would be a hash function which takes either relationship member but generates the same output regardless of the order the members are presented in.

Obviously you could do this with numbers (e.g. add(2,3) is equivalent to add(3,2)). The problem for me is that I do not want add(1,4) to equal add(2,3). Obviously any hash function has overlap but I mean a weak sense of uniqueness.

My naive (and performance undesirable) thought is:

function orderIndifferentHash(string val1, string val2)
{
  return stringMerge(hash(val1), hash(val2));
  /* String merge will 'add' each character (with wrapping).
     The pre-hash is to lengthen strings to at least 32 characters */
}
like image 524
Matt Mitchell Avatar asked Dec 13 '22 19:12

Matt Mitchell


1 Answers

In your function orderIndifferentHash you could first order val1 and val2 by some criteria and then apply any hash function you like to get the result.

function orderIndifferentHash( val1, val2 ) {
  if( val1 < val2 ) {
    first = val1
    second = val2
  }
  else {
    first = val2
    second = val1
  }
  hashInput = concat( first, second )
  return someHash( hashInput )

  // or as an alternative:
  // return concat( someHash( first ), someHash( second ) )
}
like image 127
tangens Avatar answered May 22 '23 03:05

tangens