C#
// Finite Ordered Sets - 4State - Balanced
using System;
using System.Collections.Generic;
public enum Direction { FromLeft, FromRight };
public enum State { Header, LeftHigh, Balanced, RightHigh };
public enum SetOperation
{
Union,
Intersection,
SymmetricDifference,
Difference,
Equality,
Inequality,
Subset,
Superset
}
public class Node
{
public Node Left;
public Node Right;
public Node Parent;
public State Balance;
public Node()
{
Left = this;
Right = this;
Parent = null;
Balance = State.Header;
}
public Node(Node p)
{
Left = null;
Right = null;
Parent = p;
Balance = State.Balanced;
}
public bool IsHeader
{ get { return Balance == State.Header; } }
}
public class SetNode<T> : Node
{
public T Data;
public SetNode() { }
public SetNode(T dataType, Node Parent) : base(Parent)
{
Data = dataType;
}
public override int GetHashCode()
{
return Data.GetHashCode();
}
}
class Utility // Nongeneric Tree Balancing
{
static void RotateLeft(ref Node Root)
{
Node Parent = Root.Parent;
Node x = Root.Right;
Root.Parent = x;
x.Parent = Parent;
if (x.Left != null) x.Left.Parent = Root;
Root.Right = x.Left;
x.Left = Root;
Root = x;
}
static void RotateRight(ref Node Root)
{
Node Parent = Root.Parent;
Node x = Root.Left;
Root.Parent = x;
x.Parent = Parent;
if (x.Right != null) x.Right.Parent = Root;
Root.Left = x.Right;
x.Right = Root;
Root = x;
}
static void BalanceLeft(ref Node Root)
{
Node Left = Root.Left;
switch (Left.Balance)
{
case State.LeftHigh:
Root.Balance = State.Balanced;
Left.Balance = State.Balanced;
RotateRight(ref Root);
break;
case State.RightHigh:
{
Node subRight = Left.Right;
switch (subRight.Balance)
{
case State.Balanced:
Root.Balance = State.Balanced;
Left.Balance = State.Balanced;
break;
case State.RightHigh:
Root.Balance = State.Balanced;
Left.Balance = State.LeftHigh;
break;
case State.LeftHigh:
Root.Balance = State.RightHigh;
Left.Balance = State.Balanced;
break;
}
subRight.Balance = State.Balanced;
RotateLeft(ref Left);
Root.Left = Left;
RotateRight(ref Root);
}
break;
case State.Balanced:
Root.Balance = State.LeftHigh;
Left.Balance = State.RightHigh;
RotateRight(ref Root);
break;
}
}
static void BalanceRight(ref Node Root)
{
Node Right = Root.Right;
switch (Right.Balance)
{
case State.RightHigh:
Root.Balance = State.Balanced;
Right.Balance = State.Balanced;
RotateLeft(ref Root);
break;
case State.LeftHigh:
{
Node subLeft = Right.Left; // Left Subtree of Right
switch (subLeft.Balance)
{
case State.Balanced:
Root.Balance = State.Balanced;
Right.Balance = State.Balanced;
break;
case State.LeftHigh:
Root.Balance = State.Balanced;
Right.Balance = State.RightHigh;
break;
case State.RightHigh:
Root.Balance = State.LeftHigh;
Right.Balance = State.Balanced;
break;
}
subLeft.Balance = State.Balanced;
RotateRight(ref Right);
Root.Right = Right;
RotateLeft(ref Root);
}
break;
case State.Balanced:
Root.Balance = State.RightHigh;
Right.Balance = State.LeftHigh;
RotateLeft(ref Root);
break;
}
}
public static void BalanceSet(Node Root, Direction From)
{
bool Taller = true;
while (Taller)
{
Node Parent = Root.Parent;
Direction NextFrom = (Parent.Left == Root) ? Direction.FromLeft : Direction.FromRight;
if (From == Direction.FromLeft)
{
switch (Root.Balance)
{
case State.LeftHigh:
if (Parent.IsHeader)
BalanceLeft(ref Parent.Parent);
else if (Parent.Left == Root)
BalanceLeft(ref Parent.Left);
else
BalanceLeft(ref Parent.Right);
Taller = false;
break;
case State.Balanced:
Root.Balance = State.LeftHigh;
Taller = true;
break;
case State.RightHigh:
Root.Balance = State.Balanced;
Taller = false;
break;
}
}
else
{
switch (Root.Balance)
{
case State.LeftHigh:
Root.Balance = State.Balanced;
Taller = false;
break;
case State.Balanced:
Root.Balance = State.RightHigh;
Taller = true;
break;
case State.RightHigh:
if (Parent.IsHeader)
BalanceRight(ref Parent.Parent);
else if (Parent.Left == Root)
BalanceRight(ref Parent.Left);
else
BalanceRight(ref Parent.Right);
Taller = false;
break;
}
}
if (Taller) // skip up a level
{
if (Parent.IsHeader)
Taller = false;
else
{
Root = Parent;
From = NextFrom;
}
}
}
}
public static void BalanceSetRemove(Node Root, Direction From)
{
if (Root.IsHeader) return;
bool Shorter = true;
while (Shorter)
{
Node Parent = Root.Parent;
Direction NextFrom = (Parent.Left == Root) ? Direction.FromLeft : Direction.FromRight;
if (From == Direction.FromLeft)
{
switch (Root.Balance)
{
case State.LeftHigh:
Root.Balance = State.Balanced;
Shorter = true;
break;
case State.Balanced:
Root.Balance = State.RightHigh;
Shorter = false;
break;
case State.RightHigh:
if (Root.Right.Balance == State.Balanced)
Shorter = false;
else
Shorter = true;
if (Parent.IsHeader)
BalanceRight(ref Parent.Parent);
else if (Parent.Left == Root)
BalanceRight(ref Parent.Left);
else
BalanceRight(ref Parent.Right);
break;
}
}
else
{
switch (Root.Balance)
{
case State.RightHigh:
Root.Balance = State.Balanced;
Shorter = true;
break;
case State.Balanced:
Root.Balance = State.LeftHigh;
Shorter = false;
break;
case State.LeftHigh:
if (Root.Left.Balance == State.Balanced)
Shorter = false;
else
Shorter = true;
if (Parent.IsHeader)
BalanceLeft(ref Parent.Parent);
else if (Parent.Left == Root)
BalanceLeft(ref Parent.Left);
else
BalanceLeft(ref Parent.Right);
break;
}
}
if (Shorter)
{
if (Parent.IsHeader)
Shorter = false;
else
{
From = NextFrom;
Root = Parent;
}
}
}
}
public static Node PreviousItem(Node Node)
{
if (Node.IsHeader) { return Node.Right; }
if (Node.Left != null)
{
Node = Node.Left;
while (Node.Right != null) Node = Node.Right;
}
else
{
Node y = Node.Parent;
if (y.IsHeader) return y;
while (Node == y.Left) { Node = y; y = y.Parent; }
Node = y;
}
return Node;
}
public static Node NextItem(Node Node)
{
if (Node.IsHeader) return Node.Left;
if (Node.Right != null)
{
Node = Node.Right;
while (Node.Left != null) Node = Node.Left;
}
else
{
Node y = Node.Parent;
if (y.IsHeader) return y;
while (Node == y.Right) { Node = y; y = y.Parent; }
Node = y;
}
return Node;
}
public static ulong Depth(Node Root)
{
if (Root != null)
{
ulong Left = Root.Left != null ? Depth(Root.Left) : 0;
ulong Right = Root.Right != null ? Depth(Root.Right) : 0;
return Left < Right ? Right + 1 : Left + 1;
}
else
return 0;
}
static void SwapNodeReference(ref Node First,
ref Node Second)
{ Node Temporary = First; First = Second; Second = Temporary; }
public static void SwapNodes(Node A, Node B)
{
if (B == A.Left)
{
if (B.Left != null) B.Left.Parent = A;
if (B.Right != null) B.Right.Parent = A;
if (A.Right != null) A.Right.Parent = B;
if (!A.Parent.IsHeader)
{
if (A.Parent.Left == A)
A.Parent.Left = B;
else
A.Parent.Right = B;
}
else A.Parent.Parent = B;
B.Parent = A.Parent;
A.Parent = B;
A.Left = B.Left;
B.Left = A;
SwapNodeReference(ref A.Right, ref B.Right);
}
else if (B == A.Right)
{
if (B.Right != null) B.Right.Parent = A;
if (B.Left != null) B.Left.Parent = A;
if (A.Left != null) A.Left.Parent = B;
if (!A.Parent.IsHeader)
{
if (A.Parent.Left == A)
A.Parent.Left = B;
else
A.Parent.Right = B;
}
else A.Parent.Parent = B;
B.Parent = A.Parent;
A.Parent = B;
A.Right = B.Right;
B.Right = A;
SwapNodeReference(ref A.Left, ref B.Left);
}
else if (A == B.Left)
{
if (A.Left != null) A.Left.Parent = B;
if (A.Right != null) A.Right.Parent = B;
if (B.Right != null) B.Right.Parent = A;
if (!B.Parent.IsHeader)
{
if (B.Parent.Left == B)
B.Parent.Left = A;
else
B.Parent.Right = A;
}
else B.Parent.Parent = A;
A.Parent = B.Parent;
B.Parent = A;
B.Left = A.Left;
A.Left = B;
SwapNodeReference(ref A.Right, ref B.Right);
}
else if (A == B.Right)
{
if (A.Right != null) A.Right.Parent = B;
if (A.Left != null) A.Left.Parent = B;
if (B.Left != null) B.Left.Parent = A;
if (!B.Parent.IsHeader)
{
if (B.Parent.Left == B)
B.Parent.Left = A;
else
B.Parent.Right = A;
}
else B.Parent.Parent = A;
A.Parent = B.Parent;
B.Parent = A;
B.Right = A.Right;
A.Right = B;
SwapNodeReference(ref A.Left, ref B.Left);
}
else
{
if (A.Parent == B.Parent)
SwapNodeReference(ref A.Parent.Left, ref A.Parent.Right);
else
{
if (!A.Parent.IsHeader)
{
if (A.Parent.Left == A)
A.Parent.Left = B;
else
A.Parent.Right = B;
}
else A.Parent.Parent = B;
if (!B.Parent.IsHeader)
{
if (B.Parent.Left == B)
B.Parent.Left = A;
else
B.Parent.Right = A;
}
else B.Parent.Parent = A;
}
if (B.Left != null) B.Left.Parent = A;
if (B.Right != null) B.Right.Parent = A;
if (A.Left != null) A.Left.Parent = B;
if (A.Right != null) A.Right.Parent = B;
SwapNodeReference(ref A.Left, ref B.Left);
SwapNodeReference(ref A.Right, ref B.Right);
SwapNodeReference(ref A.Parent, ref B.Parent);
}
State Balance = A.Balance;
A.Balance = B.Balance;
B.Balance = Balance;
}
}
public struct SetEntry<T> : IEnumerator<T>
{
public SetEntry(Node N) { _Node = N; }
public T Value
{
get
{
return ((SetNode<T>)_Node).Data;
}
}
public bool IsEnd { get { return _Node.IsHeader; } }
public bool MoveNext()
{
_Node = Utility.NextItem(_Node);
return _Node.IsHeader ? false : true;
}
public bool MovePrevious()
{
_Node = Utility.PreviousItem(_Node);
return _Node.IsHeader ? false : true;
}
public static SetEntry<T> operator ++(SetEntry<T> entry)
{
entry._Node = Utility.NextItem(entry._Node);
return entry;
}
public static SetEntry<T> operator --(SetEntry<T> entry)
{
entry._Node = Utility.PreviousItem(entry._Node);
return entry;
}
public void Reset()
{
while (!MoveNext()) ;
}
object System.Collections.IEnumerator.Current
{ get { return ((SetNode<T>)_Node).Data; } }
T IEnumerator<T>.Current
{ get { return ((SetNode<T>)_Node).Data; } }
public static bool operator ==(SetEntry<T> x, SetEntry<T> y) { return x._Node == y._Node; }
public static bool operator !=(SetEntry<T> x, SetEntry<T> y) { return x._Node != y._Node; }
public override bool Equals(object o) { return _Node == ((SetEntry<T>)o)._Node; }
public override int GetHashCode() { return _Node.GetHashCode(); }
public static SetEntry<T> operator +(SetEntry<T> C, ulong Increment)
{
SetEntry<T> Result = new SetEntry<T>(C._Node);
for (ulong i = 0; i < Increment; i++) ++Result;
return Result;
}
public static SetEntry<T> operator +(ulong Increment, SetEntry<T> C)
{
SetEntry<T> Result = new SetEntry<T>(C._Node);
for (ulong i = 0; i < Increment; i++) ++Result;
return Result;
}
public static SetEntry<T> operator -(SetEntry<T> C, ulong Decrement)
{
SetEntry<T> Result = new SetEntry<T>(C._Node);
for (ulong i = 0; i < Decrement; i++) --Result;
return Result;
}
public override string ToString()
{
return Value.ToString();
}
public void Dispose() { }
public Node _Node;
}
class Set<T> : IEnumerable<T>
{
IComparer<T> Comparer;
Node Header;
ulong Nodes;
//*** Constructors ***
public Set()
{
Comparer = Comparer<T>.Default;
Header = new Node();
Nodes = 0;
}
public Set(IComparer<T> c)
{
Comparer = c;
Header = new Node();
Nodes = 0;
}
//*** Properties ***
SetNode<T> Root
{
get { return (SetNode<T>)Header.Parent; }
set { Header.Parent = value; }
}
Node LeftMost
{
get { return Header.Left; }
set { Header.Left = value; }
}
Node RightMost
{
get { return Header.Right; }
set { Header.Right = value; }
}
public SetEntry<T> Begin
{ get { return new SetEntry<T>(Header.Left); } }
public SetEntry<T> End
{ get { return new SetEntry<T>(Header); } }
public ulong Length { get { return Nodes; } }
public ulong Depth { get { return Utility.Depth(Root); } }
//*** Operators ***
public bool this[T key] { get { return Search(key); } }
public static Set<T> operator +(Set<T> set, T t)
{
set.Add(t); return set;
}
public static Set<T> operator -(Set<T> set, T t)
{
set.Remove(t); return set;
}
public static Set<T> operator |(Set<T> A, Set<T> B)
{
Set<T> U = new Set<T>(A.Comparer);
CombineSets(A, B, U, SetOperation.Union);
return U;
}
public static Set<T> operator &(Set<T> A, Set<T> B)
{
Set<T> I = new Set<T>(A.Comparer);
CombineSets(A, B, I, SetOperation.Intersection);
return I;
}
public static Set<T> operator ^(Set<T> A, Set<T> B)
{
Set<T> S = new Set<T>(A.Comparer);
CombineSets(A, B, S, SetOperation.SymmetricDifference);
return S;
}
public static Set<T> operator -(Set<T> A, Set<T> B)
{
Set<T> S = new Set<T>(A.Comparer);
CombineSets(A, B, S, SetOperation.Difference);
return S;
}
public static bool operator ==(Set<T> A, Set<T> B)
{
return CheckSets(A, B, SetOperation.Equality);
}
public static bool operator !=(Set<T> A, Set<T> B)
{
return CheckSets(A, B, SetOperation.Inequality);
}
public override bool Equals(object o)
{
return CheckSets(this, (Set<T>)o, SetOperation.Equality);
}
//*** Methods ***
public void Add(T key)
{
if (Root == null)
{
Root = new SetNode<T>(key, Header);
LeftMost = RightMost = Root;
}
else
{
SetNode<T> Search = Root;
for (; ; )
{
int Compare = Comparer.Compare(key, Search.Data);
if (Compare == 0) // Item Exists
throw new EntryAlreadyExistsException();
else if (Compare < 0)
{
if (Search.Left != null)
Search = (SetNode<T>)Search.Left;
else
{
Search.Left = new SetNode<T>(key, Search);
if (LeftMost == Search) LeftMost = (SetNode<T>)Search.Left;
Utility.BalanceSet(Search, Direction.FromLeft);
Nodes++;
break;
}
}
else
{
if (Search.Right != null)
Search = (SetNode<T>)Search.Right;
else
{
Search.Right = new SetNode<T>(key, Search);
if (RightMost == Search) RightMost = (SetNode<T>)Search.Right;
Utility.BalanceSet(Search, Direction.FromRight);
Nodes++;
break;
}
}
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{ return new SetEntry<T>(Header); }
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{ return new SetEntry<T>(Header); }
public override int GetHashCode()
{
return GetHashCode((SetNode<T>)Header.Parent);
}
int GetHashCode(SetNode<T> Root)
{
if (Root != null)
{
int HashCode = Root.GetHashCode();
if (Root.Left != null)
HashCode += GetHashCode((SetNode<T>)Root.Left);
if (Root.Right != null)
HashCode += GetHashCode((SetNode<T>)Root.Right);
return HashCode;
}
return 0;
}
public void Remove(T key)
{
SetNode<T> root = Root;
for (; ; )
{
if (root == null)
throw new EntryNotFoundException();
int Compare = Comparer.Compare(key, root.Data);
if (Compare < 0)
root = (SetNode<T>)root.Left;
else if (Compare > 0)
root = (SetNode<T>)root.Right;
else // Item is found
{
if (root.Left != null && root.Right != null)
{
SetNode<T> replace = (SetNode<T>)root.Left;
while (replace.Right != null) replace = (SetNode<T>)replace.Right;
Utility.SwapNodes(root, replace);
}
SetNode<T> Parent = (SetNode<T>)root.Parent;
Direction From = (Parent.Left == root) ? Direction.FromLeft : Direction.FromRight;
if (LeftMost == root)
{
SetEntry<T> e = new SetEntry<T>(root); e.MoveNext();
if (e._Node.IsHeader)
{ LeftMost = Header; RightMost = Header; }
else
LeftMost = e._Node;
}
else if (RightMost == root)
{
SetEntry<T> e = new SetEntry<T>(root); e.MovePrevious();
if (e._Node.IsHeader)
{ LeftMost = Header; RightMost = Header; }
else
RightMost = e._Node;
}
if (root.Left == null)
{
if (Parent == Header)
Header.Parent = root.Right;
else if (Parent.Left == root)
Parent.Left = root.Right;
else
Parent.Right = root.Right;
if (root.Right != null) root.Right.Parent = Parent;
}
else
{
if (Parent == Header)
Header.Parent = root.Left;
else if (Parent.Left == root)
Parent.Left = root.Left;
else
Parent.Right = root.Left;
if (root.Left != null) root.Left.Parent = Parent;
}
Utility.BalanceSetRemove(Parent, From);
Nodes--;
break;
}
}
}
public bool Search(T key)
{
if (Root == null)
return false;
else
{
SetNode<T> Search = Root;
do
{
int Result = Comparer.Compare(key, Search.Data);
if (Result < 0) Search = (SetNode<T>)Search.Left;
else if (Result > 0) Search = (SetNode<T>)Search.Right;
else break;
} while (Search != null);
if (Search == null)
return false;
else
return true;
}
}
public override string ToString()
{
string StringOut = "{";
SetEntry<T> start = Begin;
SetEntry<T> end = End;
SetEntry<T> last = End - 1;
while (start != end)
{
string new_StringOut = start.Value.ToString();
if (start != last) new_StringOut = new_StringOut + ",";
StringOut = StringOut + new_StringOut;
++start;
}
StringOut = StringOut + "}";
return StringOut;
}
public void Validate()
{
if (Nodes == 0 || Root == null)
{
if (Nodes != 0) { throw new InvalidEmptyTreeException(); }
if (Root != null) { throw new InvalidEmptyTreeException(); }
if (LeftMost != Header) { throw new InvalidEndItemException(); }
if (RightMost != Header) { throw new InvalidEndItemException(); }
}
Validate(Root);
if (Root != null)
{
SetNode<T> x = Root;
while (x.Left != null) x = (SetNode<T>)x.Left;
if (LeftMost != x) throw new InvalidEndItemException();
SetNode<T> y = Root;
while (y.Right != null) y = (SetNode<T>)y.Right;
if (RightMost != y) throw new InvalidEndItemException();
}
}
void Validate(SetNode<T> root)
{
if (root == null) return;
if (root.Left != null)
{
SetNode<T> Left = (SetNode<T>)root.Left;
if (Comparer.Compare(Left.Data, root.Data) >= 0)
throw new OutOfKeyOrderException();
if (Left.Parent != root)
throw new TreeInvalidParentException();
Validate((SetNode<T>)root.Left);
}
if (root.Right != null)
{
SetNode<T> Right = (SetNode<T>)root.Right;
if (Comparer.Compare(Right.Data, root.Data) <= 0)
throw new OutOfKeyOrderException();
if (Right.Parent != root)
throw new TreeInvalidParentException();
Validate((SetNode<T>)root.Right);
}
ulong depth_Left = root.Left != null ? Utility.Depth(root.Left) : 0;
ulong depth_Right = root.Right != null ? Utility.Depth(root.Right) : 0;
if (depth_Left > depth_Right && depth_Left - depth_Right > 2)
throw new TreeOutOfBalanceException();
if (depth_Left < depth_Right && depth_Right - depth_Left > 2)
throw new TreeOutOfBalanceException();
}
public static void CombineSets(Set<T> A,
Set<T> B,
Set<T> R,
SetOperation operation)
{
IComparer<T> TComparer = R.Comparer;
SetEntry<T> First1 = A.Begin;
SetEntry<T> Last1 = A.End;
SetEntry<T> First2 = B.Begin;
SetEntry<T> Last2 = B.End;
switch (operation)
{
case SetOperation.Union:
while (First1 != Last1 && First2 != Last2)
{
int Order = TComparer.Compare(First1.Value, First2.Value);
if (Order < 0)
{
R.Add(First1.Value);
First1.MoveNext();
}
else if (Order > 0)
{
R.Add(First2.Value);
First2.MoveNext();
}
else
{
R.Add(First1.Value);
First1.MoveNext();
First2.MoveNext();
}
}
while (First1 != Last1)
{
R.Add(First1.Value);
First1.MoveNext();
}
while (First2 != Last2)
{
R.Add(First2.Value);
First2.MoveNext();
}
return;
case SetOperation.Intersection:
while (First1 != Last1 && First2 != Last2)
{
int Order = TComparer.Compare(First1.Value, First2.Value);
if (Order < 0)
First1.MoveNext();
else if (Order > 0)
First2.MoveNext();
else
{
R.Add(First1.Value);
First1.MoveNext();
First2.MoveNext();
}
}
return;
case SetOperation.SymmetricDifference:
while (First1 != Last1 && First2 != Last2)
{
int Order = TComparer.Compare(First1.Value, First2.Value);
if (Order < 0)
{
R.Add(First1.Value);
First1.MoveNext();
}
else if (Order > 0)
{
R.Add(First2.Value);
First2.MoveNext();
}
else
{ First1.MoveNext(); First2.MoveNext(); }
}
while (First1 != Last1)
{
R.Add(First1.Value);
First1.MoveNext();
}
while (First2 != Last2)
{
R.Add(First2.Value);
First2.MoveNext();
}
return;
case SetOperation.Difference:
while (First1 != Last1 && First2 != Last2)
{
int Order = TComparer.Compare(First1.Value, First2.Value);
if (Order < 0)
{
R.Add(First1.Value);
First1.MoveNext();
}
else if (Order > 0)
{
R.Add(First1.Value);
First1.MoveNext();
First2.MoveNext();
}
else
{ First1.MoveNext(); First2.MoveNext(); }
}
while (First1 != Last1)
{
R.Add(First1.Value);
First1.MoveNext();
}
return;
}
throw new InvalidSetOperationException();
}
public static bool CheckSets(Set<T> A,
Set<T> B,
SetOperation operation)
{
IComparer<T> TComparer = A.Comparer;
SetEntry<T> First1 = A.Begin;
SetEntry<T> Last1 = A.End;
SetEntry<T> First2 = B.Begin;
SetEntry<T> Last2 = B.End;
switch (operation)
{
case SetOperation.Equality:
case SetOperation.Inequality:
{
bool Equals = true;
while (First1 != Last1 && First2 != Last2)
{
if (TComparer.Compare(First1.Value, First2.Value) == 0)
{ First1.MoveNext(); First2.MoveNext(); }
else
{ Equals = false; break; }
}
if (Equals)
{
if (First1 != Last1) Equals = false;
if (First2 != Last2) Equals = false;
}
if (operation == SetOperation.Equality)
return Equals;
else
return !Equals;
}
case SetOperation.Subset:
case SetOperation.Superset:
{
bool Subset = true;
while (First1 != Last1 && First2 != Last2)
{
int Order = TComparer.Compare(First1.Value, First2.Value);
if (Order < 0)
{ Subset = false; break; }
else if (Order > 0)
First2.MoveNext();
else
{ First1.MoveNext(); First2.MoveNext(); }
}
if (Subset)
if (First1 != Last1) Subset = false;
if (operation == SetOperation.Subset)
return Subset;
else
return !Subset;
}
}
throw new InvalidSetOperationException();
}
}
public class EntryNotFoundException : Exception
{
static String message = "The requested entry could not be located in the specified collection.";
public EntryNotFoundException() : base(message) { }
}
public class EntryAlreadyExistsException : Exception
{
static String message = "The requested entry already resides in the collection.";
public EntryAlreadyExistsException() : base(message) { }
}
public class InvalidEndItemException : Exception
{
static String message = "The validation routines detected that the end item of a tree is invalid.";
public InvalidEndItemException() : base(message) { }
}
public class InvalidEmptyTreeException : Exception
{
static String message = "The validation routines detected that an empty tree is invalid.";
public InvalidEmptyTreeException() : base(message) { }
}
public class OutOfKeyOrderException : Exception
{
static String message = "A trees was found to be out of key order.";
public OutOfKeyOrderException() : base(message) { }
}
public class TreeInvalidParentException : Exception
{
static String message = "The validation routines detected that the Parent structure of a tree is invalid.";
public TreeInvalidParentException() : base(message) { }
}
public class TreeOutOfBalanceException : Exception
{
static String message = "The validation routines detected that the tree is out of State.";
public TreeOutOfBalanceException() : base(message) { }
}
public class InvalidSetOperationException : Exception
{
static String message = "An invalid set operation was requested.";
public InvalidSetOperationException() : base(message) { }
}
class Program
{
static void Main()
{
Set<string> s = new Set<string>() {"S0","S1","S2","S3","S4",
"S5","S6","S7","S8","S9"};
Console.WriteLine("Depth = {0}", s.Depth);
s.Validate();
for (int i = 0; i < 10; i += 2)
s.Remove("S" + i.ToString());
Console.WriteLine("Depth = {0}", s.Depth);
s.Validate();
Console.WriteLine("{0}", s);
Set<int> A = new Set<int>() { 1, 3, 5, 7 };
Set<int> B = new Set<int>() { 2, 4, 6, 8 };
Set<int> U = A | B;
Console.WriteLine("{0} | {1} == {2}", A, B, U);
}
}
C++
#include <algorithm>
#include <iostream>
/* AVL node */
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete right;
}
};
/* AVL tree */
template <class T>
class AVLtree {
public:
AVLtree(void);
~AVLtree(void);
bool insert(T key);
void deleteKey(const T key);
void printBalance();
private:
AVLnode<T> *root;
AVLnode<T>* rotateLeft ( AVLnode<T> *a );
AVLnode<T>* rotateRight ( AVLnode<T> *a );
AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );
AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );
void rebalance ( AVLnode<T> *n );
int height ( AVLnode<T> *n );
void setBalance ( AVLnode<T> *n );
void printBalance ( AVLnode<T> *n );
};
/* AVL class definition */
template <class T>
void AVLtree<T>::rebalance(AVLnode<T> *n) {
setBalance(n);
if (n->balance == -2) {
if (height(n->left->left) >= height(n->left->right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
}
else if (n->balance == 2) {
if (height(n->right->right) >= height(n->right->left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n->parent != NULL) {
rebalance(n->parent);
}
else {
root = n;
}
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {
AVLnode<T> *b = a->right;
b->parent = a->parent;
a->right = b->left;
if (a->right != NULL)
a->right->parent = a;
b->left = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {
AVLnode<T> *b = a->left;
b->parent = a->parent;
a->left = b->right;
if (a->left != NULL)
a->left->parent = a;
b->right = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {
n->left = rotateLeft(n->left);
return rotateRight(n);
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {
n->right = rotateRight(n->right);
return rotateLeft(n);
}
template <class T>
int AVLtree<T>::height(AVLnode<T> *n) {
if (n == NULL)
return -1;
return 1 + std::max(height(n->left), height(n->right));
}
template <class T>
void AVLtree<T>::setBalance(AVLnode<T> *n) {
n->balance = height(n->right) - height(n->left);
}
template <class T>
void AVLtree<T>::printBalance(AVLnode<T> *n) {
if (n != NULL) {
printBalance(n->left);
std::cout << n->balance << " ";
printBalance(n->right);
}
}
template <class T>
AVLtree<T>::AVLtree(void) : root(NULL) {}
template <class T>
AVLtree<T>::~AVLtree(void) {
delete root;
}
template <class T>
bool AVLtree<T>::insert(T key) {
if (root == NULL) {
root = new AVLnode<T>(key, NULL);
}
else {
AVLnode<T>
*n = root,
*parent;
while (true) {
if (n->key == key)
return false;
parent = n;
bool goLeft = n->key > key;
n = goLeft ? n->left : n->right;
if (n == NULL) {
if (goLeft) {
parent->left = new AVLnode<T>(key, parent);
}
else {
parent->right = new AVLnode<T>(key, parent);
}
rebalance(parent);
break;
}
}
}
return true;
}
template <class T>
void AVLtree<T>::deleteKey(const T delKey) {
if (root == NULL)
return;
AVLnode<T>
*n = root,
*parent = root,
*delNode = NULL,
*child = root;
while (child != NULL) {
parent = n;
n = child;
child = delKey >= n->key ? n->right : n->left;
if (delKey == n->key)
delNode = n;
}
if (delNode != NULL) {
delNode->key = n->key;
child = n->left != NULL ? n->left : n->right;
if (root->key == delKey) {
root = child;
}
else {
if (parent->left == n) {
parent->left = child;
}
else {
parent->right = child;
}
rebalance(parent);
}
}
}
template <class T>
void AVLtree<T>::printBalance() {
printBalance(root);
std::cout << std::endl;
}
int main(void)
{
AVLtree<int> t;
std::cout << "Inserting integer values 1 to 10" << std::endl;
for (int i = 1; i <= 10; ++i)
t.insert(i);
std::cout << "Printing balance: ";
t.printBalance();
}
输出:
Inserting integer values 1 to 10
Printing balance: 0 0 0 1 0 0 0 0 1 0
Java
public class AVLtree {
private Node root;
private static class Node {
private int key;
private int balance;
private int height;
private Node left;
private Node right;
private Node parent;
Node(int key, Node parent) {
this.key = key;
this.parent = parent;
}
}
public boolean insert(int key) {
if (root == null) {
root = new Node(key, null);
return true;
}
Node n = root;
while (true) {
if (n.key == key)
return false;
Node parent = n;
boolean goLeft = n.key > key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key, parent);
} else {
parent.right = new Node(key, parent);
}
rebalance(parent);
break;
}
}
return true;
}
private void delete(Node node) {
if (node.left == null && node.right == null) {
if (node.parent == null) {
root = null;
} else {
Node parent = node.parent;
if (parent.left == node) {
parent.left = null;
} else {
parent.right = null;
}
rebalance(parent);
}
return;
}
if (node.left != null) {
Node child = node.left;
while (child.right != null) child = child.right;
node.key = child.key;
delete(child);
} else {
Node child = node.right;
while (child.left != null) child = child.left;
node.key = child.key;
delete(child);
}
}
public void delete(int delKey) {
if (root == null)
return;
Node child = root;
while (child != null) {
Node node = child;
child = delKey >= node.key ? node.right : node.left;
if (delKey == node.key) {
delete(node);
return;
}
}
}
private void rebalance(Node n) {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
} else if (n.balance == 2) {
if (height(n.right.right) >= height(n.right.left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n.parent != null) {
rebalance(n.parent);
} else {
root = n;
}
}
private Node rotateLeft(Node a) {
Node b = a.right;
b.parent = a.parent;
a.right = b.left;
if (a.right != null)
a.right.parent = a;
b.left = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateRight(Node a) {
Node b = a.left;
b.parent = a.parent;
a.left = b.right;
if (a.left != null)
a.left.parent = a;
b.right = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateLeftThenRight(Node n) {
n.left = rotateLeft(n.left);
return rotateRight(n);
}
private Node rotateRightThenLeft(Node n) {
n.right = rotateRight(n.right);
return rotateLeft(n);
}
private int height(Node n) {
if (n == null)
return -1;
return n.height;
}
private void setBalance(Node... nodes) {
for (Node n : nodes) {
reheight(n);
n.balance = height(n.right) - height(n.left);
}
}
public void printBalance() {
printBalance(root);
}
private void printBalance(Node n) {
if (n != null) {
printBalance(n.left);
System.out.printf("%s ", n.balance);
printBalance(n.right);
}
}
private void reheight(Node node) {
if (node != null) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
}
public static void main(String[] args) {
AVLtree tree = new AVLtree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();
}
}
输出:
Inserting values 1 to 10
Printing balance: 0 0 0 1 0 1 0 0 0
Python
# Module: calculus.py
import enum
class entry_not_found(Exception):
"""Raised when an entry is not found in a collection"""
pass
class entry_already_exists(Exception):
"""Raised when an entry already exists in a collection"""
pass
class state(enum.Enum):
header = 0
left_high = 1
right_high = 2
balanced = 3
class direction(enum.Enum):
from_left = 0
from_right = 1
from abc import ABC, abstractmethod
class comparer(ABC):
@abstractmethod
def compare(self,t):
pass
class node(comparer):
def __init__(self):
self.parent = None
self.left = self
self.right = self
self.balance = state.header
def compare(self,t):
if self.key < t:
return -1
elif t < self.key:
return 1
else:
return 0
def is_header(self):
return self.balance == state.header
def length(self):
if self != None:
if self.left != None:
left = self.left.length()
else:
left = 0
if self.right != None:
right = self.right.length()
else:
right = 0
return left + right + 1
else:
return 0
def rotate_left(self):
_parent = self.parent
x = self.right
self.parent = x
x.parent = _parent
if x.left is not None:
x.left.parent = self
self.right = x.left
x.left = self
return x
def rotate_right(self):
_parent = self.parent
x = self.left
self.parent = x
x.parent = _parent;
if x.right is not None:
x.right.parent = self
self.left = x.right
x.right = self
return x
def balance_left(self):
_left = self.left
if _left is None:
return self;
if _left.balance == state.left_high:
self.balance = state.balanced
_left.balance = state.balanced
self = self.rotate_right()
elif _left.balance == state.right_high:
subright = _left.right
if subright.balance == state.balanced:
self.balance = state.balanced
_left.balance = state.balanced
elif subright.balance == state.right_high:
self.balance = state.balanced
_left.balance = state.left_high
elif subright.balance == left_high:
root.balance = state.right_high
_left.balance = state.balanced
subright.balance = state.balanced
_left = _left.rotate_left()
self.left = _left
self = self.rotate_right()
elif _left.balance == state.balanced:
self.balance = state.left_high
_left.balance = state.right_high
self = self.rotate_right()
return self;
def balance_right(self):
_right = self.right
if _right is None:
return self;
if _right.balance == state.right_high:
self.balance = state.balanced
_right.balance = state.balanced
self = self.rotate_left()
elif _right.balance == state.left_high:
subleft = _right.left;
if subleft.balance == state.balanced:
self.balance = state.balanced
_right.balance = state.balanced
elif subleft.balance == state.left_high:
self.balance = state.balanced
_right.balance = state.right_high
elif subleft.balance == state.right_high:
self.balance = state.left_high
_right.balance = state.balanced
subleft.balance = state.balanced
_right = _right.rotate_right()
self.right = _right
self = self.rotate_left()
elif _right.balance == state.balanced:
self.balance = state.right_high
_right.balance = state.left_high
self = self.rotate_left()
return self
def balance_tree(self, direct):
taller = True
while taller:
_parent = self.parent;
if _parent.left == self:
next_from = direction.from_left
else:
next_from = direction.from_right;
if direct == direction.from_left:
if self.balance == state.left_high:
if _parent.is_header():
_parent.parent = _parent.parent.balance_left()
elif _parent.left == self:
_parent.left = _parent.left.balance_left()
else:
_parent.right = _parent.right.balance_left()
taller = False
elif self.balance == state.balanced:
self.balance = state.left_high
taller = True
elif self.balance == state.right_high:
self.balance = state.balanced
taller = False
else:
if self.balance == state.left_high:
self.balance = state.balanced
taller = False
elif self.balance == state.balanced:
self.balance = state.right_high
taller = True
elif self.balance == state.right_high:
if _parent.is_header():
_parent.parent = _parent.parent.balance_right()
elif _parent.left == self:
_parent.left = _parent.left.balance_right()
else:
_parent.right = _parent.right.balance_right()
taller = False
if taller:
if _parent.is_header():
taller = False
else:
self = _parent
direct = next_from
def balance_tree_remove(self, _from):
if self.is_header():
return;
shorter = True;
while shorter:
_parent = self.parent;
if _parent.left == self:
next_from = direction.from_left
else:
next_from = direction.from_right
if _from == direction.from_left:
if self.balance == state.left_high:
shorter = True
elif self.balance == state.balanced:
self.balance = state.right_high;
shorter = False
elif self.balance == state.right_high:
if self.right is not None:
if self.right.balance == state.balanced:
shorter = False
else:
shorter = True
else:
shorter = False;
if _parent.is_header():
_parent.parent = _parent.parent.balance_right()
elif _parent.left == self:
_parent.left = _parent.left.balance_right();
else:
_parent.right = _parent.right.balance_right()
else:
if self.balance == state.right_high:
self.balance = state.balanced
shorter = True
elif self.balance == state.balanced:
self.balance = state.left_high
shorter = False
elif self.balance == state.left_high:
if self.left is not None:
if self.left.balance == state.balanced:
shorter = False
else:
shorter = True
else:
short = False;
if _parent.is_header():
_parent.parent = _parent.parent.balance_left();
elif _parent.left == self:
_parent.left = _parent.left.balance_left();
else:
_parent.right = _parent.right.balance_left();
if shorter:
if _parent.is_header():
shorter = False
else:
_from = next_from
self = _parent
def previous(self):
if self.is_header():
return self.right
if self.left is not None:
y = self.left
while y.right is not None:
y = y.right
return y
else:
y = self.parent;
if y.is_header():
return y
x = self
while x == y.left:
x = y
y = y.parent
return y
def next(self):
if self.is_header():
return self.left
if self.right is not None:
y = self.right
while y.left is not None:
y = y.left
return y;
else:
y = self.parent
if y.is_header():
return y
x = self;
while x == y.right:
x = y
y = y.parent;
return y
def swap_nodes(a, b):
if b == a.left:
if b.left is not None:
b.left.parent = a
if b.right is not None:
b.right.parent = a
if a.right is not None:
a.right.parent = b
if not a.parent.is_header():
if a.parent.left == a:
a.parent.left = b
else:
a.parent.right = b;
else:
a.parent.parent = b
b.parent = a.parent
a.parent = b
a.left = b.left
b.left = a
temp = a.right
a.right = b.right
b.right = temp
elif b == a.right:
if b.right is not None:
b.right.parent = a
if b.left is not None:
b.left.parent = a
if a.left is not None:
a.left.parent = b
if not a.parent.is_header():
if a.parent.left == a:
a.parent.left = b
else:
a.parent.right = b
else:
a.parent.parent = b
b.parent = a.parent
a.parent = b
a.right = b.right
b.right = a
temp = a.left
a.left = b.left
b.left = temp
elif a == b.left:
if a.left is not None:
a.left.parent = b
if a.right is not None:
a.right.parent = b
if b.right is not None:
b.right.parent = a
if not parent.is_header():
if b.parent.left == b:
b.parent.left = a
else:
b.parent.right = a
else:
b.parent.parent = a
a.parent = b.parent
b.parent = a
b.left = a.left
a.left = b
temp = a.right
a.right = b.right
b.right = temp
elif a == b.right:
if a.right is not None:
a.right.parent = b
if a.left is not None:
a.left.parent = b
if b.left is not None:
b.left.parent = a
if not b.parent.is_header():
if b.parent.left == b:
b.parent.left = a
else:
b.parent.right = a
else:
b.parent.parent = a
a.parent = b.parent
b.parent = a
b.right = a.right
a.right = b
temp = a.left
a.left = b.left
b.left = temp
else:
if a.parent == b.parent:
temp = a.parent.left
a.parent.left = a.parent.right
a.parent.right = temp
else:
if not a.parent.is_header():
if a.parent.left == a:
a.parent.left = b
else:
a.parent.right = b
else:
a.parent.parent = b
if not b.parent.is_header():
if b.parent.left == b:
b.parent.left = a
else:
b.parent.right = a
else:
b.parent.parent = a
if b.left is not None:
b.left.parent = a
if b.right is not None:
b.right.parent = a
if a.left is not None:
a.left.parent = b
if a.right is not None:
a.right.parent = b
temp1 = a.left
a.left = b.left
b.left = temp1
temp2 = a.right
a.right = b.right
b.right = temp2
temp3 = a.parent
a.parent = b.parent
b.parent = temp3
balance = a.balance
a.balance = b.balance
b.balance = balance
class parent_node(node):
def __init__(self, parent):
self.parent = parent
self.left = None
self.right = None
self.balance = state.balanced
class set_node(node):
def __init__(self, parent, key):
self.parent = parent
self.left = None
self.right = None
self.balance = state.balanced
self.key = key
class ordered_set:
def __init__(self):
self.header = node()
def __iter__(self):
self.node = self.header
return self
def __next__(self):
self.node = self.node.next()
if self.node.is_header():
raise StopIteration
return self.node.key
def __delitem__(self, key):
self.remove(key)
def __lt__(self, other):
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while (first1 != last1) and (first2 != last2):
l = first1.key < first2.key
if not l:
first1 = first1.next();
first2 = first2.next();
else:
return True;
a = self.__len__()
b = other.__len__()
return a < b
def __hash__(self):
h = 0
for i in self:
h = h + i.__hash__()
return h
def __eq__(self, other):
if self < other:
return False
if other < self:
return False
return True
def __ne__(self, other):
if self < other:
return True
if other < self:
return True
return False
def __len__(self):
return self.header.parent.length()
def __getitem__(self, key):
return self.contains(key)
def __str__(self):
l = self.header.right
s = "{"
i = self.header.left
h = self.header
while i != h:
s = s + i.key.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s
def __or__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
r.add(first1.key)
first1 = first1.next()
elif graater:
r.add(first2.key)
first2 = first2.next()
else:
r.add(first1.key)
first1 = first1.next()
first2 = first2.next()
while first1 != last1:
r.add(first1.key)
first1 = first1.next()
while first2 != last2:
r.add(first2.key)
first2 = first2.next()
return r
def __and__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
first1 = first1.next()
elif graater:
first2 = first2.next()
else:
r.add(first1.key)
first1 = first1.next()
first2 = first2.next()
return r
def __xor__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
r.add(first1.key)
first1 = first1.next()
elif graater:
r.add(first2.key)
first2 = first2.next()
else:
first1 = first1.next()
first2 = first2.next()
while first1 != last1:
r.add(first1.key)
first1 = first1.next()
while first2 != last2:
r.add(first2.key)
first2 = first2.next()
return r
def __sub__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
r.add(first1.key)
first1 = first1.next()
elif graater:
r.add(first2.key)
first2 = first2.next()
else:
first1 = first1.next()
first2 = first2.next()
while first1 != last1:
r.add(first1.key)
first1 = first1.next()
return r
def __lshift__(self, data):
self.add(data)
return self
def __rshift__(self, data):
self.remove(data)
return self
def is_subset(self, other):
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
is_subet = True
while first1 != last1 and first2 != last2:
if first1.key < first2.key:
is_subset = False
break
elif first2.key < first1.key:
first2 = first2.next()
else:
first1 = first1.next()
first2 = first2.next()
if is_subet:
if first1 != last1:
is_subet = False
return is_subet
def is_superset(self,other):
return other.is_subset(self)
def add(self, data):
if self.header.parent is None:
self.header.parent = set_node(self.header,data)
self.header.left = self.header.parent
self.header.right = self.header.parent
else:
root = self.header.parent
while True:
c = root.compare(data)
if c >= 0:
if root.left is not None:
root = root.left
else:
new_node = set_node(root,data)
root.left = new_node
if self.header.left == root:
self.header.left = new_node
root.balance_tree(direction.from_left)
return
else:
if root.right is not None:
root = root.right
else:
new_node = set_node(root, data)
root.right = new_node
if self.header.right == root:
self.header.right = new_node
root.balance_tree(direction.from_right)
return
def remove(self,data):
root = self.header.parent;
while True:
if root is None:
raise entry_not_found("Entry not found in collection")
c = root.compare(data)
if c < 0:
root = root.left;
elif c > 0:
root = root.right;
else:
if root.left is not None:
if root.right is not None:
replace = root.left
while replace.right is not None:
replace = replace.right
root.swap_nodes(replace)
_parent = root.parent
if _parent.left == root:
_from = direction.from_left
else:
_from = direction.from_right
if self.header.left == root:
n = root.next();
if n.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.left = n
elif self.header.right == root:
p = root.previous();
if p.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.right = p
if root.left is None:
if _parent == self.header:
self.header.parent = root.right
elif _parent.left == root:
_parent.left = root.right
else:
_parent.right = root.right
if root.right is not None:
root.right.parent = _parent
else:
if _parent == self.header:
self.header.parent = root.left
elif _parent.left == root:
_parent.left = root.left
else:
_parent.right = root.left
if root.left is not None:
root.left.parent = _parent;
_parent.balance_tree_remove(_from)
return
def contains(self,data):
root = self.header.parent;
while True:
if root == None:
return False
c = root.compare(data);
if c > 0:
root = root.left;
elif c < 0:
root = root.right;
else:
return True
def find(self,data):
root = self.header.parent;
while True:
if root == None:
raise entry_not_found("An entry is not found in a collection")
c = root.compare(data);
if c > 0:
root = root.left;
elif c < 0:
root = root.right;
else:
return root.key;
class key_value(comparer):
def __init__(self, key, value):
self.key = key
self.value = value
def compare(self,kv):
if self.key < kv.key:
return -1
elif kv.key < self.key:
return 1
else:
return 0
def __lt__(self, other):
return self.key < other.key
def __str__(self):
return '(' + self.key.__str__() + ',' + self.value.__str__() + ')'
def __eq__(self, other):
return self.key == other.key
def __hash__(self):
return hash(self.key)
class dictionary:
def __init__(self):
self.set = ordered_set()
return None
def __lt__(self, other):
if self.keys() < other.keys():
return true
if other.keys() < self.keys():
return false
first1 = self.set.header.left
last1 = self.set.header
first2 = other.set.header.left
last2 = other.set.header
while (first1 != last1) and (first2 != last2):
l = first1.key.value < first2.key.value
if not l:
first1 = first1.next();
first2 = first2.next();
else:
return True;
a = self.__len__()
b = other.__len__()
return a < b
def add(self, key, value):
try:
self.set.remove(key_value(key,None))
except entry_not_found:
pass
self.set.add(key_value(key,value))
return
def remove(self, key):
self.set.remove(key_value(key,None))
return
def clear(self):
self.set.header = node()
def sort(self):
sort_bag = bag()
for e in self:
sort_bag.add(e.value)
keys_set = self.keys()
self.clear()
i = sort_bag.__iter__()
i = sort_bag.__next__()
try:
for e in keys_set:
self.add(e,i)
i = sort_bag.__next__()
except:
return
def keys(self):
keys_set = ordered_set()
for e in self:
keys_set.add(e.key)
return keys_set
def __len__(self):
return self.set.header.parent.length()
def __str__(self):
l = self.set.header.right;
s = "{"
i = self.set.header.left;
h = self.set.header;
while i != h:
s = s + "("
s = s + i.key.key.__str__()
s = s + ","
s = s + i.key.value.__str__()
s = s + ")"
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.set.node = self.set.header
return self
def __next__(self):
self.set.node = self.set.node.next()
if self.set.node.is_header():
raise StopIteration
return key_value(self.set.node.key.key,self.set.node.key.value)
def __getitem__(self, key):
kv = self.set.find(key_value(key,None))
return kv.value
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.set.remove(key_value(key,None))
class array:
def __init__(self):
self.dictionary = dictionary()
return None
def __len__(self):
return self.dictionary.__len__()
def push(self, value):
k = self.dictionary.set.header.right
if k == self.dictionary.set.header:
self.dictionary.add(0,value)
else:
self.dictionary.add(k.key.key+1,value)
return
def pop(self):
if self.dictionary.set.header.parent != None:
data = self.dictionary.set.header.right.key.value
self.remove(self.dictionary.set.header.right.key.key)
return data
def add(self, key, value):
try:
self.dictionary.remove(key)
except entry_not_found:
pass
self.dictionary.add(key,value)
return
def remove(self, key):
self.dictionary.remove(key)
return
def sort(self):
self.dictionary.sort()
def clear(self):
self.dictionary.header = node();
def __iter__(self):
self.dictionary.node = self.dictionary.set.header
return self
def __next__(self):
self.dictionary.node = self.dictionary.node.next()
if self.dictionary.node.is_header():
raise StopIteration
return self.dictionary.node.key.value
def __getitem__(self, key):
kv = self.dictionary.set.find(key_value(key,None))
return kv.value
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.dictionary.remove(key)
def __lshift__(self, data):
self.push(data)
return self
def __lt__(self, other):
return self.dictionary < other.dictionary
def __str__(self):
l = self.dictionary.set.header.right;
s = "{"
i = self.dictionary.set.header.left;
h = self.dictionary.set.header;
while i != h:
s = s + i.key.value.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
class bag:
def __init__(self):
self.header = node()
def __iter__(self):
self.node = self.header
return self
def __delitem__(self, key):
self.remove(key)
def __next__(self):
self.node = self.node.next()
if self.node.is_header():
raise StopIteration
return self.node.key
def __str__(self):
l = self.header.right;
s = "("
i = self.header.left;
h = self.header;
while i != h:
s = s + i.key.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + ")"
return s;
def __len__(self):
return self.header.parent.length()
def __lshift__(self, data):
self.add(data)
return self
def add(self, data):
if self.header.parent is None:
self.header.parent = set_node(self.header,data)
self.header.left = self.header.parent
self.header.right = self.header.parent
else:
root = self.header.parent
while True:
c = root.compare(data)
if c >= 0:
if root.left is not None:
root = root.left
else:
new_node = set_node(root,data)
root.left = new_node
if self.header.left == root:
self.header.left = new_node
root.balance_tree(direction.from_left)
return
else:
if root.right is not None:
root = root.right
else:
new_node = set_node(root, data)
root.right = new_node
if self.header.right == root:
self.header.right = new_node
root.balance_tree(direction.from_right)
return
def remove_first(self,data):
root = self.header.parent;
while True:
if root is None:
return False;
c = root.compare(data);
if c > 0:
root = root.left;
elif c < 0:
root = root.right;
else:
if root.left is not None:
if root.right is not None:
replace = root.left;
while replace.right is not None:
replace = replace.right;
root.swap_nodes(replace);
_parent = root.parent
if _parent.left == root:
_from = direction.from_left
else:
_from = direction.from_right
if self.header.left == root:
n = root.next();
if n.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.left = n;
elif self.header.right == root:
p = root.previous();
if p.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.right = p
if root.left is None:
if _parent == self.header:
self.header.parent = root.right
elif _parent.left == root:
_parent.left = root.right
else:
_parent.right = root.right
if root.right is not None:
root.right.parent = _parent
else:
if _parent == self.header:
self.header.parent = root.left
elif _parent.left == root:
_parent.left = root.left
else:
_parent.right = root.left
if root.left is not None:
root.left.parent = _parent;
_parent.balance_tree_remove(_from)
return True;
def remove(self,data):
success = self.remove_first(data)
while success:
success = self.remove_first(data)
def remove_node(self, root):
if root.left != None and root.right != None:
replace = root.left
while replace.right != None:
replace = replace.right
root.swap_nodes(replace)
parent = root.parent;
if parent.left == root:
next_from = direction.from_left
else:
next_from = direction.from_right
if self.header.left == root:
n = root.next()
if n.is_header():
self.header.left = self.header;
self.header.right = self.header
else:
self.header.left = n
elif self.header.right == root:
p = root.previous()
if p.is_header():
root.header.left = root.header
root.header.right = header
else:
self.header.right = p
if root.left == None:
if parent == self.header:
self.header.parent = root.right
elif parent.left == root:
parent.left = root.right
else:
parent.right = root.right
if root.right != None:
root.right.parent = parent
else:
if parent == self.header:
self.header.parent = root.left
elif parent.left == root:
parent.left = root.left
else:
parent.right = root.left
if root.left != None:
root.left.parent = parent;
parent.balance_tree_remove(next_from)
def remove_at(self, data, ophset):
p = self.search(data);
if p == None:
return
else:
lower = p
after = after(data)
s = 0
while True:
if ophset == s:
remove_node(lower);
return;
lower = lower.next_node()
if after == lower:
break
s = s+1
return
def search(self, key):
s = before(key)
s.next()
if s.is_header():
return None
c = s.compare(s.key)
if c != 0:
return None
return s
def before(self, data):
y = self.header;
x = self.header.parent;
while x != None:
if x.compare(data) >= 0:
x = x.left;
else:
y = x;
x = x.right;
return y
def after(self, data):
y = self.header;
x = self.header.parent;
while x != None:
if x.compare(data) > 0:
y = x
x = x.left
else:
x = x.right
return y;
def find(self,data):
root = self.header.parent;
results = array()
while True:
if root is None:
break;
p = self.before(data)
p = p.next()
if not p.is_header():
i = p
l = self.after(data)
while i != l:
results.push(i.key)
i = i.next()
return results
else:
break;
return results
class bag_dictionary:
def __init__(self):
self.bag = bag()
return None
def add(self, key, value):
self.bag.add(key_value(key,value))
return
def remove(self, key):
self.bag.remove(key_value(key,None))
return
def remove_at(self, key, index):
self.bag.remove_at(key_value(key,None), index)
return
def clear(self):
self.bag.header = node()
def __len__(self):
return self.bag.header.parent.length()
def __str__(self):
l = self.bag.header.right;
s = "{"
i = self.bag.header.left;
h = self.bag.header;
while i != h:
s = s + "("
s = s + i.key.key.__str__()
s = s + ","
s = s + i.key.value.__str__()
s = s + ")"
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.bag.node = self.bag.header
return self
def __next__(self):
self.bag.node = self.bag.node.next()
if self.bag.node.is_header():
raise StopIteration
return key_value(self.bag.node.key.key,self.bag.node.key.value)
def __getitem__(self, key):
kv_array = self.bag.find(key_value(key,None))
return kv_array
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.bag.remove(key_value(key,None))
class unordered_set:
def __init__(self):
self.bag_dictionary = bag_dictionary()
def __len__(self):
return self.bag_dictionary.__len__()
def __hash__(self):
h = 0
for i in self:
h = h + i.__hash__()
return h
def __eq__(self, other):
for t in self:
if not other.contains(t):
return False
for u in other:
if self.contains(u):
return False
return true;
def __ne__(self, other):
return not self == other
def __or__(self, other):
r = unordered_set()
for t in self:
r.add(t);
for u in other:
if not self.contains(u):
r.add(u);
return r
def __and__(self, other):
r = unordered_set()
for t in self:
if other.contains(t):
r.add(t)
for u in other:
if self.contains(u) and not r.contains(u):
r.add(u);
return r
def __xor__(self, other):
r = unordered_set()
for t in self:
if not other.contains(t):
r.add(t)
for u in other:
if not self.contains(u) and not r.contains(u):
r.add(u)
return r
def __sub__(self, other):
r = ordered_set()
for t in self:
if not other.contains(t):
r.add(t);
return r
def __lshift__(self, data):
self.add(data)
return self
def __rshift__(self, data):
self.remove(data)
return self
def __getitem__(self, key):
return self.contains(key)
def is_subset(self, other):
is_subet = True
for t in self:
if not other.contains(t):
subset = False
break
return is_subet
def is_superset(self,other):
return other.is_subset(self)
def add(self, value):
if not self.contains(value):
self.bag_dictionary.add(hash(value),value)
else:
raise entry_already_exists("Entry already exists in the unordered set")
def contains(self, data):
if self.bag_dictionary.bag.header.parent == None:
return False;
else:
index = hash(data);
_search = self.bag_dictionary.bag.header.parent;
search_index = _search.key.key;
if index < search_index:
_search = _search.left
elif index > search_index:
_search = _search.right
if _search == None:
return False
while _search != None:
search_index = _search.key.key;
if index < search_index:
_search = _search.left
elif index > search_index:
_search = _search.right
else:
break
if _search == None:
return False
return self.contains_node(data, _search)
def contains_node(self,data,_node):
previous = _node.previous()
save = _node
while not previous.is_header() and previous.key.key == _node.key.key:
save = previous;
previous = previous.previous()
c = _node.key.value
_node = save
if c == data:
return True
next = _node.next()
while not next.is_header() and next.key.key == _node.key.key:
_node = next
c = _node.key.value
if c == data:
return True;
next = _node.next()
return False;
def find(self,data,_node):
previous = _node.previous()
save = _node
while not previous.is_header() and previous.key.key == _node.key.key:
save = previous;
previous = previous.previous();
_node = save;
c = _node.key.value
if c == data:
return _node
next = _node.next()
while not next.is_header() and next.key.key == _node.key.key:
_node = next
c = _node.data.value
if c == data:
return _node
next = _node.next()
return None
def search(self, data):
if self.bag_dictionary.bag.header.parent == None:
return None
else:
index = hash(data)
_search = self.bag_dictionary.bag.header.parent
c = _search.key.key
if index < c:
_search = _search.left;
elif index > c:
_search = _search.right;
while _search != None:
if index != c:
break
c = _search.key.key
if index < c:
_search = _search.left;
elif index > c:
_search = _search.right;
else:
break
if _search == None:
return None
return self.find(data, _search)
def remove(self,data):
found = self.search(data);
if found != None:
self.bag_dictionary.bag.remove_node(found);
else:
raise entry_not_found("Entry not found in the unordered set")
def clear(self):
self.bag_dictionary.bag.header = node()
def __str__(self):
l = self.bag_dictionary.bag.header.right;
s = "{"
i = self.bag_dictionary.bag.header.left;
h = self.bag_dictionary.bag.header;
while i != h:
s = s + i.key.value.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.bag_dictionary.bag.node = self.bag_dictionary.bag.header
return self
def __next__(self):
self.bag_dictionary.bag.node = self.bag_dictionary.bag.node.next()
if self.bag_dictionary.bag.node.is_header():
raise StopIteration
return self.bag_dictionary.bag.node.key.value
class map:
def __init__(self):
self.set = unordered_set()
return None
def __len__(self):
return self.set.__len__()
def add(self, key, value):
try:
self.set.remove(key_value(key,None))
except entry_not_found:
pass
self.set.add(key_value(key,value))
return
def remove(self, key):
self.set.remove(key_value(key,None))
return
def clear(self):
self.set.clear()
def __str__(self):
l = self.set.bag_dictionary.bag.header.right;
s = "{"
i = self.set.bag_dictionary.bag.header.left;
h = self.set.bag_dictionary.bag.header;
while i != h:
s = s + "("
s = s + i.key.value.key.__str__()
s = s + ","
s = s + i.key.value.value.__str__()
s = s + ")"
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.set.node = self.set.bag_dictionary.bag.header
return self
def __next__(self):
self.set.node = self.set.node.next()
if self.set.node.is_header():
raise StopIteration
return key_value(self.set.node.key.key,self.set.node.key.value)
def __getitem__(self, key):
kv = self.set.find(key_value(key,None))
return kv.value
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.remove(key)