public void EqualsOperatorReturnsFalseIfTuplesContainDifferentItem2() { var tuple1 = new Tuple<string, int>("this is a test", 42); var tuple2 = new Tuple<string, int>("this is a test", 9); Assert.IsFalse(tuple1.Equals(tuple2)); }
public void EqualsOperatorReturnsTrueIfTuplesComposedOfSamePieces() { var tuple1 = new Tuple<string, int>("this is a test", 42); var tuple2 = new Tuple<string, int>("this is a test", 42); Assert.IsTrue(tuple1.Equals(tuple2)); }
public void OneNullOneNotDifferentData() { var one = new Tuple<string, string>("Hi", null); var two = new Tuple<string, string>("Hi", "Hi"); var equalsOutput = one.Equals(two); var operatorOutput = one == two; Assert.False(equalsOutput, "Different tuples with different values should compare to false"); Assert.False(operatorOutput, "Different tuples with different values should compare to false"); }
public void OneNullOneNotSameData() { var one = new Tuple<string, string>("Hi", null); var two = new Tuple<string, string>("Hi", null); var equalsOutput = one.Equals(two); var operatorOutput = one == two; Assert.True(equalsOutput, "Different tuples with same values should compare to true"); Assert.True(operatorOutput, "Different tuples with same values should compare to true"); }
public void DifferentTripleCompare() { var tripleOne = new Tuple<int, int, int>(5, 5, 5); var tripleTwo = new Tuple<int, int, int>(5, 1, 5); var equalsOutput = tripleOne.Equals(tripleTwo); var operatorOutput = tripleOne == tripleTwo; Assert.False(equalsOutput, "Different tuples with different values should compare to false"); Assert.False(operatorOutput, "Different tuples with different values should compare to false"); }
private Tuple <int, int> GetNextVertex(Labyrinth labyrinth, Dictionary <Tuple <int, int>, int> vertexPoints, Tuple <int, int> lastPoint, Tuple <int, int> lastDirection, ref int length) { lastDirection = Tuple.Create(lastDirection.Item1 * -1, lastDirection.Item2 * -1); length++; int roadCount = 0; Tuple <int, int> newPoint = null; Tuple <int, int> newRoad = null; Tuple <int, int> newDirection = null; foreach (var direction in labyrinth.Directions.OrderBy(d => random.Next())) { var x = lastPoint.Item1 + direction.Item1; var y = lastPoint.Item2 + direction.Item2; newPoint = Tuple.Create(x, y); if (lastDirection.Equals(direction)) { continue; } if (x > labyrinth.LabyrinthArray.GetLength(0) - 1 || x < 0 || y > labyrinth.LabyrinthArray.GetLength(0) - 1 || y < 0) { continue; } if (labyrinth.LabyrinthArray[x, y] == labyrinth.Wall) { continue; } roadCount++; newRoad = newPoint; newDirection = direction; } if (roadCount == 1) { return(GetNextVertex(labyrinth, vertexPoints, newRoad, newDirection, ref length)); } else { if (vertexPoints.ContainsKey(lastPoint)) { return(null); } else { return(lastPoint); } } }
public void Equals_DifferentTypeInequalForFailure() { var t1 = new Tuple <string, int>("abc", 123); var t2 = new Tuple <string, string>("abc", "123"); var x = Validation <Tuple <string, int> > .Failure(t1); var y = Validation <Tuple <string, string> > .Failure(t2); Assert.That(t1.Equals(t2), Is.False); Assert.That(x.Equals(y), Is.False); }
public void Equals_DifferentTypeInequal() { var t1 = new Tuple <string, int>("abc", 123); var t2 = new Tuple <string, string>("abc", "123"); var x = Option <Tuple <string, int>, string> .Some(t1); var y = Option <Tuple <string, string>, string> .Some(t2); Assert.That(t1.Equals(t2), Is.False); Assert.That(x.Equals(y), Is.False); }
public void Equals_SomeEqual() { var t1 = new Tuple <string, int>("abc", 123); var t2 = new Tuple <string, int>("abc", 123); var x = Option <Tuple <string, int>, string> .Some(t1); var y = Option <Tuple <string, int>, string> .Some(t2); Assert.That(t1.Equals(t2), Is.True); Assert.That(x.Equals(y), Is.True); }
public void ValueEqual() { var t1 = new Tuple <string, int>("abc", 123); var t2 = new Tuple <string, int>("abc", 123); var x = Maybe <Tuple <string, int> > .Some(t1); var y = Maybe <Tuple <string, int> > .Some(t2); Assert.That(t1.Equals(t2), Is.True); Assert.That(x.Equals(y), Is.True); }
public void TuplesExampleTest() { var t1 = new Tuple <int, string>(1, "example1"); Assert.That(t1.Item1, Is.EqualTo(1)); Assert.That(t1.Item2, Is.EqualTo("example1")); var t2 = Tuple.Create(1, "example1"); //value comparison reference with not == will not be equal Assert.That(t1.Equals(t2)); }
public void Test() { BinarySerializer serializer = new BinarySerializer(); var message = new Tuple<string, string>("Name", "Cool"); string subject = serializer.GetObjectSubject(message); var array = serializer.Serialize(message); var messageDeserialized = serializer.Deserialize(subject, array.Array, array.Offset, array.Count); Assert.That(message.Equals(messageDeserialized)); }
public void Equals_FailureInequal() { var t1 = new Tuple <string, int>("abc", 123); var t2 = new Tuple <string, int>("dfs", 532); var x = Validation <Tuple <string, int> > .Failure(t1); var y = Validation <Tuple <string, int> > .Failure(t2); Assert.That(t1.Equals(t2), Is.False); Assert.That(x.Equals(y), Is.False); }
public void Tuple_Equal() { var population1 = new Tuple <string, int, int, int, int, int, int>( "New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278); var population2 = new Tuple <string, int, int, int, int, int, int>( "New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278); Assert.That(population1.Equals(population2)); Assert.That((object)population1 != (object)population2); }
protected void SetConfiguration(Board board, Direction direction, TileAdder adder) { this.Board = board; this.TileAdder = adder; this.BoardChanged = false; Tuple <int, int> swipe = direction.GetSwipe(); if (swipe.Equals(direction.GetUp())) { this.StartRow = 0; this.StartColumn = 0; this.UpIncrement = swipe.Item1; this.RightIncrement = 1; this.MovementPlane = Plane.Vertical; } else if (swipe.Equals(direction.GetRight())) { this.StartRow = 0; this.StartColumn = 3; this.UpIncrement = 1; this.RightIncrement = swipe.Item2; this.MovementPlane = Plane.Horizontal; } else if (swipe.Equals(direction.GetDown())) { this.StartRow = 3; this.StartColumn = 0; this.UpIncrement = swipe.Item1; this.RightIncrement = 1; this.MovementPlane = Plane.Vertical; } else if (swipe.Equals(direction.GetLeft())) { this.StartRow = 0; this.StartColumn = 0; this.UpIncrement = 1; this.RightIncrement = swipe.Item2; this.MovementPlane = Plane.Horizontal; } }
static void Main(string[] args) { Tuple <int, int> tuple1 = Tuple.Create(1, 3); Tuple <int, int> tuple2 = Tuple.Create(1, 3); Console.WriteLine( "Method Tuple.ReferenceEquals(); : " + Tuple.ReferenceEquals(tuple1, tuple2)); Console.WriteLine( "Method Tuple.Equals(); == : " + tuple1.Equals(tuple2)); Console.WriteLine( "Operator == for Tuple : " + (tuple1 == tuple2)); }
public void FirstTest() { Tuple <int, int> t1 = new Tuple <int, int>(0, 0); Tuple <int, int> t2 = new Tuple <int, int>(0, 0); bool b = t1 == t2; bool c = t1.Equals(t2); HashSet <Tuple <int, int> > h = new HashSet <Tuple <int, int> >(); h.Add(t1); bool d = h.Contains(t2); }
static void Main(string[] args) { // a set of generic classes for holding a set of differently typed elements var t1 = new Tuple<int, string>(123, "Hello"); Tuple<int, string> t2 = Tuple.Create(123, "Hello"); var t3 = Tuple.Create(123, "Hello"); Console.WriteLine(t1.Item1 * 2); Console.WriteLine(t2.Item2.ToUpper()); Console.WriteLine(t1 == t2); // False for reference types Console.WriteLine(t1.Equals(t2)); // True }
void Rotate(int[,] a, Tuple <int, int> p, Tuple <int, int> start) { int n = a.GetLength(0) - 1; int i = p.Item1, j = p.Item2; int newVal = a[n - j, i]; //previous element of the cycle Tuple <int, int> next = new Tuple <int, int>(j, n - i); //net element of the cycle if (!next.Equals(start)) { Rotate(a, next, start); } a[i, j] = newVal; }
public static void RunDemo() { Console.WriteLine("EqualTuples demo: Demonstrates that == and object.Equals() are inconsistent for tuples!"); Tuple <int, int> tuple1 = Tuple.Create(1, 2); Tuple <int, int> tuple2 = Tuple.Create(1, 2); Console.WriteLine("Reference: " + ReferenceEquals(tuple1, tuple2)); // returns FALSE : evaluates reference equality Console.WriteLine("Method: " + tuple1.Equals(tuple2)); // returns TRUE : evaluates value equality Console.WriteLine("Operator: " + (tuple1 == tuple2)); // returns FALSE : evaluates reference equality because no == overload is present in Tuple Console.WriteLine(); }
public override bool Equals(object obj) { var cond = obj as CsConditionSeq; if (cond == null) { return(false); } else { return(cond.isAND == isAND && elems.Equals(cond.elems)); } }
private bool NotAdjacentToBody(Tuple <int, int> cell) { for (var i = 0; i < 4; i++) { var adjacentcellLayout = new Tuple <int, int>(cell.Item1 + CellX[i], cell.Item2 + CellY[i]); if (!adjacentcellLayout.Equals(Head) && Body.Contains(adjacentcellLayout)) { return(false); } } return(true); }
IEnumerator WaitPush(Vector2Int position, Vector2Int positionDirection, Direction direction) { float isPushing = (direction == Direction.Right) ? 1 : -1; _pushFromCoroutine = _pushFrom; yield return(new WaitForSeconds(0.5f)); if (_pushFromCoroutine.Equals(_pushFrom) & Input.GetAxis("Horizontal") == isPushing) { Push(position, positionDirection, direction); } _coroutineIsRunning = false; }
static void FoundNakedPair(string group, int index, Tuple <int, int> firstPair, Tuple <int, int> secondPair, List <int> remove) { switch (group) { case "Box": for (int a = (index / 3) * 3; a < ((index / 3) * 3) + 3; a++) { for (int b = (index % 3) * 3; b < ((index % 3) * 3) + 3; b++) { if (!firstPair.Equals(Tuple.Create <int, int>(a, b)) && !secondPair.Equals(Tuple.Create <int, int>(a, b))) { spaces[a, b] = spaces[a, b].Except(remove).ToList(); } } } break; case "Row": for (int a = 0; a < 9; a++) { if (!firstPair.Equals(Tuple.Create <int, int>(index, a)) && !secondPair.Equals(Tuple.Create <int, int>(index, a))) { spaces[index, a] = spaces[index, a].Except(remove).ToList(); } } break; case "Column": for (int a = 0; a < 9; a++) { if (!firstPair.Equals(Tuple.Create <int, int>(a, index)) && !secondPair.Equals(Tuple.Create <int, int>(a, index))) { spaces[a, index] = spaces[a, index].Except(remove).ToList(); } } break; } }
public void Detuple5() { Prop.ForAll <List <int> >(ms => { var xs = ms.AsQueryExpr() .Aggregate(Tuple.Create(0, 1), (t, _) => Tuple.Create(t.Item2, t.Item1 + t.Item2)) .Run(); var ys = ms .Aggregate(Tuple.Create(0, 1), (t, _) => Tuple.Create(t.Item2, t.Item1 + t.Item2)); return(Tuple.Equals(xs, ys)); }).QuickCheckThrowOnFailure(); }
protected virtual void TestNameUnique(Event item) { var newName = GetNamesForItem(item); var existingNames = this .Where(e => !string.IsNullOrEmpty(e.SourceName)) .Where(e => !string.IsNullOrEmpty(e.Name)) .Select(e => GetNamesForItem(e)); if (existingNames.Any(n => Tuple.Equals(n, newName))) { throw new ArgumentOutOfRangeException("Collection item names must be unique."); } }
private void NumPress(object sender, KeyEventArgs args) { if (!highlight.Equals(new Tuple <int, int>(1000, 1000)) && (_digits.Contains(args.KeyValue - 48) || _digits.Contains(args.KeyValue - 96))) { char key = args.KeyValue > 90 ? (char)(args.KeyValue - 48) : (char)args.KeyValue; int y = highlight.Item2 / 50; int x = highlight.Item1 / 50; UpdateBoard(x, y, key); duplicates.RemoveAll(i => i == y * 9 + x); added.RemoveAll(i => i == y * 9 + x); } else if (!highlight.Equals(new Tuple <int, int>(1000, 1000)) && (args.KeyCode == Keys.Delete || args.KeyCode == Keys.Back)) { int y = highlight.Item2 / 50; int x = highlight.Item1 / 50; UpdateBoard(x, y, ' '); duplicates.RemoveAll(i => i == y * 9 + x); added.RemoveAll(i => i == y * 9 + x); } }
private bool checkCellMove(Tuple <int, int> input) { if (!searched.Contains(input)) { searched.Add(input); } if (input.Equals(target)) { if (Map[input] == 1) { //flat if (rd.Next() % 10 < 1) { updateProbMove(moveTarget());// do the update upon fail return(false); } return(true); } else if (Map[input] == 2) { if (rd.Next() % 10 < 3) { updateProbMove(moveTarget());// do the update upon fail return(false); } return(true); } else if (Map[input] == 3) { if (rd.Next() % 10 < 7) { updateProbMove(moveTarget());// do the update upon fail return(false); } return(true); } else { if (rd.Next() % 10 < 9) { updateProbMove(moveTarget());// do the update upon fail return(false); } return(true); } } updateProbMove(moveTarget());// do the update upon fail return(false); }
public override void Draw(Graphics g, LiveSplitState state, float width, float height, LayoutMode mode) { Update(); for (int i = Targets.Count - 1; i >= 0; --i) { if (Current.Equals(Targets[i])) { Draw(g, (int)width, (int)height, i); return; } } Draw(g, (int)width, (int)height, true); }
private void GeneratePathBetweenLocations(Tuple <int, int> start, Tuple <int, int> end) { Tuple <int, int> startCopy = Tuple.Create(start.Item1, start.Item2); while (!startCopy.Equals(end)) { var m = startCopy.Item1; var n = startCopy.Item2; if (WorldMatrix[m, n] == WorldCellType.None) { WorldMatrix[m, n] = WorldCellType.Path; } MoveLocationTowardsDestination(startCopy, end); } }
public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return(false); } // If parameter cannot be cast to Point return false. if (!(obj is DependencyKey otherKey)) { return(false); } return(nameAndType.Equals(otherKey.nameAndType)); }
public static void Main() { // Create five 8-tuple objects containing prime numbers. var prime1 = new Tuple <Int32, Int32, Int32, Int32, Int32, Int32, Int32, Tuple <Int32> > (2, 3, 5, 7, 11, 13, 17, new Tuple <Int32>(19)); var prime2 = new Tuple <Int32, Int32, Int32, Int32, Int32, Int32, Int32, Tuple <Int32> > (23, 29, 31, 37, 41, 43, 47, new Tuple <Int32>(55)); var prime3 = new Tuple <Int32, Int32, Int32, Int32, Int32, Int32, Int32, Tuple <Int32> > (3, 2, 5, 7, 11, 13, 17, new Tuple <Int32>(19)); var prime4 = new Tuple <Int32, Int32, Int32, Int32, Int32, Int32, Int32, Tuple <Int32, Int32> > (2, 3, 5, 7, 11, 13, 17, new Tuple <Int32, Int32>(19, 23)); var prime5 = new Tuple <Int32, Int32, Int32, Int32, Int32, Int32, Int32, Tuple <Int32> > (2, 3, 5, 7, 11, 13, 17, new Tuple <Int32>(19)); Console.WriteLine("{0} = {1} : {2}", prime1, prime2, prime1.Equals(prime2)); Console.WriteLine("{0} = {1} : {2}", prime1, prime3, prime1.Equals(prime3)); Console.WriteLine("{0} = {1} : {2}", prime1, prime4, prime1.Equals(prime4)); Console.WriteLine("{0} = {1} : {2}", prime1, prime5, prime1.Equals(prime5)); }
public static Tuple <int, int> ValidateLocationNotTaken(Board board, Tuple <int, int> userMove) { while (board.IsLocationTaken(userMove)) { Console.WriteLine("This location is taken"); UserInputHandler.PrintInstructions(); userMove = UserInputHandler.GetUserInput(); if (userMove.Equals(Board.QuitMove)) { return(userMove); } } return(userMove); }
public virtual bool check_step(Tuple <int, int> destination, BoardClass board) { bool result = false; foreach (var step in chess_steps) { Tuple <int, int> new_cord = sum_tuples(step, chess_cord); if (new_cord.Equals(destination)) { result = true; break; } } return(result); }
public void TestInequalTuples() { Tuple <int> a1 = new Tuple <int>(3); Tuple <int> b1 = new Tuple <int>(4); Assert.False(a1.Equals(b1), "1 equals"); Assert.False(a1.GetHashCode() == b1.GetHashCode(), "1 =="); Assert.True(a1.GetHashCode() != b1.GetHashCode(), "1 !="); Tuple <int, int> a2 = new Tuple <int, int>(1, 7); Tuple <int, int> b2 = new Tuple <int, int>(1, 8); Assert.False(a2.Equals(b2), "2 equals"); Assert.False(a2.GetHashCode() == b2.GetHashCode(), "2 =="); Assert.True(a2.GetHashCode() != b2.GetHashCode(), "2 !="); }
public static bool AreHotkeysEqual(Tuple <int, int> hotkey1, Tuple <int, int> hotkey2) { //if they are all zero, they are not the same, because 0 == NONE if (hotkey1.Item1 == 0 && hotkey1.Equals(hotkey2)) { return(false); } //if there are not all 0 // compare the rows, if they are both 0, they are the same, compare the rest bool row1Equal = ((hotkey1.Item1 == 0 && hotkey2.Item1 == 0) || (hotkey1.Item1 == hotkey2.Item1)); bool row2Equal = ((hotkey1.Item2 == 0 && hotkey2.Item2 == 0) || (hotkey1.Item2 == hotkey2.Item2)); return(row1Equal && row2Equal); }
public void Sample() { // Создание кортежа var tuple = new Tuple<int, string, bool>(42, "abc", true); // Доступ к компонентам кортежа: Assert.That(tuple.Item1, Is.EqualTo(42)); Assert.That(tuple.Item2, Is.EqualTo("abc")); Assert.That(tuple.Item3, Is.EqualTo(true)); //Переопределенный ToString Assert.That(tuple.ToString(), Is.EqualTo("(42, abc, True)")); // Переопределенный Equals сравнивает значения компонент кортежа var otherTuple = new Tuple<int, string, bool>(42, "abc", true); Assert.IsTrue(tuple.Equals(otherTuple)); }
/// <summary> /// 判定是否死亡 /// </summary> /// <param name="left">蛇移动边界左边</param> /// <param name="right">蛇移动边界右边</param> /// <param name="up">蛇移动边界上面</param> /// <param name="down">蛇移动边界下面</param> /// <returns>是否死亡</returns> public bool isDead(int left, int right, int up, int down) { Tuple <int, int> head = pos[0]; if (head.Item1 <= left || head.Item1 >= right || head.Item2 <= up || head.Item2 >= down) //判断是否撞墙 { return(true); } for (int i = 1; i < pos.Count; i++) //判断是否自我相撞 { if (head.Equals(pos[i])) { return(true); } } return(false); }
private void AfterPreAppStartExecute(Tuple<long, long> currentHash, Tuple<long, long> cachedTopLevelFilesHash) { bool gotLock = false; try { // Grab the compilation mutex, since this method accesses the codegen files CompilationLock.GetLock(ref gotLock); // After pre app start methods have executed, the second hash value should match the current value in the hash code combiner. CheckCodeGenFiles(currentHash.Item2, cachedTopLevelFilesHash.Item2); if (!cachedTopLevelFilesHash.Equals(currentHash)) { // Hash has changed. Persist it to disk _codeGenCache.SavePreservedSpecialFilesCombinedHash(currentHash); } // VSWhidbey 537929 : Setup a filechange monitor for the web.hash file. If this file is modified, // we will need to shutdown the appdomain so we don't use the obsolete assemblies. The new appdomain // will use the up-to-date assemblies. HttpRuntime.FileChangesMonitor.StartMonitoringFile(_webHashFilePath, new FileChangeEventHandler(this.OnWebHashFileChange)); Debug.Assert(File.Exists(_webHashFilePath), _webHashFilePath); } finally { // Always release the mutex if we had taken it if (gotLock) { CompilationLock.ReleaseLock(); } } }
protected override Tuple CalculateMro(Tuple baseClasses) { // should always be the same for ReflectedTypes Debug.Assert(baseClasses.Equals(BaseClasses)); if (effectivePythonType != null) { return effectivePythonType.MethodResolutionOrder; } else { return base.CalculateMro(baseClasses); } }
/// <summary> /// Please look at the class documentation for detailed description how this algorithm works. /// </summary> /// <param name="myTypeAttribute">The Attribute representing the edge to follow (p.e. "Friends")</param> /// <param name="myVertexType">The type of the start node.</param> /// <param name="myStart">The start node</param> /// <param name="myEnd">The end node</param> /// <param name="shortestOnly">true, if only shortest path shall be found</param> /// <param name="findAll">if true and shortestOnly is true, all shortest paths will be found. /// If true, and shortest only is false, all paths will be searched</param> /// <param name="myMaxDepth">The maximum depth to search</param> /// <param name="myMaxPathLength">The maximum path length which shall be analyzed</param> /// <returns>A HashSet which contains all found paths. Every path is represented by a List of ObjectUUIDs</returns>m> public HashSet<List<Tuple<long, long>>> Find(IAttributeDefinition myTypeAttribute, IVertexType myVertexType, IVertex myStart, IVertex myEnd, bool shortestOnly, bool findAll, UInt64 myMaxDepth, UInt64 myMaxPathLength) { #region declarations //set current depth _DepthLeft = 1; _DepthRight = 1; //maximum depth _MaxDepthLeft = 0; _MaxDepthRight = 0; _MaxPathLength = myMaxPathLength; #region initialize maxDepths //if the maxDepth is greater then maxPathLength, then set maxDepth to maxPathLength if (myMaxDepth > _MaxPathLength) myMaxDepth = _MaxPathLength; else if (_MaxPathLength > myMaxDepth) _MaxPathLength = myMaxDepth; //set depth for left side _MaxDepthLeft = Convert.ToUInt64(myMaxDepth / 2 + 1); //if myMaxDepth is 1 _MaxDepthRight keeps 0, just one side is searching if (myMaxDepth > 1) //both sides have the same depth _MaxDepthRight = _MaxDepthLeft; //if myMaxDepth is even, one side has to search in a greater depth if ((myMaxDepth % 2) == 0) _MaxDepthRight = Convert.ToUInt64(_MaxDepthLeft - 1); #endregion //shortest path length _ShortestPathLength = 0; //_Target node, the _Target of the select _Target = new Node(myEnd.VertexTypeID, myEnd.VertexID); _Root = new Node(myStart.VertexTypeID, myStart.VertexID); //the attribute (edge) which is used for the search _AttributeDefinition = myTypeAttribute; //search the type on which the attribute is defined IVertexType current = myVertexType; List<IVertexType> tempList = new List<IVertexType>(); tempList.Add(current); bool foundDefinedType = false; while (current.HasParentType && !foundDefinedType) { if (current.ParentVertexType.HasAttribute(_AttributeDefinition.Name)) { foundDefinedType = true; } current = current.ParentVertexType; tempList.Add(current); } if (foundDefinedType) _Types = tempList; else _Types.Add(myVertexType); //dummy node to check in which level the BFS is _DummyLeft = null; _DummyRight = null; _FindAll = findAll; _ShortestOnly = shortestOnly; #endregion #region BidirectionalBFS //check if the EdgeType is ASetReferenceEdgeType #region initialize variables //enqueue start node to start from left side _QueueLeft.Enqueue(myStart); //enqueue _DummyLeft to analyze the depth of the left side _QueueLeft.Enqueue(_DummyLeft); //enqueue _Target node to start from right side _QueueRight.Enqueue(myEnd); //enqueue _DummyRight to analyze the depth of the right side _QueueRight.Enqueue(_DummyRight); //add _Root and _Target to visitedNodes _VisitedNodesLeft.Add(_Root.Key, _Root); _VisitedNodesRight.Add(_Target.Key, _Target); #endregion #region check if start has outgoing and _Target has incoming edge //check that the start node has the outgoing edge and the target has incoming vertices if (!myStart.HasOutgoingEdge(_AttributeDefinition.ID) && !HasIncomingVertices(myEnd)) { return null; } #endregion //if there is more than one object in the queue and the actual depth is less than MaxDepth while (((_QueueLeft.Count > 0) && (_QueueRight.Count > 0)) && ((_DepthLeft <= _MaxDepthLeft) || (_DepthRight <= _MaxDepthRight))) { #region both queues contain objects and both depths are not reached if (((_QueueLeft.Count > 0) && (_QueueRight.Count > 0)) && ((_DepthLeft <= _MaxDepthLeft) && (_DepthRight <= _MaxDepthRight))) { #region check if a level is completely searched if (LeftLevelCompleted()) continue; if (RightLevelCompleted()) continue; #endregion check if there is a dummyNode at the beginning of a queue #region get first nodes of the queues //hold the actual element of the queues Node currentNodeLeft; Node currentNodeRight; IVertex currentVertexLeft; IVertex currentVertexRight; Tuple<long, long> currentLeft; Tuple<long, long> currentRight; //get the first Object of the queue currentVertexLeft = _QueueLeft.Dequeue(); currentLeft = new Tuple<long, long>(currentVertexLeft.VertexTypeID, currentVertexLeft.VertexID); if (_VisitedNodesLeft.ContainsKey(currentLeft)) currentNodeLeft = _VisitedNodesLeft[currentLeft]; else currentNodeLeft = new Node(currentLeft); //get the first Object of the queue currentVertexRight = _QueueRight.Dequeue(); currentRight = new Tuple<long, long>(currentVertexRight.VertexTypeID, currentVertexRight.VertexID); if (_VisitedNodesRight.ContainsKey(currentRight)) currentNodeRight = _VisitedNodesRight[currentRight]; else currentNodeRight = new Node(currentRight); #endregion #region the edge and the backwardedge are existing if (currentVertexLeft.HasOutgoingEdge(_AttributeDefinition.ID) && HasIncomingVertices(currentVertexRight)) { //get all referenced ObjectUUIDs using the given Edge var leftVertices = currentVertexLeft.GetOutgoingEdge(_AttributeDefinition.ID).GetTargetVertices(); #region check left friends foreach (var nextLeftVertex in leftVertices) { Node nextLeftNode = null; Tuple<long, long> nextLeft = new Tuple<long, long>(nextLeftVertex.VertexTypeID, nextLeftVertex.VertexID); #region if the child is the _Target if (nextLeft.Equals(_Target.Key)) { if (TargetFoundCheckAbort(nextLeft, ref currentNodeLeft, ref nextLeftNode, nextLeftVertex)) return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths(); } #endregion #region already visited else if (_VisitedNodesLeft.ContainsKey(nextLeft)) { UpdateVisitedLeft(nextLeft, ref currentNodeLeft); } #endregion already visited #region set as visited else { SetAsVisitedLeft(nextLeft, ref currentNodeLeft, ref nextLeftNode, nextLeftVertex); } #endregion set as visited } #endregion check left friends //get all referenced ObjectUUIDs using the given Edge var rightVertices = GetIncomingVertices(currentVertexRight); #region check right friends foreach (var nextRightVertex in rightVertices) { Node nextRightNode = null; Tuple<long, long> nextRight = new Tuple<long, long>(nextRightVertex.VertexTypeID, nextRightVertex.VertexID); #region if the child is the _Target if (_Root.Key.Equals(nextRight)) { if (RootFoundCheckAbort(nextRight, ref currentNodeRight, ref nextRightNode, nextRightVertex)) return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths(); } #endregion if the child is the _Target #region already visited else if (_VisitedNodesRight.ContainsKey(nextRight)) { UpdateVisitedRight(nextRight, ref currentNodeRight); } #endregion already visited #region set as visited else { SetAsVisitedRight(nextRight, ref currentNodeRight, ref nextRightNode, nextRightVertex); } #endregion set as visited } #endregion check right friends #region build intersection of _VisitedNodesLeft and _VisitedNodesRight //marks if intersection nodes are existing bool foundIntersect = false; foreach (var node in _VisitedNodesLeft) { if (_VisitedNodesRight.ContainsKey(node.Key)) { //set nodes children and parents node.Value.addChildren(_VisitedNodesRight[node.Key].Children); node.Value.addParents(_VisitedNodesRight[node.Key].Parents); //set nodes children and parents _VisitedNodesRight[node.Key].addChildren(node.Value.Children); _VisitedNodesRight[node.Key].addParents(node.Value.Parents); _IntersectNodes.Add(_VisitedNodesRight[node.Key]); foundIntersect = true; } } #endregion build intersection of _VisitedNodesLeft and _VisitedNodesRight #region analyze intersection //if intersection nodes existing if (foundIntersect) { //only shortest path if (_ShortestOnly && !_FindAll) { if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength) { _ShortestPathLength = _MaxPathLength; } else { _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1); } //return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths(); return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll) .GetShortestPath(_IntersectNodes); } //if find all shortest paths else if (_ShortestOnly && _FindAll) { //set maxDepth to actual depth _MaxDepthLeft = _DepthLeft; _MaxDepthRight = _DepthRight; if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength) { _ShortestPathLength = _MaxPathLength; } else if (_ShortestPathLength == 0) { _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1); } } } #endregion analyze intersection } #endregion the edge and the backwardedge are existing #region only the edge exists else if (currentVertexLeft.HasOutgoingEdge(_AttributeDefinition.ID)) { var result = CheckNextVerticesOfLeftSide(ref currentVertexLeft, ref currentNodeLeft); if (result != null) return result; } #endregion only the edge exists #region only the backwardedge exists else if (HasIncomingVertices(currentVertexRight)) { var result = CheckNextVerticesOfRightSide(ref currentVertexRight, ref currentNodeRight); if (result != null) return result; } #endregion only the backwardedge exists } #endregion both queues contain objects and both depths are not reached #region only left queue contain objects else if ((_QueueLeft.Count > 0) && (_DepthLeft <= _MaxDepthLeft)) { #region check if first element of queue is a dummy if (LeftLevelCompleted()) continue; #endregion check if first element of queue is a dummy #region get first nodes of the queues //hold the actual element of the queues Node currentNodeLeft; IVertex currentVertexLeft; //get the first Object of the queue currentVertexLeft = _QueueLeft.Dequeue(); Tuple<long, long> currentLeft = new Tuple<long, long>(currentVertexLeft.VertexTypeID, currentVertexLeft.VertexID); if (_VisitedNodesLeft.ContainsKey(currentLeft)) continue; if (_VisitedNodesLeft.ContainsKey(currentLeft)) currentNodeLeft = _VisitedNodesLeft[currentLeft]; else currentNodeLeft = new Node(currentLeft); #endregion #region check next vertices if (currentVertexLeft.HasOutgoingEdge(_AttributeDefinition.ID)) { var result = CheckNextVerticesOfLeftSide(ref currentVertexLeft, ref currentNodeLeft); if (result != null) return result; } #endregion } #endregion only left queue contain objects #region only right queue contain objects else if ((_QueueRight.Count > 0) && (_DepthRight <= _MaxDepthRight)) { #region check if first element of the queue is a dummy if (RightLevelCompleted()) continue; #endregion check if first element of the queue is a dummy #region get first nodes of the queues //hold the actual element of the queues Node currentNodeRight; IVertex currentVertexRight; //get the first Object of the queue currentVertexRight = _QueueRight.Dequeue(); Tuple<long, long> currentRight = new Tuple<long, long>(currentVertexRight.VertexTypeID, currentVertexRight.VertexID); if (_VisitedNodesRight.ContainsKey(currentRight)) continue; if (_VisitedNodesRight.ContainsKey(currentRight)) currentNodeRight = _VisitedNodesRight[currentRight]; else currentNodeRight = new Node(currentRight); #endregion #region check next vertices if (HasIncomingVertices(currentVertexRight)) { var result = CheckNextVerticesOfRightSide(ref currentVertexRight, ref currentNodeRight); if (result != null) return result; } #endregion } #endregion only right queue contain objects #region abort loop else break; #endregion abort loop } #region nothing found if (_ShortestOnly && !_FindAll) return null; #endregion //get result paths #region start TargetAnalyzer if (_ShortestOnly && _FindAll) { if (_ShortestPathLength > _MaxPathLength) { _ShortestPathLength = _MaxPathLength; } return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths(); } else { return new TargetAnalyzer(_Root, _Target, _MaxPathLength, _ShortestOnly, _FindAll).GetPaths(); } #endregion start TargetAnalyzer #endregion BidirectionalBFS }
public void TupleEqualsNullReturnsFalse() { var testTuple = new Tuple<string, int>("this is a test", 42); Assert.IsFalse(testTuple.Equals(null)); }
public void TupleEqualsItselfReturnsTrue() { var testTuple = new Tuple<string, int>("this is a test", 42); Assert.IsTrue(testTuple.Equals(testTuple)); }
/// <summary> /// Checks if the search should be aborted. /// </summary> /// <param name="myTuple">the Tuple of the current Vertex.</param> /// <param name="myCurrentNode">The current Node.</param> /// <param name="myNextNode">The next Node.</param> /// <param name="myVertex">The actual Vertex.</param> /// <returns>True, if the target is found AND the BFS could be finished. False, if the BFS should be continued.</returns> private bool TargetFoundCheckAbort(Tuple<long, long> myTuple, ref Node myCurrentNode, ref Node myNextNode, IVertex myVertex) { if (myTuple.Equals(_Target.Key)) { //set currentLeft as parent of _Target _Target.addParent(myCurrentNode); #region check if already visited if (_VisitedNodesLeft.ContainsKey(myTuple)) { //set currentLeft as parent _VisitedNodesLeft[myTuple].addParent(myCurrentNode); //set currentNodeLeft as child myCurrentNode.addChild(_VisitedNodesLeft[myTuple]); } else { //create a new node and set currentLeft = parent myNextNode = new Node(myTuple, myCurrentNode); //set currentNodeLeft as child of currentLeft myCurrentNode.addChild(myNextNode); //never seen before //mark the node as visited _VisitedNodesLeft.Add(myNextNode.Key, myNextNode); //and put node into the queue _QueueLeft.Enqueue(myVertex); } #endregion #region check how much parents are searched if (_ShortestOnly && !_FindAll) { if ((_DepthLeft + _DepthRight + 1) > _MaxPathLength) { _ShortestPathLength = _MaxPathLength; } else { _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight + 1); } return true; } //if find all shortest paths else if (_ShortestOnly && _FindAll) { //set maxDepth to actual depth _MaxDepthLeft = _DepthLeft; _MaxDepthRight = _DepthRight; if ((_DepthLeft + _DepthRight) > _MaxPathLength) { _ShortestPathLength = _MaxPathLength; } else { _ShortestPathLength = Convert.ToUInt64(_DepthLeft + _DepthRight); } } #endregion } return false; }
public void OutputAndDebugWriter () { //Interesting fact... Debug.Write(""); produces log entry //but Console.Write(""); does not InitializeTest (); AddBreakpoint ("5070ed1c-593d-4cbe-b4fa-b2b0c7b25289"); var errorsList = new List<string> (); errorsList.Add ("ErrorText"); var outputList = new HashSet<string> (); outputList.Add ("NormalText"); var debugList = new List<Tuple<int,string,string>> (); debugList.Add (new Tuple<int,string,string> (0, "", "DebugText")); debugList.Add (new Tuple<int, string, string> (3, "SomeCategory", "DebugText2")); var unexpectedOutput = new List<string> (); var unexpectedError = new List<string> (); var unexpectedDebug = new List<Tuple<int,string,string>> (); Session.DebugWriter = delegate(int level, string category, string message) { var entry = new Tuple<int,string,string> (level, category, message); if (entry.Equals (new Tuple<int,string,string> (0, "", "")))//Sdb is emitting some empty messages :S return; if (debugList.Contains (entry)) { debugList.Remove (entry); } else { unexpectedDebug.Add (entry); } }; Session.OutputWriter = delegate(bool isStderr, string text) { if (isStderr) { if (errorsList.Contains (text)) errorsList.Remove (text); else unexpectedError.Add (text); } else { if (outputList.Contains (text)) outputList.Remove (text); else unexpectedOutput.Add (text); } }; StartTest ("OutputAndDebugWriter"); CheckPosition ("5070ed1c-593d-4cbe-b4fa-b2b0c7b25289"); if (outputList.Count > 0) Assert.Fail ("Output list still has following items:" + string.Join (",", outputList)); if (errorsList.Count > 0) Assert.Fail ("Error list still has following items:" + string.Join (",", errorsList)); if (debugList.Count > 0) Assert.Fail ("Debug list still has following items:" + string.Join (",", debugList)); if (unexpectedOutput.Count > 0) Assert.Fail ("Unexcpected Output list has following items:" + string.Join (",", unexpectedOutput)); if (unexpectedError.Count > 0) Assert.Fail ("Unexcpected Error list has following items:" + string.Join (",", unexpectedError)); if (unexpectedDebug.Count > 0) Assert.Fail ("Unexcpected Debug list has following items:" + string.Join (",", unexpectedDebug)); }
public void SameTripleCompare() { var tripleOne = new Tuple<int, int, int>(5, 5, 5); var equalsOutput = tripleOne.Equals(tripleOne); var operatorOutput = tripleOne == tripleOne; Assert.True(equalsOutput, "Same tuple should compare to true"); Assert.True(operatorOutput, "Same tuple should compare to true"); }
private HashSet<List<Tuple<long, long>>> CheckNextVerticesOfLeftSide(ref IVertex myCurrentVertexLeft, ref Node myCurrentNodeLeft) { //get all referenced ObjectUUIDs using the given Edge var leftVertices = myCurrentVertexLeft.GetOutgoingEdge(_AttributeDefinition.ID).GetTargetVertices(); #region check left friends foreach (var nextLeftVertex in leftVertices) { Node nextLeftNode = null; Tuple<long, long> nextLeft = new Tuple<long, long>(nextLeftVertex.VertexTypeID, nextLeftVertex.VertexID); #region if the child is the _Target if (nextLeft.Equals(_Target.Key)) { if (TargetFoundCheckAbort(nextLeft, ref myCurrentNodeLeft, ref nextLeftNode, nextLeftVertex)) return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths(); } #endregion #region already visited from right side else if (_VisitedNodesRight.ContainsKey(nextLeft)) { if (VisitedByRightSide(nextLeft, ref myCurrentNodeLeft)) return new TargetAnalyzer(_Root, _Target, _ShortestPathLength, _ShortestOnly, _FindAll).GetPaths(); } #endregion already visited from right side #region already visited else if (_VisitedNodesLeft.ContainsKey(nextLeft)) { UpdateVisitedLeft(nextLeft, ref myCurrentNodeLeft); } #endregion already visited #region set as visited else { SetAsVisitedLeft(nextLeft, ref myCurrentNodeLeft, ref nextLeftNode, nextLeftVertex); } #endregion set as visited } #endregion check left friends return null; }