Data structures and algorithms (C # implementation) series --- demonstration (III)
Heavenkiller (original)
Public static void ShowSortedList_Polynomial ()
{
// 100 + 10 * x + x ^ 2 + 1 + 10 * x + 100x ^ 2
SortedList tmpListA = new SortedList ();
SortedList tmpListB = new SortedList ();
SortedList tmpListC = new SortedList (); // used to store the result
SortedList tmpKeyList = new SortedList (); // used to store all keys of two polynomials
// Init polynomial A and show it
TmpListA. Add (0,100 );
TmpListA. Add (1, 10 );
TmpListA. Add (2, 1 );
ShowSortedList_ShowPolynomial ("tmpListA", tmpListA. GetEnumerator ());
// Init polynomial B and show it
TmpListB. Add (0, 1 );
TmpListB. Add (1, 10 );
TmpListB. Add (2,100 );
ShowSortedList_ShowPolynomial ("tmpListB", tmpListB. GetEnumerator ());
// Init the key list which contains all keys of A and B but everyone once
IDictionaryEnumerator tmpIDic = tmpListA. GetEnumerator ();
While (tmpIDic. MoveNext ()! = False)
{
If (! TmpKeyList. ContainsKey (tmpIDic. Key ))
{
TmpKeyList. Add (tmpIDic. Key, null );
}
}
TmpIDic = tmpListB. GetEnumerator ();
While (tmpIDic. MoveNext ()! = False)
{
If (! TmpKeyList. ContainsKey (tmpIDic. Key ))
{
TmpKeyList. Add (tmpIDic. Key, null );
}
}
// Add A and B and show the result
TmpIDic = tmpKeyList. GetEnumerator ();
While (tmpIDic. MoveNext ()! = False)
{
Object objA = null, objB = null, objC = null;
ObjC = tmpIDic. Key;
If (tmpListA. ContainsKey (objC ))
ObjA = tmpListA [objC];
If (tmpListA. ContainsKey (objC ))
ObjB = tmpListB [objC];
// ObjC = objA + objB;
// TmpKeyList [objC] = (int) objA + (int) objC;
TmpListC. Add (objC, (int) objA + (int) objB );
}
ShowSortedList_ShowPolynomial ("the addition result of A and B", tmpListC. GetEnumerator ());
}
Public static void ShowSortedList_ShowPolynomial (string tip, IDictionaryEnumerator iDic)
{
String strExpress = null;
IDic. Reset ();
While (iDic. MoveNext ()! = False)
{
StrExpress + = iDic. Value. ToString () + "* X ^" + iDic. Key. ToString () + "+ ";
}