0

我正在生成随机脚本,但我必须保证每个新脚本都是唯一的(以前没有重复过)。所以基本上每个已经生成的脚本都会与每个新脚本进行比较。

我认为必须有一种方法来散列每个新脚本,而不是仅仅使用普通的字符串比较,这样比较会更快。

关于如何散列字符串以更快地进行多重比较的任何想法?

4

5 回答 5

1

一种方法是使用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);
于 2013-03-05T11:06:54.827 回答
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 不会出现两次。

于 2013-03-05T11:12:59.973 回答
0

您可以使用 HashSet。保证哈希集永远不会包含重复项

于 2013-03-05T11:08:00.473 回答
0

将脚本与其哈希一起存储:

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实例中搜索具有相同哈希码的任何实例。如果你没有找到任何你知道你的新随机脚本是独一无二的。如果您确实找到了一些,那么它们可能是相同的,您必须比较脚本的实际文本以查看它们是否相同。

于 2013-03-05T11:09:55.367 回答
0

您可以将每个生成的存储stringHashSet中。

对于每个新字符串,您将调用Contains以 O(1) 复杂度运行的方法。这是确定新生成的字符串是否之前生成的简单方法。

于 2013-03-05T11:10:08.117 回答