Пример #1
0
//need this to compare two BinaryTreePtr Objects
//bool BinaryTreePtr::operator<(const BinaryTreePtr& b) const
//{
//	return frequency < b.frequency;
//}
int main(int argc, char** argv)
{
	ifstream inf(argv[1]);
	char character;
	//BinaryTreePtr p;
	int ascii[256] = {};
	int temp[256];
	int counter = 0;
	BinaryHeap <BinaryTreePtr> heap; //not sure what size

	while (inf.get(character)) //reads each character as char
	{
		
		int num_char = (int)character; //casts char into int
		
		ascii[num_char]++; //increments array based on asci

	}

	for (int j = 0; j < 256; j++)
	{
		if (ascii[j] != 0)
		{
			
			int freq = ascii[j];
			heap.insert(BinaryTreePtr((char)j,ascii[j]));
		}
	}

	while(!heap.isEmpty())
	{
		BinaryTreePtr min_1;
		heap.deleteMin(min_1);
		//cout << (char)min_1.asci_value << min_1.frequency << endl;
		if (heap.isEmpty())
		{
			heap.insert(min_1);
			break;
		}
		else
		{
			
			BinaryTreePtr min_2;
			heap.deleteMin(min_2);
		//	cout << (char)min_2.asci_value << min_2.frequency << endl;
			BinaryTreePtr parent;
			int temp_freq = min_1.Node->getInfo() + min_2.Node->getInfo();
			char temp_char = 'Y';
			BinaryTreePtr Parent(temp_char, temp_freq, min_1.Node, min_2.Node);
			heap.insert(Parent);
		}
	}
	char* random = new char[500]();
	int i = 0;
	BinaryTreePtr last;
	heap.deleteMin(last);
	last.Node->print(random, i);
}
void Encoder::generateHuffmanTree(){
  BinaryHeap<node<int> > heap;
  node<int> nodes[256];
  int numNodes = 0;
  for(int i = 0; i < 256; i++)
   if(freq[i] > 0 && i!= 10)
    cout << i << " " << freq[i] <<  endl;
  
  for(int i = 0; i < 256; i++){
    if(freq[i]>0 && i!=10){
      nodes[numNodes].probability = freq[i];
      nodes[numNodes].internal = 0;
      nodes[numNodes].value = i;
      heap.insert(nodes[numNodes]);
      numNodes++;
    }
  }
  // nodes disappear after this...
  for(int i = 0; i < numNodes; i++){
    cout << nodes[i].probability << " " << (char)nodes[i].value << endl;
  }

  node<int> lnode, rnode;
  node<int> parentNodes[300];
  
  int treeNumber = 0;
  
  while(heap.currentSize > 1) //while 2 or more elements in heap
  {
      heap.deleteMin(lnode);
      heap.deleteMin(rnode);

      cout << "Lnode = " << lnode.probability << " " << lnode.value <<  endl;
      cout << "Rnode = " << rnode.probability << " " << rnode.value <<  endl;

      parentNodes[treeNumber].internal = 1;
      parentNodes[treeNumber].probability = lnode.probability + rnode.probability;
      parentNodes[treeNumber].left = &lnode;
      parentNodes[treeNumber].right = &rnode;
      parentNodes[treeNumber].value = treeNumber;
      cout << "Tree " << treeNumber+1 << " has weight: " << lnode.probability + rnode.probability << endl;
      cout << "Left child: " << parentNodes[treeNumber].left->probability << " " << parentNodes[treeNumber].left->value << " Right child: " << parentNodes[treeNumber].right->probability << " " << parentNodes[treeNumber].right->value << endl << endl;
      heap.insert(parentNodes[treeNumber]);
      parentNodes[treeNumber].value = treeNumber++;
      
  }
  treeNumber--; // to take away last unneeded ++
  //parentNodes[treeNumber--].returnCodes(parentNodes[treeNumber--]);
  //returnCodes(&parentNodes[treeNumber--]);

  returnCodes(&parentNodes[0]);
  returnCodes(&parentNodes[1]);
  returnCodes(&parentNodes[2]);
  returnCodes(&parentNodes[3]);

}
Пример #3
0
	void rest_order(MarketInstruction * mi) {
		if(mi->type == MarketInstruction::Order) {
			if(mi->typeOfOrder == MarketInstruction::Sell) {
				sellOrders->insert(mi, mi->id);
			}
			else if(mi->typeOfOrder == MarketInstruction::Buy) {
				buyOrders->insert(mi, mi->id);
			}
		}
	}
Пример #4
0
int main() {

	BinaryHeap<int> H;
 

	cout << endl;

	vector<int> list = {30,17,20,15,10,12,5,7,8,5,2,9};

	for (int i : list)
	{
		H.insert(i);

	}

	H.printHeap();

	cout << " .....Inserting 1,10,6,4...." << endl;

	vector<int> list2 = {1,10,6,4};
	
	for (int i : list2)
	{
		H.insert(i);

	}

	H.printHeap();

	cout << " ......Performing 3 DeleteMin() ......" << endl;



	for (int i = 0 ; i<3; i++ )
	{
	H.deleteMin();
	}

	H.printHeap(); 

	cout << endl << H.HeapHeight();







//{30,17,20,15,10,12,5,7,8,5,2,9};



return 0;
}
Пример #5
0
/**
 * Main function
 */
int main(int argc, char** argv){
	BinaryHeap <char> bheap;
	bheap.insert('X');
	bheap.insert('Y');
	bheap.insert('A');
	bheap.insert('R');
	bheap.insert('Z');

	bheap.delete_top();
	bheap.print_heap();
	
	return 0;
}
Пример #6
0
int main(int argc, char **argv) {

    BinaryHeap<int> testHeap;
    std::string input;
    std::string numbers = "0123456789";
    
    std::cout << "Input vals to add to BinaryHeap (val1 val2 val3 val4 ... end)\n";

    while (std::cin >> input)
    {
	// if 'std::String::find_first_not_of' doesnt find anything, then it outputs max_int (long int)
	// since any num higher than 1 will be set to true, add 1 to max int to start at 0(false)
	 if (input.find_first_not_of(numbers)+1 ) {
		if (input == "end")
		{
		    break;
		}
		else 
		{
		    std::cerr << input << " not recognized\n";
		    continue;
		}
	     
	} // end if 	
	int num = std::atoi(input.c_str()); // transform string into number, would have normally use boost::lexical_cast though
	testHeap.insert(num);
    }
 
    std::cout << "Input vals to remove from BinaryHeap (val1 val2 val3 val4 ... end)\n";

    while (std::cin >> input)
    {
	// if 'std::String::find_first_not_of' doesnt find anything, then it outputs max_int (long int)
	    // since any num higher than 1 will be set to true, add 1 to max int to start at 0(false)
	 if (input.find_first_not_of(numbers)+1 ) {
		if (input == "end")
		    break;
		else 
		{
		    std::cerr << input << " not recognized\n";
		    continue;
		}
	     
	} // end if 	
	int num = std::atoi(input.c_str());
	testHeap.removeKey(num);
    }
    
    std::cerr << "\n";
    
    
    while (!testHeap.isEmpty())
    {
	std::cerr << testHeap.findMin() << " ";
	testHeap.deleteMin();
	
    }
    std::cerr << "\n";
        return 0;
}
Пример #7
0
static void test_heap(const T* data, unsigned data_size, const T* sorted_data,
                      const T* to_remove, unsigned removed_size, const T* sorted_after_remove,
                      const T& not_in_heap) {
    BinaryHeap<T, Compare> heap;
    const size_t initial_capacity = data_size / 2, grow_capacity = (data_size * 3) / 2, alignment = 4;
    UAllocTraits_t traits = {0};
    TEST_ASSERT_TRUE(heap.init(initial_capacity, grow_capacity, traits, alignment));

    // Fill the heap with data
    for (unsigned i = 0; i < data_size; i++) {
        heap.insert(data[i]);
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_EQUAL(data_size, heap.get_num_elements());

    // Remove and check root at each step
    for (unsigned i = 0; i < data_size; i ++) {
        T root = heap.get_root();
        TEST_ASSERT_TRUE(root == sorted_data[i]);
        heap.remove_root();
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_TRUE(heap.is_empty());

    // Put everything back again
    for (unsigned i = 0; i < data_size; i++) {
        heap.insert(data[i]);
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_EQUAL(data_size, heap.get_num_elements());

    // And check removing
    for (unsigned i = 0; i < removed_size; i ++) {
        TEST_ASSERT_TRUE(heap.remove(to_remove[i]));
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_TRUE(!heap.remove(not_in_heap)); // this element is not in the heap
    TEST_ASSERT_EQUAL(data_size - removed_size, heap.get_num_elements());
    // Remove and check root at each step
    for (unsigned i = 0; i < data_size - removed_size; i ++) {
        T root = heap.pop_root();
        TEST_ASSERT_TRUE(root == sorted_after_remove[i]);
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_TRUE(heap.is_empty());
    TEST_ASSERT_EQUAL(0, heap.get_num_elements());
}
Пример #8
0
void generate_Soldiers(BinaryHeap<soldier>& heap, int number_of_Spartans, int number_of_Persians, vector<int>& spartans, vector<int>& persians)
{
	soldier newSoldier, minimum;
	int faction_Selection, current_Spartans, current_Persians;
	current_Spartans = 0, current_Persians = number_of_Spartans;
	int timeValue = 0;

	while((number_of_Spartans > 0 || number_of_Persians > 0) )
	{
		faction_Selection = rand() % 2;//Select from 1 to 0 for the faction

		if(faction_Selection == 1 && (number_of_Spartans > 0)){

 			newSoldier.set_Faction(true);//Set the faction of our new soldier.
			timeValue = rand() % 51 + 1;
			newSoldier.set_actionTime(timeValue);

			newSoldier.set_iD(current_Spartans);//Sets the iD to the current value of i. We will step through this i times, creating i soldiers.

			spartans.push_back(current_Spartans);//The ID is pushed into the vector of soldiers.
			current_Spartans++;
			number_of_Spartans--;

			heap.insert(newSoldier);//Insert our newly created soldier

		}
		else if(faction_Selection == 0 && (number_of_Persians > 0)){

			newSoldier.set_Faction(false);


			timeValue = rand() % 900 + 51;
			newSoldier.set_actionTime( timeValue );
			newSoldier.set_iD(current_Persians);//Sets the iD to the current value of i. We will step through this i times, creating i soldiers.
			persians.push_back(current_Persians);
			current_Persians++;
			number_of_Persians--;

			heap.insert(newSoldier);//Insert our newly created soldier

		}
	}
}
//getAlpha uses a binaryHeap to get the word I want alphabetized.
string getAlpha(string letters) {
  BinaryHeap<char,char> getInOrder;
  for (int i = 0; i < letters.length(); i++) {
    getInOrder.insert(letters[i], letters[i]);
  }
  string alphaWord = "";
  for (int j = 0; j < letters.length(); j++) {
    alphaWord += getInOrder.removeMin();
  }
  return alphaWord;
}
Пример #10
0
void insertFromFile (BinaryHeap<Comparable> & bh, string fileName = string("input.txt"))
{
	ifstream ifs(fileName.c_str());
	string temp, word;

	if (ifs)                        // make sure file is open
		while (getline(ifs, temp))
		{
			stringstream ss(temp);
			while (ss >> word)
				bh.insert(word);       // insert every word in file
		}
	else
bool SetCoveringSolution::greedyCover() {
	if(coveredRows == SetCoveringDecoder::nrows) { return false; }

	// Initialize heap with columnCount values:
	BinaryHeap< double >* heap = new BinaryHeap< double >(SetCoveringDecoder::ncolumns);
	for(unsigned j = 0; j < SetCoveringDecoder::ncolumns; ++j) {
		if(rowsCoveredByCol[j] > 0) {
			heap->insert(j, - double(rowsCoveredByCol[j] / SetCoveringDecoder::columnCosts[j]));
		}
	}

	while(coveredRows < SetCoveringDecoder::nrows) {
		const unsigned greedyCol = heap->extractMin();	// Get best column from heap

		openColumn(greedyCol, &heap);	// Open it
	}

	delete heap;
	return isFeasible();
}
Пример #12
0
void Encoder::getHeap(const unsigned char *message, const int size,
                      BinaryHeap<HuffmanNode *> &heap, int &elements) const
{
  unsigned int frequency[256] = {0};

  for (int i = 0; i < size; i++)
  {
    frequency[message[i]]++;
  }  // for each character

  for (int chars = 0; chars < 256; chars++)
  {
    if (frequency[chars] != 0)
    {
      elements++;		// to keep track of how large BHeap is
      HuffmanNode *ins = new HuffmanNode((unsigned char)chars, frequency[chars]);
      heap.insert(ins);
    }  // if character is in file, add to heap
  }  // for freqlist

  return;
}  // getHeap()
int main(int argc, char *argv[]) {
    
    std::vector<int> v { 10, 22, 32, 11, 23, 23, 100, 1, 0 };
    
    BinaryHeap<double> *binaryHeap = new BinaryHeap<double>(15);
    binaryHeap->insert(10);
    binaryHeap->insert(1);
    binaryHeap->insert(3);
    binaryHeap->insert(1);
    binaryHeap->insert(2);
    binaryHeap->insert(3);
    binaryHeap->insert(33);
    binaryHeap->insert(0);
    binaryHeap->display();

    return 0;
}
Пример #14
0
void repeatedBackwardAStar(bool** maze, int size, State* start, State* goal){
	int counter = 0;
	State** S = new State*[size];
	for (int i = 0; i < size; i++){
		S[i] = new State[size];
	}
	for (int r = 0; r < size; r++){
		for (int c = 0; c < size; c++){
			S[r][c].row = r;
			S[r][c].col = c;
			S[r][c].search = 0;
		}
	}

	while (!compareStatePos(start, goal)){
		counter = counter + 1;

		S[start->row][start->col].g = INF;
		S[start->row][start->col].search = counter;

	
		S[goal->row][goal->col].g = 0;
		S[goal->row][goal->col].h = manhattanDistance(start, goal);
		S[goal->row][goal->col].f = goal->g + goal->h;
		S[goal->row][goal->col].search = counter;

		BinaryHeap OPEN;
		list<State> CLOSED;

		// watch 4 states around the start state to update cost, if any 
		if (start->row > 0 && !maze[start->row - 1][start->col]){
			updateCostToInf(S, size, start->row - 1, start->col);
		}
		if (start->row< size - 1 && !maze[start->row + 1][start->col]){
			updateCostToInf(S, size, start->row + 1, start->col);
		}
		if (start->col > 0 && !maze[start->row][start->col - 1]){
			updateCostToInf(S, size, start->row, start->col - 1);
		}
		if (start->col < size - 1 && !maze[start->row][start->col + 1]){
			updateCostToInf(S, size, start->row, start->col + 1);
		}

		OPEN.insert(S[goal->row][goal->col]);
		computePath(S, maze, start, &OPEN, &CLOSED, counter, size, false);

		if (OPEN.size() == 0){
			cout << "I cannot reach the target\n";

			// clean up 
			for (int i = 0; i < size; i++){
				delete[] S[i];
			}
			delete[] S;

			return;
		}

		// follow the tree-pointers from sstart to sgoal 
		//stack<coord> path;
		coord current;
		current.row = start->row;
		current.col = start->col;
		//path.push(curCoord);

		while (current.row != goal->row || current.col != goal->col){
			int curRow = current.row;
			int curCol = current.col;
			
			// watch 4 states around this current state to update cost, if any 
			if (current.row > 0 && !maze[current.row - 1][current.col]){
				updateCostToInf(S, size, current.row - 1, current.col);
			}
			if (current.row < size - 1 && !maze[current.row + 1][current.col]){
				updateCostToInf(S, size, current.row + 1, current.col);
			}
			if (current.col > 0 && !maze[current.row][current.col - 1]){
				updateCostToInf(S, size, current.row, current.col - 1);
			}
			if (current.col < size - 1 && !maze[current.row][current.col + 1]){
				updateCostToInf(S, size, current.row, current.col + 1);
			}

			coord next; 

			next.row = S[curRow][curCol].treeRow;
			next.col = S[curRow][curCol].treeCol;
			int dir = direction(&current, &next);
			cout << "\tTried to move to: (" << next.row << ", " << next.col << ")... ";
			if (S[current.row][current.col].cost[dir] > 1){
				cout << "BLOCKED" << endl;
				start = &S[current.row][current.col];
				break;
			}
			cout << "OK! Moved start to: (" << next.row << ", " << next.col << ")" << endl;
			current = next;
		}
		start = &S[current.row][current.col];
	}

	cout << "I reached the target" << endl;


	// clean up 
	for (int i = 0; i < size; i++){
		delete[] S[i];
	}
	delete[] S;
}