我正在生成随机脚本,但我必须保证每个新脚本都是唯一的(以前没有重复过)。所以基本上每个已经生成的脚本都会与每个新脚本进行比较。
我认为必须有一种方法来散列每个新脚本,而不是仅仅使用普通的字符串比较,这样比较会更快。
关于如何散列字符串以更快地进行多重比较的任何想法?
一种方法是使用HashSet<String>
HashSet 类提供高性能的集合操作。集合是不包含重复元素且其元素没有特定顺序的集合。
HashSet<string> scripts = new HashSet<string>();
string generated_script = "some_text";
if (!scripts.Contains(generated_script)) // is HashSet<String> dont contains your string already then you can add it
{
scripts.Add(generated_script);
}
此外,您可以检查duplicate items
数组中是否存在。但这可能不是很有效HashSet<String>
string[] array = new[] {"demo", "demo", "demo"};
string compareWith = "demo";
int duplicates_count = array.GroupBy(x => x).Count(g => g.Count() > 1);
像下面这样使用 HashSet
string uniqueCode= "ABC";
string uniqueCode1 = "XYZ";
string uniqueCode2 = "ABC";
HashSet<string> uniqueList = new HashSet<string>();
uniqueList.Add(uniqueCode);
uniqueList.Add(uniqueCode1);
uniqueList.Add(uniqueCode2);
如果您看到唯一列表的计数,您将是 2。所以 ABC 不会出现两次。
您可以使用 HashSet。保证哈希集永远不会包含重复项
将脚本与其哈希一起存储:
class ScriptData
{
public ScriptData(string script)
{
this.ScriptHash=script.GetHashCode();
this.Script=script;
}
public int ScriptHash{get;private set;}
public string Script{get;private set;}
}
然后,每当您需要检查您的新随机脚本是否唯一时,只需获取新脚本的哈希码并在所有ScriptData
实例中搜索具有相同哈希码的任何实例。如果你没有找到任何你知道你的新随机脚本是独一无二的。如果您确实找到了一些,那么它们可能是相同的,您必须比较脚本的实际文本以查看它们是否相同。
您可以将每个生成的存储string
在HashSet中。
对于每个新字符串,您将调用Contains
以 O(1) 复杂度运行的方法。这是确定新生成的字符串是否之前生成的简单方法。