本文整理汇总了C#中HashSet.Remove方法的典型用法代码示例。如果您正苦于以下问题:C# HashSet.Remove方法的具体用法?C# HashSet.Remove怎么用?C# HashSet.Remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HashSet
的用法示例。
在下文中一共展示了HashSet.Remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LongestConsecutiveSolution
public int LongestConsecutiveSolution(int[] nums)
{
int length = nums.Length;
HashSet<int> set = new HashSet<int>();
int max=0;
foreach(int cur in nums)
set.Add(cur);
foreach (int cur in nums)
{
int len=1;
int left = cur - 1;
int right = cur + 1;
while (set.Contains(left))
{
len++;
set.Remove(left);
left--;
}
while (set.Contains(right))
{
len++;
set.Remove(left);
right++;
}
max = max > len ? max : len;
}
return max;
}
示例2: drawCodeGenerators
static void drawCodeGenerators(CodeGeneratorConfig codeGeneratorConfig, Type[] codeGenerators)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Code Generators", EditorStyles.boldLabel);
var enabledCodeGenerators = new HashSet<string>(codeGeneratorConfig.enabledCodeGenerators);
var availableGeneratorNames = new HashSet<string>();
foreach (var codeGenerator in codeGenerators) {
availableGeneratorNames.Add(codeGenerator.Name);
var isEnabled = enabledCodeGenerators.Contains(codeGenerator.Name);
isEnabled = EditorGUILayout.Toggle(codeGenerator.Name, isEnabled);
if (isEnabled) {
enabledCodeGenerators.Add(codeGenerator.Name);
} else {
enabledCodeGenerators.Remove(codeGenerator.Name);
}
}
foreach (var generatorName in codeGeneratorConfig.enabledCodeGenerators.ToArray()) {
if (!availableGeneratorNames.Contains(generatorName)) {
enabledCodeGenerators.Remove(generatorName);
}
}
var sortedCodeGenerators = enabledCodeGenerators.ToArray();
Array.Sort(sortedCodeGenerators);
codeGeneratorConfig.enabledCodeGenerators = sortedCodeGenerators;
}
示例3: LongestConsecutiveSequenceLength
/// <summary>
/// Find Longest Consequitive Sequence
/// </summary>
/// <param name="arr">Source Array</param>
/// <returns>Length of longest consecutive numbers</returns>
public static int LongestConsecutiveSequenceLength(int[] arr)
{
HashSet<int> allElements = new HashSet<int>(arr);
int maxConsecutiveLength = 1;
while (allElements.Count > 0)
{
int firstValue = allElements.First();
int leftElement = firstValue;
int currentLength = 1;
while (allElements.Contains(leftElement - 1))
{
allElements.Remove(leftElement - 1);
leftElement--;
currentLength++;
}
int rightElement = firstValue;
while (allElements.Contains(rightElement + 1))
{
allElements.Remove(rightElement + 1);
rightElement++;
currentLength++;
}
if (currentLength > maxConsecutiveLength)
{
maxConsecutiveLength = currentLength;
}
allElements.Remove(firstValue);
}
return maxConsecutiveLength;
}
示例4: LongestConsecutive
public int LongestConsecutive(int[] num)
{
HashSet<int> hset = new HashSet<int>(num);
int answer = 1;
for (int i = 0; i < num.Length; i++)
{
int current = num[i];
if (hset.Remove(current))
{
int tmp = 1;
int higher = current +1;
while (hset.Remove(higher++))
{
tmp++;
}
int lower = current - 1;
while (hset.Remove(lower--))
{
tmp++;
}
answer = Math.Max(answer, tmp);
}
}
return answer;
}
示例5: AddRemove
public void AddRemove()
{
var set = new HashSet<int>();
foreach (int item in Enumerable.Range(100, 100))
{
bool added = set.Add(item);
Assert.IsTrue(added);
}
Assert.AreEqual(100, set.Count);
Assert.IsFalse(set.Add(120));
foreach (int item in Enumerable.Range(120, 20))
{
bool removed = set.Remove(item);
Assert.IsTrue(removed);
}
Assert.AreEqual(80, set.Count);
Assert.IsFalse(set.Remove(120));
foreach (int item in Enumerable.Range(100, 200))
set.Add(item);
Assert.AreEqual(200, set.Count);
}
示例6: LongestConsecutive
public int LongestConsecutive(int[] num)
{
int max = 0;
HashSet<int> hashSet = new HashSet<int>(num);
foreach (int val in num)
{
if (hashSet.Remove(val))
{
int tempResult = 1;
int upperVal = val + 1;
while (hashSet.Remove(upperVal++))
{
tempResult++;
}
int lowerVal = val - 1;
while (hashSet.Remove(lowerVal--))
{
tempResult++;
}
max = Math.Max(max, tempResult);
}
}
return max;
}
示例7: FindBest
public int[] FindBest()
{
var remaining = new HashSet<Point>(_cities);
var first = remaining.First();
var route = new List<Point> { first };
remaining.Remove(first);
var numericRoute = new List<int>{_cities.IndexOf(first)};
var distance = 0.0d;
while (remaining.Any())
{
var shortest = double.MaxValue;
Point next = null;
foreach (var p in remaining)
{
var d = Distance(route.Last(), p);
if (d < shortest)
{
shortest = d;
next = p;
}
}
route.Add(next);
numericRoute.Add(_cities.IndexOf(next));
remaining.Remove(next);
distance += shortest;
}
distance += Distance(route.First(), route.Last());
Console.WriteLine("Distance calculated in closestneighbour: " + distance);
return numericRoute.ToArray();
}
示例8: Cluster
/// <summary>
/// Starts the clustering.
/// </summary>
/// <param name="elements"></param>
/// <param name="fusion"></param>
/// <param name="metric"></param>
/// <returns></returns>
protected internal Cluster[] Cluster(List<Element> elements, Fusion fusion, IDistanceMetric metric)
{
HashSet<Cluster> clusters = new HashSet<Cluster>();
ClusterPairs pairs = new ClusterPairs();
// 1. Initialize each element as a cluster
foreach (Element el in elements)
{
Cluster cl = new Cluster(fusion);
cl.AddElement(el);
clusters.Add(cl);
}
// 2. a) Calculate the distances of all clusters to all other clusters
foreach (Cluster cl1 in clusters)
{
foreach (Cluster cl2 in clusters)
{
if (cl1 == cl2)
continue;
ClusterPair pair = new ClusterPair(cl1, cl2, cl1.CalculateDistance(cl2));
pairs.AddPair(pair);
}
}
// 2. b) Initialize the pair with the lowest distance to each other.
ClusterPair lowestDistancePair = pairs.LowestDistancePair;
// 3. Merge clusters to new clusters and recalculate distances in a loop until there are only countCluster clusters
while (!isFinished(clusters, lowestDistancePair))
{
// a) Merge: Create a new cluster and add the elements of the two old clusters
lowestDistancePair = pairs.LowestDistancePair;
Cluster newCluster = new Cluster(fusion);
newCluster.AddElements(lowestDistancePair.Cluster1.GetElements());
newCluster.AddElements(lowestDistancePair.Cluster2.GetElements());
// b)Remove the two old clusters from clusters
clusters.Remove(lowestDistancePair.Cluster1);
clusters.Remove(lowestDistancePair.Cluster2);
// c) Remove the two old clusters from pairs
pairs.RemovePairsByOldClusters(lowestDistancePair.Cluster1, lowestDistancePair.Cluster2);
// d) Calculate the distance of the new cluster to all other clusters and save each as pair
foreach (Cluster cluster in clusters)
{
ClusterPair pair = new ClusterPair(cluster, newCluster, cluster.CalculateDistance(newCluster));
pairs.AddPair(pair);
}
// e) Add the new cluster to clusters
clusters.Add(newCluster);
}
return clusters.ToArray<Cluster>();
}
示例9: LengthOfLongestSubstring
public int LengthOfLongestSubstring(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
char[] sArrays = s.ToCharArray();
int backPointer = 0;
int result = 0;
HashSet<char> hs = new HashSet<char>();
for (int frontPointer = 0; frontPointer < s.Length; )
{
while (frontPointer < s.Length && !hs.Contains(sArrays[frontPointer]))
{
hs.Add(sArrays[frontPointer++]);
}
result = Math.Max(result, frontPointer - backPointer);
while (frontPointer < s.Length && sArrays[backPointer] != sArrays[frontPointer])
{
hs.Remove(sArrays[backPointer++]);
}
if (backPointer <= frontPointer && backPointer < s.Length)
{
hs.Remove(sArrays[backPointer++]);
}
}
return result;
}
示例10: FindFreeVariablesInLambda
// HACK: HashSet parameter is ugly
public static IEnumerable<string> FindFreeVariablesInLambda(IEnumerable<string> parameters, IEnumerable<object> body, HashSet<string> localVariablesDefinedInLambda)
{
HashSet<string> accessedVariables = new HashSet<string>();
foreach (object o in body) FindAccessedVariables(o, accessedVariables, localVariablesDefinedInLambda);
accessedVariables.Remove("nil");
foreach (string p in parameters) accessedVariables.Remove(p);
foreach (string i in localVariablesDefinedInLambda) accessedVariables.Remove(i);
return accessedVariables;
}
示例11: FindPath
public Node[] FindPath()
{
HashSet<Node> open = new HashSet<Node>();
HashSet<Node> closed = new HashSet<Node>();
Node current = start;
current.G = 0;
Node destination = finish;
current.F = HeuristicCost(current, destination);
open.Add(current);
while (open.Count != 0)
{
current = Lowest_f(open);
if (current.Equals(destination))
{
if (current.previous != null)
{
return Path(current, start);
}
}
open.Remove(current);
closed.Add(current);
foreach (Node node in GetNeighbours(current))
{
double t = current.G + Distance(current, node);
if (t < node.G)
{
if (open.Contains(node))
{
open.Remove(node);
}
if (closed.Contains(node))
{
closed.Remove(node);
}
}
if (!open.Contains(node) && !(closed.Contains(node)))
{
node.G = t;
node.F = HeuristicCost(node, destination);
node.previous = current;
open.Add(node);
}
}
}
return null;
}
示例12: Main
internal static void Main()
{
string decorationLine = new string('-', Console.WindowWidth);
Console.Write(decorationLine);
Console.WriteLine("***Presenting the functionality of the data structure 'Hash set'***");
Console.Write(decorationLine);
HashSet<int> years = new HashSet<int>();
Console.WriteLine("---Add operation---");
years.Add(1990);
years.Add(1992);
years.Add(2013);
years.Add(2016);
years.Add(2022);
Console.WriteLine("Count = " + years.Count);
Console.WriteLine();
Console.WriteLine("---Iterator functionality---");
PrintYears(years);
Console.WriteLine();
Console.WriteLine("---Contains operation---");
Console.WriteLine("Does years set contain {0}? - {1}", 1992, years.Contains(1992));
Console.WriteLine("Does years set contain {0}? - {1}", 2012, years.Contains(2012));
Console.WriteLine();
Console.WriteLine("---Remove operation---");
Console.WriteLine("Is {0} removed from years set? - {1}", 1996, years.Remove(1996));
Console.WriteLine("Years set count: " + years.Count);
Console.WriteLine("Is {0} removed from years set? - {1}", 1990, years.Remove(1990));
Console.WriteLine("Years set count: " + years.Count);
Console.WriteLine();
Console.WriteLine("---UnionWith operation---");
int[] yearsToUnionWith = new int[] { 2005, 2009, 2021, 2016, 1992, 2013 };
years.UnionWith(yearsToUnionWith);
Console.WriteLine("All years after a union with: {0}", string.Join(", ", yearsToUnionWith));
PrintYears(years);
Console.WriteLine("Years set count: " + years.Count);
Console.WriteLine();
Console.WriteLine("---IntersectWith operation---");
int[] yearsToIntersectWith = new int[] { 2045, 2025, 2021, 2016, 1999, 2017, 2013 };
years.IntersectWith(yearsToIntersectWith);
Console.WriteLine("All years after an intersect with: {0}", string.Join(", ", yearsToIntersectWith));
PrintYears(years);
Console.WriteLine("Years set count: " + years.Count);
Console.WriteLine();
Console.WriteLine("---Clear operation---");
years.Clear();
Console.WriteLine("Years count after clearing: " + years.Count);
}
示例13: AppMetadata
private AppMetadata(string json)
{
JsonValue data;
try
{
data = JsonValue.Parse(json);
}
catch (FormatException e)
{
MessageBox.Show("Apparently the metadata contains an error. Sorry about that! Please try again in a minute.\n\nThe error is: " + e.Message, "Error in apps.json", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(1);
return;
}
if ((int) data["version"] != 1)
{
MessageBox.Show("This version of Steam Disk Saver is too old. The metadata uses format " + data["version"] + ", but this version only supports format 1. Please download the latest version.", "Outdated version", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Environment.Exit(0);
}
foreach (var item in data["categories"])
{
Categories.Add(new Category(item.Key, item.Value));
}
var engines = data["engines"];
foreach (var item in data["apps"])
{
var id = int.Parse(item.Key);
var app = item.Value;
Known.Add(id);
var categoriesInApp = new HashSet<string>();
foreach (var cat in app)
{
categoriesInApp.Add(cat.Key);
}
categoriesInApp.Remove("engine");
foreach (var cat in Categories)
{
categoriesInApp.Remove(cat.Key);
cat.AddApp(id, app, engines);
}
foreach (var cat in categoriesInApp)
{
Debug.WriteLine("Unknown category {0} in {1}", cat, id);
}
}
}
示例14: DetermineValidOptionsForSquare
// Method establishes which values can fill an empty square by eliminating any values already occurring in row/column/box.
public List<int> DetermineValidOptionsForSquare(SquareCoordinate squareCoordinate, IImmutableSudokuGrid grid)
{
HashSet<int> validSquareOptions = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int offset = 1; offset < 9; offset++)
{
validSquareOptions.Remove(grid.Elements[(squareCoordinate.Row + offset) % 9, squareCoordinate.Column]);
validSquareOptions.Remove(grid.Elements[(squareCoordinate.Row), (squareCoordinate.Column + offset) % 9]);
validSquareOptions.Remove(grid.Elements[(3 * (squareCoordinate.Row / 3)) + offset % 3, (3 * (squareCoordinate.Column / 3)) + (offset - offset % 3) / 3]);
}
return validSquareOptions.ToList<int>();
}
示例15: RequestExhangeCards
public override Card[] RequestExhangeCards()
{
List<Card> retCards = new List<Card>();
//arrange he cards by suits
List<Card>[] suitsCount = ArrangeCardBySuits(Cards);
//look at each suit which has 2 cards or less and add those cards to the returned array
foreach (List<Card> suit in suitsCount)
{
if (suit.Count <= 2)
{
retCards.AddRange(suit);
suit.Clear();
}
}
//see how many cards are in the returned array
if (retCards.Count == 3)
{
return retCards.ToArray();
}
else if (retCards.Count > 3)
{
//find lowest card and throw away
while (retCards.Count > 3)
{
//remove the card with the lowest value - till we have only 3 cards left
Card current = GetLowestCardInCollection(retCards);
retCards.Remove(current);
}
}
else if (retCards.Count < 3)
{
//copy cards for operation & remove cards already picked from that collection
ICollection<Card> cards_cpy = new HashSet<Card>(Cards);
foreach (Card c in retCards)
{
cards_cpy.Remove(c);
}
//add highest card in my hand to return array - till I have 3 cards
while (retCards.Count < 3)
{
Card current = GetHighestCardInCollection(cards_cpy);
retCards.Add(current);
cards_cpy.Remove(current);
}
}
return retCards.ToArray();
}