本文整理汇总了C#中SortedSet.First方法的典型用法代码示例。如果您正苦于以下问题:C# SortedSet.First方法的具体用法?C# SortedSet.First怎么用?C# SortedSet.First使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SortedSet
的用法示例。
在下文中一共展示了SortedSet.First方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main()
{
int tasksCount = int.Parse(Console.ReadLine());
var tasks = new SortedSet<Task>();
for (int i = 0; i < tasksCount; i++)
{
string[] commandComponents = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string commandName = commandComponents[0].ToLower();
int taskComplexity = 0;
string taskName = string.Empty;
if (commandComponents.Length > 1)
{
taskComplexity = int.Parse(commandComponents[1]);
taskName = commandComponents[2];
}
switch (commandName)
{
case "new":
{
tasks.Add(new Task
{
Complexity = taskComplexity,
Name = taskName
});
break;
}
case "solve":
{
if (tasks.Count == 0)
{
Console.WriteLine("Rest");
break;
}
Console.WriteLine($"{tasks.First().Complexity} - {tasks.First().Name}");
tasks.Remove(tasks.First());
break;
}
default:
break;
}
}
}
示例2: Load
/// <summary>
/// FanIn
/// </summary>
public IEnumerable<Activity> Load(ActivityStream stream, ActivityStreamOptions feedOptions)
{
// At this point we have all the streams with their timestamp
Dictionary<byte[], long> streamsToLoad = new StreamCrawler(streamStore).StreamsToLoad(stream, feedOptions.Paging.Timestamp);
Dictionary<string, DateTime> debug = streamsToLoad.ToDictionary(key => Encoding.UTF8.GetString(key.Key), val => DateTime.FromFileTimeUtc(val.Value));
feedOptions = feedOptions ?? ActivityStreamOptions.Default;
var snapshot = GetSnapshot(streamsToLoad, feedOptions);
SortedSet<Activity> buffer = new SortedSet<Activity>(Activity.ComparerDesc);
// Init
foreach (var str in streamsToLoad)
{
var streamId = str.Key;
FetchNextActivity(snapshot, streamId, buffer);
}
while (buffer.Count > 0)
{
Activity nextActivity = buffer.First();
buffer.Remove(nextActivity);
yield return nextActivity;
FetchNextActivity(snapshot, nextActivity.StreamId, buffer);
}
}
示例3: More_specific_type_goes_first
public void More_specific_type_goes_first()
{
var set1 = new SortedSet<Type>(comparer) { typeof(JohnChild), typeof(JohnParent) };
var set2 = new SortedSet<Type>(comparer) { typeof(JohnParent), typeof(JohnChild) };
Assert.AreEqual(typeof(JohnChild), set1.First());
Assert.AreEqual(typeof(JohnChild), set2.First());
}
示例4: Search
public static Stack<Square> Search(Map map, Square source, Square target, Func<Square, Square, int> heuristic)
{
Dictionary<Square, Square> parents = new Dictionary<Square, Square>();
HashSet<Square> closed = new HashSet<Square>();
SortedSet<Square> open = new SortedSet<Square>();
source.Score.Cost = 0;
source.Score.Estimate = heuristic(source, target);
open.Add(source);
while (open.Count > 0)
{
// Get node with lowest f(x) score
Square current = open.First();
if (current == target)
break;
// Transfer node to closed set
open.Remove(current);
closed.Add(current);
// Examine neighbors
foreach (Square neighbor in map.GetNeighbors(current))
{
// Check if node is already processed or not passable
if (closed.Contains(neighbor) || (neighbor != target && !neighbor.IsPassable))
continue;
// Tentative g score
float g = current.Score.Cost + 1;
// Add (new) node to open
if (!open.Contains(neighbor))
{
parents[neighbor] = current;
neighbor.Score.Cost = g;
neighbor.Score.Estimate = heuristic(neighbor, target);
open.Add(neighbor);
}
// Updating existing node in open
else if (g < neighbor.Score.Cost)
{
open.Remove(neighbor);
parents[neighbor] = current;
neighbor.Score.Cost = g;
open.Add(neighbor);
}
}
}
return ReconstructPath(parents, target);
}
示例5: GetNearestTarget
private void GetNearestTarget()
{
Target = null;
var targetEntities = new SortedSet<Entity>(new ByDistance((x1, y1, x2, y2) =>
TDLDistances.ChebyshevDistance(x1, y1, x2, y2), X, Y));
foreach (var tag in TargetTags)
{
var entities = Field.GetEntitiesByTag(tag).Where(x => x != Entity);
foreach (var ent in entities) targetEntities.Add(ent);
}
if (targetEntities.Count == 0) return;
var target = targetEntities.First();
Target = target;
TargetDistance = TDLDistances.ChebyshevDistance(target.X, target.Y, X, Y);
}
示例6: CalculatePath
private static List<Step> CalculatePath(IMovable movable, Zone destination)
{
List<Step> steps = new List<Step>();
if (movable.Location == destination || !movable.CanCross(destination))
return steps;
//Calculate path using A* algorithm
SortedSet<PathfindingNode> openList = new SortedSet<PathfindingNode>(
Comparer<PathfindingNode>.Create((a, b) => a.CompareTo(b)));
HashSet<Zone> closedList = new HashSet<Zone>();
openList.Add(new PathfindingNode(movable.Location, destination.DistanceWith(movable.Location)));
bool pathFound = destination == movable.Location;
while (!pathFound)
{
if (openList.Count == 0)
break;
PathfindingNode currentNode = openList.First();
foreach (Zone neighbourg in currentNode.Zone.Adjacencies.Select(a => a.Neighbourg).Where(s => movable.CanCross(s)))
{
if (closedList.Contains(neighbourg) || openList.Any(n => n.Zone == neighbourg))
continue;
openList.Add(new PathfindingNode(neighbourg, destination.DistanceWith(neighbourg), currentNode));
if (neighbourg == destination) // Path found !
{
pathFound = true;
steps.Add(new Step(currentNode.Zone, destination));
while (currentNode.Parent != null)
{
steps.Add(new Step(currentNode.Parent.Zone, currentNode.Zone));
currentNode = currentNode.Parent;
}
steps.Reverse();
break;
}
}
openList.Remove(currentNode);
closedList.Add(currentNode.Zone);
}
if (steps.Count == 0)
return steps;
return steps;
}
示例7: More_specific_type_goes_first_three_classes
public void More_specific_type_goes_first_three_classes()
{
var set1 = new SortedSet<Type>(comparer) { typeof(JohnChild), typeof(JohnParent), typeof(JohnGrandparent) };
var set2 = new SortedSet<Type>(comparer) { typeof(JohnChild), typeof(JohnGrandparent), typeof(JohnParent) };
var set3 = new SortedSet<Type>(comparer) { typeof(JohnParent), typeof(JohnChild), typeof(JohnGrandparent) };
var set4 = new SortedSet<Type>(comparer) { typeof(JohnParent), typeof(JohnGrandparent), typeof(JohnChild) };
var set5 = new SortedSet<Type>(comparer) { typeof(JohnGrandparent), typeof(JohnParent), typeof(JohnChild) };
var set6 = new SortedSet<Type>(comparer) { typeof(JohnGrandparent), typeof(JohnChild), typeof(JohnParent) };
Assert.AreEqual(typeof(JohnChild), set1.First());
Assert.AreEqual(typeof(JohnChild), set2.First());
Assert.AreEqual(typeof(JohnChild), set3.First());
Assert.AreEqual(typeof(JohnChild), set4.First());
Assert.AreEqual(typeof(JohnChild), set5.First());
Assert.AreEqual(typeof(JohnChild), set6.First());
Assert.AreEqual(typeof(JohnGrandparent), set1.Last());
Assert.AreEqual(typeof(JohnGrandparent), set2.Last());
Assert.AreEqual(typeof(JohnGrandparent), set3.Last());
Assert.AreEqual(typeof(JohnGrandparent), set4.Last());
Assert.AreEqual(typeof(JohnGrandparent), set5.Last());
Assert.AreEqual(typeof(JohnGrandparent), set6.Last());
}
示例8: PrintDetailedChanges
/// <summary>
/// Print a list of source changes, along with the success state for other builds of this node.
/// </summary>
/// <param name="History">History for this node</param>
static void PrintDetailedChanges(NodeHistory History, int CurrentCL)
{
DateTime StartTime = DateTime.UtcNow;
// Find all the changelists that we're interested in
SortedSet<int> BuildChanges = new SortedSet<int>();
BuildChanges.UnionWith(History.AllStarted.Where(x => x >= History.LastSucceeded));
BuildChanges.Add(CurrentCL);
// Find all the changelists that we're interested in
List<P4Connection.ChangeRecord> ChangeRecords = GetSourceChangeRecords(BuildChanges.First(), BuildChanges.Last());
// Print all the changes in the set
int LastCL = BuildChanges.First();
foreach(int BuildCL in BuildChanges)
{
// Show all the changes in this range
foreach(P4Connection.ChangeRecord Record in ChangeRecords.Where(x => x.CL > LastCL && x.CL <= BuildCL))
{
string[] Lines = Record.Summary.Split(new char[]{ '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
Log(" {0} {1} {2}", Record.CL, Record.UserEmail, (Lines.Length > 0)? Lines[0] : "");
}
// Show the status of this build
string BuildStatus;
if(BuildCL == CurrentCL)
{
BuildStatus = "this sync";
}
else if (History.AllSucceeded.Contains(BuildCL))
{
BuildStatus = "built";
}
else if (History.AllFailed.Contains(BuildCL))
{
BuildStatus = "FAILED";
}
else
{
BuildStatus = "running";
}
Log(" {0} {1} {2}", (BuildCL == CurrentCL)? ">>>>" : " ", BuildCL, BuildStatus.ToString());
// Update the last CL now that we've output this one
LastCL = BuildCL;
}
Log("Took {0:0.0}s to get P4 history", (DateTime.UtcNow - StartTime).TotalSeconds);
}
示例9: ShortestPaths
private static Tuple<int[], double[]> ShortestPaths(IEnumerable<Tuple<int, int>> edges, Func<int, int, double> weight, int source)
{
var neighborsOf = edges.ToNeighborhoodLists();
var vertices = Enumerable.Range(0, neighborsOf.Count);
// distanceTo will store the distance from source to any other vertex. At the beginning according to Dijkstra algorithm it's infinity for all
// vertices except the source
var distanceTo = Enumerable.Repeat(double.PositiveInfinity, neighborsOf.Count).ToArray();
distanceTo[source] = 0; // distance from the source to itself
// previous[v] will store the previous vertex in the shortest path from source to v. Initialized to -1, which means no previous vertex
// as we don't know the shortest path yet.
var previous = Enumerable.Repeat(-1, neighborsOf.Count).ToArray();
var priorityQueue = new SortedSet<int>(DelegateComparer.Create<int>((x, y) => // compare vertices according to their distance from source
{
var weightCompare = distanceTo[x].CompareTo(distanceTo[y]);
if (weightCompare == 0)
return x.CompareTo(y);
else
return weightCompare;
}));
foreach (var v in vertices)
priorityQueue.Add(v);
// the main loop of the Dijkstra algorithm
while (priorityQueue.Count > 0)
{
// we remove the min-distance vertex from the priority queue
var v = priorityQueue.First();
priorityQueue.Remove(v);
// update all neighbors of v with new distances
foreach (var u in neighborsOf[v])
{
var newDistance = distanceTo[v] + weight(v, u);
if (newDistance < distanceTo[u])
{
// we have to add and remove u from the priority queue during distance update, otherwise the priority queue will incorrectly
// return the minimal-distance node.
priorityQueue.Remove(u);
distanceTo[u] = newDistance;
priorityQueue.Add(u);
previous[u] = v;
}
}
}
return Tuple.Create(previous, distanceTo);
}
示例10: LearnInvFromTemplate
private ICEOutcome LearnInvFromTemplate(Dictionary<string, int> impl2Priority, Template t, int range, out VCGenOutcome overallOutcome)
{
overallOutcome = null;
// create a new z3 context
if (z3Context != null)
{
z3Context.context.Dispose();
z3Context.config.Dispose();
}
z3Context = new Z3Context();
foreach (var func in existentialFunctions.Values)
{
// initialize function to an "Octagons" instance with the given template "t".
function2Value[func.Name] = ICEDomainFactory.GetInstance("Octagons", t, ref z3Context, func.Name, range);
}
// add counterexamples into the z3Context. These are obtained from the earlier iterations of the template.
foreach (var cex in counterExamples)
{
AddCounterExampleToZ3Context(cex);
}
var worklist = new SortedSet<Tuple<int, string>>();
name2Impl.Keys.Iter(k => worklist.Add(Tuple.Create(impl2Priority[k], k)));
while (worklist.Any())
{
var impl = worklist.First().Item2;
worklist.Remove(worklist.First());
#region vcgen
var gen = prover.VCExprGen;
var terms = new List<Expr>();
foreach (var tup in impl2FuncCalls[impl])
{
var controlVar = tup.Item2;
var exprVars = tup.Item3;
var varList = new List<Expr>();
exprVars.Args.OfType<Expr>().Iter(v => varList.Add(v));
var args = new List<Expr>();
controlVar.InParams.Iter(v => args.Add(Expr.Ident(v)));
Expr term = Expr.Eq(new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args),
function2Value[tup.Item1].Gamma(varList));
if (controlVar.InParams.Count != 0)
{
term = new ForallExpr(Token.NoToken, new List<Variable>(controlVar.InParams.ToArray()),
new Trigger(Token.NoToken, true, new List<Expr> { new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args) }),
term);
}
terms.Add(term);
}
var env = BinaryTreeAnd(terms, 0, terms.Count - 1);
env.Typecheck(new TypecheckingContext((IErrorSink)null));
var envVC = prover.Context.BoogieExprTranslator.Translate(env);
var vc = gen.Implies(envVC, impl2VC[impl]);
if (CommandLineOptions.Clo.Trace)
{
Console.WriteLine("Verifying {0}: ", impl);
//Console.WriteLine("env: {0}", envVC);
var envFuncs = new HashSet<string>();
impl2FuncCalls[impl].Iter(tup => envFuncs.Add(tup.Item1));
envFuncs.Iter(f => PrintFunction(existentialFunctions[f]));
}
#endregion vcgen
VCExpr finalVC;
#region bound_value_of_cexs
#if false
finalVC = vc;
#else
int bound = 1000000;
terms.Clear();
foreach (var tup in impl2FuncCalls[impl])
{
var exprVars = tup.Item3;
var varList = new List<Expr>();
exprVars.Args.OfType<Expr>().Where(v => v.Type.IsInt).Iter(v => varList.Add(v));
foreach (var variable in varList)
{
terms.Add(Expr.Le(variable, Expr.Literal(bound)));
terms.Add(Expr.Ge(variable, Expr.Literal(-1 * bound)));
//terms.Add(Expr.Ge(variable, Expr.Literal(0)));
}
}
var boundcex = BinaryTreeAnd(terms, 0, terms.Count - 1);
boundcex.Typecheck(new TypecheckingContext((IErrorSink)null));
var boundcexVC = prover.Context.BoogieExprTranslator.Translate(boundcex);
finalVC = gen.Implies(boundcexVC, vc);
//.........这里部分代码省略.........
示例11: GetRuns
private static Queue<Run> GetRuns(string Path_To_File)
{
Queue<Run> ResultedRuns = new Queue<Run>();
Run CurrentRun = new Run();
using (StreamReader rdr = new StreamReader(@"Unsorted files\" + Path_To_File)){
SortedSet<int> SortedHeap = new SortedSet<int>();
SortedHeap.Reverse();
List<int> ReserveList = new List<int>();
for (int i = 0; i < 4; i++)
SortedHeap.Add(Int32.Parse(rdr.ReadLine()));
do{
while (SortedHeap.Count != 0){
int pretendent = SortedHeap.First();
SortedHeap.Remove(SortedHeap.First());
CurrentRun.Enqueue(pretendent);
if (!rdr.EndOfStream){
int Next = Int32.Parse(rdr.ReadLine());
if (Next >= pretendent)
SortedHeap.Add(Next);
else
ReserveList.Add(Next);
}
}
SortedHeap = new SortedSet<int>(ReserveList);
ReserveList = new List<int>();
ResultedRuns.Enqueue(CurrentRun);
CurrentRun = new Run();
} while (SortedHeap.Count != 0);
}
return ResultedRuns;
}
示例12: LearnInv
private VCGenOutcome LearnInv(Dictionary<string, int> impl2Priority)
{
var worklist = new SortedSet<Tuple<int, string>>();
name2Impl.Keys.Iter(k => worklist.Add(Tuple.Create(impl2Priority[k], k)));
while (worklist.Any())
{
var impl = worklist.First().Item2;
worklist.Remove(worklist.First());
#region vcgen
var gen = prover.VCExprGen;
var terms = new List<Expr>();
foreach (var tup in impl2FuncCalls[impl])
{
var controlVar = tup.Item2;
var exprVars = tup.Item3;
var varList = new List<Expr>();
exprVars.Args.OfType<Expr>().Iter(v => varList.Add(v));
var args = new List<Expr>();
controlVar.InParams.Iter(v => args.Add(Expr.Ident(v)));
Expr term = Expr.Eq(new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args),
function2Value[tup.Item1].Gamma(varList));
if (controlVar.InParams.Count != 0)
{
term = new ForallExpr(Token.NoToken, new List<Variable>(controlVar.InParams.ToArray()),
new Trigger(Token.NoToken, true, new List<Expr> { new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args) }),
term);
}
terms.Add(term);
/*
foreach (var variable in varList)
{
terms.Add(Expr.Le(variable, Expr.Literal(10)));
terms.Add(Expr.Ge(variable, Expr.Literal(-10)));
}
*/
}
var env = BinaryTreeAnd(terms, 0, terms.Count - 1);
env.Typecheck(new TypecheckingContext((IErrorSink)null));
var envVC = prover.Context.BoogieExprTranslator.Translate(env);
var vc = gen.Implies(envVC, impl2VC[impl]);
if (CommandLineOptions.Clo.Trace)
{
Console.WriteLine("Verifying {0}: ", impl);
//Console.WriteLine("env: {0}", envVC);
var envFuncs = new HashSet<string>();
impl2FuncCalls[impl].Iter(tup => envFuncs.Add(tup.Item1));
envFuncs.Iter(f => PrintFunction(existentialFunctions[f]));
}
#endregion vcgen
VCExpr finalVC;
for (int i = 0; i <= bounds4cex.Count(); i++)
{
#region boundcexvalues
/* Last iteration is when there are enforced no bounds on the cex values. */
if (i < bounds4cex.Count())
{
int bound = bounds4cex.ElementAt(i);
terms.Clear();
foreach (var tup in impl2FuncCalls[impl])
{
var exprVars = tup.Item3;
var varList = new List<Expr>();
exprVars.Args.OfType<Expr>().Where(v => v.Type.IsInt).Iter(v => varList.Add(v));
foreach (var variable in varList)
{
terms.Add(Expr.Le(variable, Expr.Literal(bound)));
terms.Add(Expr.Ge(variable, Expr.Literal(-1 * bound)));
//terms.Add(Expr.Ge(variable, Expr.Literal(0)));
}
}
var boundcex = BinaryTreeAnd(terms, 0, terms.Count - 1);
boundcex.Typecheck(new TypecheckingContext((IErrorSink)null));
var boundcexVC = prover.Context.BoogieExprTranslator.Translate(boundcex);
finalVC = gen.Implies(boundcexVC, vc);
}
else
{
//finalVC = vc;
int bound = 1000000;
terms.Clear();
foreach (var tup in impl2FuncCalls[impl])
{
var exprVars = tup.Item3;
var varList = new List<Expr>();
exprVars.Args.OfType<Expr>().Where(v => v.Type.IsInt).Iter(v => varList.Add(v));
foreach (var variable in varList)
{
//.........这里部分代码省略.........
示例13: GetPathUsingAStar
private IEnumerable<Tile> GetPathUsingAStar(IEvacuateable person, BuildingBlock destination)
{
bool firstRun = true;
SortedSet<BuildingBlock> priorityQueue = new SortedSet<BuildingBlock>(Comparer<BuildingBlock>.Default);
Dictionary<string, BuildingBlock> closedSet = new Dictionary<string, BuildingBlock>();
List<BuildingBlock> unvisitedVertices = TheFloorPlan.Tiles.Values.Cast<BuildingBlock>().ToList();
foreach (BuildingBlock point in unvisitedVertices)
{
point.LengthToDestination = point.DiagonalDistanceTo(destination);
point.Parent = null;
if (firstRun)
firstRun = false;
else
point.LengthFromSource = 100000;
point.IsChecked = false;
}
unvisitedVertices.Remove(person.Position as BuildingBlock);
BuildingBlock currentPosition = person.Position as BuildingBlock;
if (currentPosition == null) return null;
currentPosition.LengthFromSource = 0;
unvisitedVertices.Insert(0, currentPosition);
while (!Equals(currentPosition, destination))
{
foreach (BuildingBlock buildingBlock in currentPosition.BuildingBlockNeighbours)
{
if (buildingBlock.IsChecked == false)
{
if (!closedSet.ContainsKey(Settings.Coordinate(buildingBlock.X, buildingBlock.Y, buildingBlock.Z)))
{
priorityQueue.Add(buildingBlock);
}
}
}
CheckNeighbors(currentPosition, priorityQueue);
if (priorityQueue.Count == 0)
{
if (closedSet.ContainsKey(Settings.Coordinate(currentPosition.X, currentPosition.Y, currentPosition.Z)) == false)
closedSet.Add(Settings.Coordinate(currentPosition.X, currentPosition.Y, currentPosition.Z), currentPosition);
foreach (BuildingBlock buildingBlock in unvisitedVertices)
{
buildingBlock.IsChecked = false;
}
continue;
}
currentPosition.IsChecked = true;
currentPosition = priorityQueue.First();
priorityQueue.Clear();
}
List<BuildingBlock> path = new List<BuildingBlock>();
BuildingBlock parent = destination;
do
{
path.Add(parent);
parent = parent.Parent;
} while (parent != null);
path.Reverse();
return path;
}
示例14: LockOperation
private object LockOperation()
{
do
{
if (id == null)
{
long sessionId = Zookeeper.SessionId;
string prefix = "x-" + sessionId + "-";
FindPrefixInChildren(prefix, Zookeeper, dir);
idName = new ZNodeName(id);
}
if (id == null) continue;
List<string> names = Zookeeper.GetChildren(dir, false);
if (names.IsEmpty())
{
LOG.Warn("No children in: " + dir + " when we've just " +
"created one! Lets recreate it...");
// lets force the recreation of the id
id = null;
}
else
{
// lets sort them explicitly (though they do seem to come back in order ususally :)
var sortedNames = new SortedSet<ZNodeName>();
foreach (string name in names)
{
sortedNames.Add(new ZNodeName(dir.Combine(name)));
}
ownerId = sortedNames.First().Name;
SortedSet<ZNodeName> lessThanMe = sortedNames.HeadSet(idName);
if (!lessThanMe.IsEmpty())
{
ZNodeName lastChildName = lessThanMe.Last();
lastChildId = lastChildName.Name;
if (LOG.IsDebugEnabled)
{
LOG.Debug("watching less than me node: " + lastChildId);
}
Stat stat = Zookeeper.Exists(lastChildId, new LockWatcher(this));
if (stat != null)
{
return false;
}
LOG.Warn("Could not find the stats for less than me: " + lastChildName.Name);
}
else
{
if (Owner)
{
OnLockAcquired();
return true;
}
}
}
} while (id == null);
return false;
}
示例15: CliqueMatrix
public CliqueMatrix(IEnumerable<INetworkNode> nodes, IEnumerable<int> members)
: base(nodes)
{
_members = new SortedSet<int>(members);
_representativeNode = base.GetNodeById(_members.First());
}