Tyler Murry
Tyler Murry

Reputation: 2815

Unique Value for Two Strings

This seems like a fairly simple problem, but the solution is eluding me:

If I have the following two strings:

string str1 = "Ping";
string str2 = "Pong";

I'm needing an algorithm to create a unique value for the two strings, no matter what order they are in. For example:

UniqueValue(str1, str2) and UniqueValue(str2, str1) should return the exact same value.

EDIT: UniqueValue returns a string. I understand it won't be "truly" unique, but a hash-like value will work.

Thanks, Tyler

Upvotes: 0

Views: 595

Answers (5)

agent-j
agent-j

Reputation: 27953

You can Xor the hashcodes.

static string UniqueValue (string str1, string str2)
{
   return (str1.GetHashCode () ^ str2.GetHashCode()).ToString ();
}

Edit: Or, you can generate this string:

if (str2 > str1)
   return str1+str2;
return str2+str1;

Upvotes: 3

Justin Simon
Justin Simon

Reputation: 1133

Sort the strings.

Convert / to // and ; to /; in each of the strings.

Concatenate the strings, putting a ; between each.

Upvotes: 7

Andrew
Andrew

Reputation: 14457

public int UniqueValue(params string[] strings)
{
    return String.Join("~", strings.AsEnumerable<string>()
                                   .OrderBy<string, string>(s => s)
                                   .ToArray<string>())
                 .GetHashCode();
}

This, of course, is provided that you don't need complete uniqueness and that a hash code is good enough.

Upvotes: 0

Chris Laplante
Chris Laplante

Reputation: 29668

I would hash them with SHA1: http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx

To determine in which orientation they should be in when concatenated, use String.CompareTo: http://msdn.microsoft.com/en-us/library/system.string.compareto.aspx.

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67355

I would use some sort of hash, but I don't see any algorithm that would produce a 100% guaranteed unique string that could never be duplicated by any other two strings.

Upvotes: 0

Related Questions