示例#1
0
int TestRedBlackTree_CString()
{
	RedBlackTree<const char *, const char *> *rbtree = new RedBlackTree<const char *, const char *>();
	char                                     *tmp;

	TEST_ASSERT(rbtree->size() == 0);

	/* If the tree is properly encapsulated, this won't cause an error on test #1. */
	tmp = cc_strdup("first");
	rbtree->insert(tmp, "one");
	free(tmp); tmp = NULL;

	TEST_ASSERT(rbtree->size() == 1);

	rbtree->insert("second", "two");
	rbtree->insert("third", "three");
	rbtree->insert("fourth", "four");

	TEST_ASSERT(rbtree->size() == 4);

	const char *res = NULL;
	TEST_ASSERT(rbtree->find("first", res));

	const char *tmp1 = "one";
	TEST_ASSERT(Compare(res, tmp1) == 0);

	TEST_ASSERT(!rbtree->exists("fifth"));

	TEST_ASSERT(rbtree->exists("second"));
	TEST_ASSERT(rbtree->find("second", res));

	tmp1 = "two";
	TEST_ASSERT(Compare(res, tmp1) == 0);

	TEST_ASSERT(!rbtree->erase("fifth"));
	TEST_ASSERT(rbtree->size() == 4);

	TEST_ASSERT(rbtree->exists("first"));
	TEST_ASSERT(rbtree->erase("first"));
	TEST_ASSERT(rbtree->size() == 3);

	TEST_ASSERT(rbtree->exists("second"));
	TEST_ASSERT(rbtree->erase("second"));
	TEST_ASSERT(rbtree->size() == 2);

	TEST_ASSERT(rbtree->exists("third"));
	TEST_ASSERT(rbtree->erase("third"));
	TEST_ASSERT(rbtree->size() == 1);

	TEST_ASSERT(rbtree->exists("fourth"));
	TEST_ASSERT(rbtree->erase("fourth"));
	TEST_ASSERT(rbtree->size() == 0);

	delete rbtree;
	return 0;
}
示例#2
0
TEST_F(TestRBTree, RedBlackTree)
{
    RedBlackTree<int32> tree;
    
    tree.insert(1);
    tree.insert(2);
    tree.insert(3);
    
    tree.dump();
}
示例#3
0
int TestRedBlackTree_String()
{
	RedBlackTree<std::string, std::string> *rbtree = new RedBlackTree<std::string, std::string>();

	TEST_ASSERT(rbtree->size() == 0);

	rbtree->insert("first", "one");
	rbtree->insert("second", "two");
	rbtree->insert("third", "three");
	rbtree->insert("fourth", "four");

	std::string                             res;

	TEST_ASSERT(rbtree->size() == 4);

	TEST_ASSERT(rbtree->find("first", res));
	TEST_ASSERT(res == "one");

	TEST_ASSERT(!rbtree->exists("fifth"));

	TEST_ASSERT(rbtree->exists("second"));
	TEST_ASSERT(rbtree->find("second", res));

	TEST_ASSERT(res == "two");

	TEST_ASSERT(!rbtree->erase("fifth"));
	TEST_ASSERT(rbtree->size() == 4);

	TEST_ASSERT(rbtree->exists("first"));
	TEST_ASSERT(rbtree->erase("first"));
	TEST_ASSERT(rbtree->size() == 3);

	TEST_ASSERT(rbtree->exists("second"));
	TEST_ASSERT(rbtree->erase("second"));
	TEST_ASSERT(rbtree->size() == 2);

	TEST_ASSERT(rbtree->exists("third"));
	TEST_ASSERT(rbtree->erase("third"));
	TEST_ASSERT(rbtree->size() == 1);

	TEST_ASSERT(rbtree->exists("fourth"));
	TEST_ASSERT(rbtree->erase("fourth"));
	TEST_ASSERT(rbtree->size() == 0);

	delete rbtree;
	return 0;
}
示例#4
0
int main() 
{
	RedBlackTree<int, int> tree;
	/*for(int i = 0; i<10; i++) {
		std::pair<int, int> item;
		item.first = i; item.second = i;
		tree.insert(item);
	}*/
	std::pair<int, int> item;
	item.first = 0; item.second = 0;
	tree.insert(item);	
	tree.print();
	item.first = 1; item.second = 1;
	tree.insert(item);
	tree.print();
	item.first = 2; item.second = 2;
	tree.insert(item);
	tree.print();
	item.first = 3; item.second = 2;
	tree.insert(item);
	tree.print();
	item.first = 4; item.second = 2;
	tree.insert(item);
	tree.print();
	item.first = 6; item.second = 2;
	tree.insert(item);
	tree.print();
	item.first = 1; item.second = 2;
	tree.insert(item);
	tree.print();
	for(BinarySearchTree<int, int>::iterator it = tree.begin(); it != tree.end(); ++it) {
		std::cout << it->first << " ";
	}
	return 0;
}
示例#5
0
int TestRedBlackTree_Int()
{
	RedBlackTree<int, int> *rbtree = new RedBlackTree<int, int>();

	TEST_ASSERT(rbtree->size() == 0);

	rbtree->insert(1, 1);
	rbtree->insert(2, 2);
	rbtree->insert(3, 3);
	rbtree->insert(4, 4);

	int                     res;
	TEST_ASSERT(rbtree->size() == 4);

	TEST_ASSERT(rbtree->find(1, res));
	TEST_ASSERT(res == 1);

	TEST_ASSERT(!rbtree->exists(5));

	TEST_ASSERT(rbtree->find(2, res));
	TEST_ASSERT(res == 2);

	TEST_ASSERT(!rbtree->erase(5));
	TEST_ASSERT(rbtree->size() == 4);

	TEST_ASSERT(rbtree->exists(1));
	TEST_ASSERT(rbtree->erase(1));
	TEST_ASSERT(rbtree->size() == 3);

	TEST_ASSERT(rbtree->exists(2));
	TEST_ASSERT(rbtree->erase(2));
	TEST_ASSERT(rbtree->size() == 2);

	TEST_ASSERT(rbtree->exists(3));
	TEST_ASSERT(rbtree->erase(3));
	TEST_ASSERT(rbtree->size() == 1);

	TEST_ASSERT(rbtree->exists(4));
	TEST_ASSERT(rbtree->erase(4));
	TEST_ASSERT(rbtree->size() == 0);

	delete rbtree;
	return 0;
}
示例#6
0
int main()
{
	RedBlackTree t;
	for (unsigned i = 1000; i > 0; --i)
	{
		int k = static_cast<int>(rand());
		cout << "inserting " << k << endl;
		t.insert(k);
	}
}
bool test_redblack()
{
	RedBlackTree<int> rbt;
	int lim = 1000;
	srand(time(NULL));
	for(int i = 0; i < lim; i++)
	{
		rbt.insert((i + lim ) % lim);
	}

	int *sorted = rbt.inorder();
	printf("\n");
	for(int i = 0; i < 15; i++)
	{
		printf("%d", sorted[i]);
	}
	printf("\n");
	return true;
}
示例#8
0
int main(int argc, char const *argv[])
{
	RedBlackTree<int, string> sample;
	sample.insert(make_pair(10,"haha"));
	sample.insert(make_pair(20,"haha"));
	sample.insert(make_pair(30,"haha"));
	sample.insert(make_pair(15,"haha"));
	sample.insert(make_pair(25,"haha"));
	sample.insert(make_pair(12,"haha"));
	sample.insert(make_pair(5,"haha"));
	sample.insert(make_pair(3,"haha"));
	sample.insert(make_pair(8,"haha"));
	sample.insert(make_pair(27,"haha"));
	sample.insert(make_pair(40,"haha"));
	sample.insert(make_pair(50,"haha"));
	sample.insert(make_pair(45,"haha"));
	sample.insert(make_pair(9,"haha"));


	sample.print();
	return 0;
}
示例#9
0
int main()
{
	srand(time(0));

	BinarySearchTree BST;
	RedBlackTree RBT;

	cout << "Inserting 1000 ordered elements into a Binary Search Tree and a Red Black Tree:" << endl << endl;

	for (int i = 0; i < 1000; i++)
	{
		BST.insert(i);
		RBT.insert(i);
	}

	cout << "Height of the Binary Search Tree: " << BST.height() << endl;
	cout << "Height of the Red Black Tree: "     << RBT.height() << endl;

	cout << endl;
	
	BinarySearchTree BST2;
	RedBlackTree RBT2;

	cout << "Inserting 1000 random elements into a Binary Search Tree and a Red Black Tree:" << endl << endl;

	int r;

	for (int i = 0; i < 1000; i++)
	{
		r = rand() % 1000;

		BST2.insert(r);
		RBT2.insert(r);
	}

	cout << "Height of the Binary Search Tree: " << BST2.height() << endl;
	cout << "Height of the Red Black Tree: "     << RBT2.height() << endl;

	cout << endl;
	
}
示例#10
0
文件: test.cpp 项目: JWangatang/CS104
int main(){
	RedBlackTree<int, char>* tree = new RedBlackTree<int,char>();

	cout << "Constructed Tree" << endl;

	cout << "Insert 10, A" << endl;
	pair<int, char> p1(10,'a');
	tree->insert(p1);
	tree->print2();
	cout << endl;

	cout << "Insert Duplicate 10, X" << endl;
	pair<int, char> p123(10,'x');
	tree->insert(p123);
	tree->print2();
	cout << endl;

	cout << "Insert 20, B" << endl;
	pair<int, char> p2(20,'b');
	tree->insert(p2);
	tree->print2();
	cout << endl;

	cout << "Insert 30, C" << endl;
	pair<int, char> p3(30,'c');
	tree->insert(p3);
	tree->print2();
	cout << endl;


	cout << "Insert 15, D" << endl;
	pair<int, char> p4(15,'d');
	tree->insert(p4);
	tree->print2();
	cout << endl;

	cout << "Insert 25, E" << endl;
	pair<int, char> p5(25,'e');
	tree->insert(p5);
	tree->print2();
	cout << endl;

	cout << "Insert 12, F" << endl;
	pair<int, char> p6(12,'f');
	tree->insert(p6);
	tree->print2();
	cout << endl;

	cout << "Insert 5, G" << endl;
	pair<int, char> p7(5,'g');
	tree->insert(p7);
	tree->print2();
	cout << endl;
	
	cout << "Insert 3, H" << endl;
	pair<int, char> p8(3,'h');
	tree->insert(p8);
	tree->print2();
	cout << endl;

	cout << "Insert 8, I" << endl;
	pair<int, char> p9(8,'i');
	tree->insert(p9);
	tree->print2();
	cout << endl;

	cout << "Insert 27, j" << endl;
	pair<int, char> p10(27,'j');
	tree->insert(p10);
	tree->print2();
	cout << endl;

	cout << "Insert 40, k" << endl;
	pair<int, char> p11(40,'k');
	tree->insert(p11);
	tree->print2();
	cout << endl;

	cout << "Insert 50, z" << endl;
	pair<int, char> p14(50,'z');
	tree->insert(p14);
	tree->print2();
	cout << endl;

	cout << "Insert 45, l" << endl;
	pair<int, char> p12(45,'l');
	tree->insert(p12);
	tree->print2();
	cout << endl;

	cout << "Insert 9, m" << endl;
	pair<int, char> p13(9,'m');
	tree->insert(p13);
	tree->print2();
	cout << endl;
	
	
	cout << "Testing Iteration:" << endl;
	for(RedBlackTree<int,char>::iterator it = tree->begin(); it!=tree->end(); ++it){
		cout << (*it).first << " ";
	}
	cout << endl;

	return 0;
}
示例#11
0
int main(int argc, const char * argv[]) {
    /*****************************
     Test 1: increasing input
     ***************************/
    RedBlackTree<int> mytree;
    
    for(int k = 0; k < 100000; k++){
        mytree.insert(k, k);
    }
    
    //checks
    if(mytree.testBlackHeight()){
        std::cout << "Passed 1st black height test\n";
    }
    else{
        std::cout << "Failed 1st black height test\n";
    }
    
    int height = mytree.getHeight();
    
    std::cout << "Height: " << height << std::endl;
    
    //The claim: Every Red Black Tree with n nodes has height <= 2 * Log_2(n+1)
    
    if(mytree.heightVSsizeTest()){
        std::cout << "passed 1st height vs size test\n";
    }
    else{
        std::cout << "Failed 1st height vs size test\n";
    }
    /*****************************
     Test 2: decreasing input
     ***************************/
    RedBlackTree<int> mytree2;
    
    for(int k = 100000; k > 0; k--){
        mytree2.insert(k, k);
    }
    
    //checks
    if(mytree2.testBlackHeight()){
        std::cout << "Passed 2nd black height test\n";
    }
    else{
        std::cout << "Failed 2nd black height test\n";
    }
    
    int height2 = mytree2.getHeight();
    
    std::cout << "Height: " << height2 << std::endl;
    
    //The claim: Every Red Black Tree with n nodes has height <= 2 * Log_2(n+1)
    
    if(mytree2.heightVSsizeTest()){
        std::cout << "passed 2nd height vs size test\n";
    }
    else{
        std::cout << "Failed 2nd height vs size test\n";
    }
    /*****************************
     Test 3: 100 random trees with 100,000 inputs
     ***************************/
    srand(time(0));
    bool blackTest = true;
    bool hVsTest = true;
    double avgheight = 0;
    for(int j = 0; j < 100; j++){
        RedBlackTree<int> mytree4;
        
        for(int k = 0; k < 100000; k++){
            int x = rand()%100000;
            mytree4.insert(x, k);
        }
        //checks
        if(!mytree4.testBlackHeight()){
            blackTest = false;
        }
        
        if(!mytree4.heightVSsizeTest()){
            hVsTest = false;
        }
        
        avgheight = avgheight + mytree4.getHeight();
    }
    
    avgheight = avgheight/100;
    
    std::cout << "Average height: " << avgheight << std::endl;
    
    if(mytree2.testBlackHeight()){
        std::cout << "Passed multi-black height test\n";
    }
    else{
        std::cout << "Failed multi-black height test\n";
    }
    
    if(mytree2.heightVSsizeTest()){
        std::cout << "passed multi-height vs size test\n";
    }
    else{
        std::cout << "Failed multi-height vs size test\n";
    }
    
    /*****************************
     Test 4: testing ordering
     ***************************/
    RedBlackTree<int> mytree6;
    for(int k = 0; k < 100; k++){
        int x = rand()%100;
        mytree6.insert(x, x);
    }
    std::cout << "Inorder traversal:\n";
    mytree6.inorder();
    
    /**************************
     More random testing
     *************************/
    RedBlackTree<int> mytree8;
    //test case that was previously breaking the tree
    mytree8.insert(36, 36);
    mytree8.insert(58, 58);
    mytree8.insert(40, 40);
    mytree8.insert(71, 71);
    mytree8.insert(56, 56);
    
    std::cout << std::endl;
    mytree8.inorder();
    std::cout << std::endl;
    
    


    return 0;
}
示例#12
0
void ParseMemoryLeakFile(const char *_inputFilename, const char *_outputFilename)
{
	/* */
	/* Start up */
	/* */

	RedBlackTree<char *, int> combined;
	RedBlackTree<char *, int> frequency;
	int                       unrecognised = 0;

	/* */
	/* Open the file and start parsing */
	/* */

	FILE                     *memoryfile = fopen(_inputFilename, "rb");

	while (memoryfile && !feof(memoryfile))	{
		char thisline[1024];

		fgets(thisline, 1024, memoryfile);

		if (!strncmp(thisline, " Data:", 6) == 0) { /* This line is a data line - useless to us */
			if (strchr(thisline, ':')) {                               /* This line does not have a source file location - useless to us */
				/* Get the size */

				char *lastcomma = strrchr(thisline, ',');
				if (lastcomma == 0) continue;

				char *ssize = lastcomma + 2;
				int   size;
				char  unused[32];

				sscanf(ssize, "%d %s", &size, unused);

				/* Get the source file name */

				char *sourcelocation = thisline;
				char *colon = strrchr(thisline, ':');

				*(colon - 1) = '\x0';

				/* Put the result into our BTree */

				int   result = 0;
				bool  found = combined.find(sourcelocation, result);

				if (found)
					combined.replace(sourcelocation, result + size);
				else
					combined.insert(sourcelocation, size);

				found = frequency.find(sourcelocation, result);

				if (frequency.exists(sourcelocation))
					frequency.replace(sourcelocation, result + size);
				else
					frequency.insert(sourcelocation, 1);
			} else {
				char *lastcomma = strrchr(thisline, ',');

				if (lastcomma) {
					char *ssize = lastcomma + 2;
					int   size;
					char  unused[32];

					sscanf(ssize, "%d %s", &size, unused);

					unrecognised += size;
				}
			}
		}
	}

	fclose(memoryfile);


	/* */
	/* Sort the results into a list */
	/* */

	LList<char *>   sorted;
	DArray<char *> *dataI = combined.ConvertIndexToDArray();
	DArray<int>    *dataD = combined.ConvertToDArray();

	int             totalsize = 0;

	for (size_t i = 0; i < dataI->size(); i++) {
		if (dataI->valid(i)) {
			char *newsource = dataI->get(i);
			int   newsize = dataD->get(i);

			totalsize += newsize;
			bool  inserted = false;

			for (size_t i = 0; i < sorted.size(); i++) {
				char *existingsource = sorted.get(i);
				int   existingsize;

				combined.find(existingsource, existingsize);

				if (newsize <= existingsize) {
					sorted.insert_at(newsource, i);
					inserted = true;
					break;
				}
			}

			if (!inserted)
				sorted.insert(newsource);
		}
	}

	delete dataI;
	delete dataD;


	/* */
	/* Open the output file */
	/* */

	if (sorted.size()) {
		FILE *output = fopen(_outputFilename, "wt");

		/* */
		/* Print out our sorted list */
		/* */

		fprintf(output, "Total recognised memory leaks   : %d Kbytes\n",
		        int( totalsize / 1024 ));
		fprintf(output, "Total unrecognised memory leaks : %d Kbytes\n\n",
		        int( unrecognised / 1024 ));

		for (int k = (int)sorted.size() - 1; k >= 0 && k < (int)sorted.size(); k--) {
			char *source = sorted.get(k);
			CoreAssert(source);
			int   size; combined.find(source, size);
			int   freq; frequency.find(source, freq);

			if (size > 1048576) {
				fprintf(output, "%-95s (%d MB in %d leaks)\n", source,
				        int( size / 1048576 ), freq);
			} else if (size > 2048) {
				fprintf(output, "%-95s (%d KB in %d leaks)\n", source,
				        int( size / 1024 ), freq);
			} else {
				fprintf(output, "%-95s (%d  bytes in %d leaks)\n", source, size,
				        freq);
			}
		}

		/* */
		/* Clean up */

		fclose(output);
	}
}
示例#13
0
int main(int argc, const char *argv[]) {
// Make sure the right number of command line arguments exist.
    if (!(argc == 3 || argc == 2)) {
        cerr << "Usage: " << argv[0] << " <filename> [limit]" << endl;
        return 1;
    }
// Create an ifstream object.
    ifstream input_file(argv[1]);
// If it does not exist, print an error message.
    if (!input_file) {
        cerr << "Error: Cannot open file '" << argv[1] << "' for input."
                << endl;
        return 1;
    }

    if (argc == 3 && !is_number(argv[2])) {
        cerr << "Error: Invalid limit '" << argv[2] << "' received." << endl;
        return 1;
    }

    int limit;
    if (argc == 3) {
        limit = atoi(argv[2]);
    } else {
        limit = 10;
    }

    if (limit < 0) {
        cerr << "Error: Invalid limit '" << argv[2] << "' received." << endl;
        return 1;
    }

    RedBlackTree<string, int> *tree;
    tree = new RedBlackTree<string, int>();
// Add read errors to the list of exceptions the ifstream will handle.
    input_file.exceptions(ifstream::badbit);
    string line;
    unsigned int maxwordwidth = 0;

    try {

        // Use getline to read in a line.
        // See http://www.cplusplus.com/reference/string/string/getline/

        while (getline(input_file, line)) {
            string buf; // Have a buffer string
            stringstream ss(line); // Insert the string into a stream

            vector<string> tokens; // Create vector to hold our words

            while (ss >> buf) {
                tokens.push_back(buf);

                string nopunct = removePunct(buf);

                RedBlackTree<string, int>::iterator it = tree->find(nopunct);
                if (it == tree->end()) {
                    if (nopunct != "")
                        tree->insert(nopunct, 1);
                } else {
                    it->second++;
                }
            }

        }

        // Don't forget to close the file.
        input_file.close();

    } catch (const ifstream::failure &f) {
        cerr << "Error: An I/O error occurred reading '" << argv[1] << "'.";
    }

    vector<Node<string, int> > sorted;
    for (RedBlackTree<string, int>::iterator it = tree->begin();
            it != tree->end(); ++it) {
        Node<string, int> n(it->first, it->second);

        sorted.push_back(n);
    }

    sort(sorted.begin(), sorted.end(), lessthanfun); //loop through sorted from 0 to limit to determine the largest word size
    int wordnum = 1;
    for (vector<Node<string, int> >::iterator it = sorted.begin();
            it != sorted.end(); ++it) {

        if ((it->kv_pair_.first).size() > maxwordwidth) {
            maxwordwidth = (it->kv_pair_.first).size();
        }
        if (wordnum >= limit) {

            break;
        }
        wordnum++;
    }

    wordnum = 1;
    cout << "Total unique words: " << tree->size() << endl;
    int numwidth = numDigits(min((int) tree->size(), limit));
    for (vector<Node<string, int> >::iterator it = sorted.begin();
            it != sorted.end(); ++it) {

        string numstring = "";
        int thisnumwidth = numDigits(wordnum);
        for (int i = 0; i < numwidth - thisnumwidth; i++) {
            numstring += " ";
        }

        stringstream convert;
        convert << wordnum;
        numstring += convert.str();
        string wordoutput = it->kv_pair_.first;

        for (size_t i = 0; i < maxwordwidth - (it->kv_pair_.first).size() + 1;
                i++) {

            wordoutput += " ";
        }
        cout << numstring << ". " << wordoutput << it->kv_pair_.second << endl;
        if (wordnum >= limit) {
            break;

        }
        wordnum++;
    }
    return 0;
}