示例#1
0
int Treap::find(string str)
{
    return findNode(str)->getValue();
}
示例#2
0
int Circuit::createSHIFTModule(const string &input, const string &output, unsigned int numBits, unsigned int numShift)
{
  Node* node;
  // create input nodes
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = input + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // create output nodes
  for (unsigned int i = 0; i < numBits+numShift; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // assign '0's to the least numShift bits
  Node* zeroNode = createNode("ZERO");
  createZERONode(zeroNode);
  
  for (unsigned int i = 0; i < numShift; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output + "[" + sstr.str() + "]";
    
    Node* outNode = findNode(name);
    assert(outNode != NULL);
    
    createBUF1Node(zeroNode, outNode);
  }
  
  // assign inputs to the remaining numBits bits
  for (unsigned int i = numShift; i < numBits+numShift; ++i)
  {
    string name;
    
    // find input node[i-numShift]
    stringstream inStr;
    inStr << i-numShift;
    name = input + "[" + inStr.str() + "]";
    Node* inNode = findNode(name);
    assert(inNode != NULL);
    
    // find output node[i]
    stringstream outStr;
    outStr << i;
    name = output + "[" + outStr.str() + "]";
    Node* outNode = findNode(name);
    assert(outNode != NULL);
    
    // assign
    createBUF1Node(inNode, outNode);
  }
  
  return 0;
}
bool TreeSetImpl::contains(const void *key) const {
  return findNode(key) != NULL;
}
示例#4
0
//procura código na árvore a partir da raíz (representado por String com 0s e 1s): procura código inteiro
int findNode(HuffmanTree *hft, char* s, short verbose)
{
	return findNode(hft, s, hft->root, verbose);
}
示例#5
0
int Circuit::createADDModule(const string &input1, const string &input2, const string &cin, const string &output, const string &cout, unsigned int numBits)
{
  Node* node;
  // create input1 and input2 nodes
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = input1 + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = input2 + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // create cin node
  node = createNode(cin);
  
  // create output nodes
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // create cout
  node = createNode(cout);
  
  // create internal nodes C
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output+"c" ;
    name = name + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // create other internal nodes d, f, g, c
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output+"d" ;
    name = name + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output+"e" ;
    name = name + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output+"f" ;
    name = name + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output+"g" ;
    name = name + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  for (unsigned int i = 0; i < numBits; ++i)
  {
  	Node* internal_c_previous;
    if(i!=0)
    {
    	stringstream sstr;
    	sstr << i-1;
    	string name = output+"c";
    	name = name + "[" + sstr.str() + "]";
    	internal_c_previous = findNode(name);
    	assert(internal_c_previous != NULL);
    }
  
    stringstream sstr;
    sstr << i;
    string name = output + "[" + sstr.str() + "]";
    Node* outNode = findNode(name);
    assert(outNode != NULL);
    
    name = input1 + "[" + sstr.str() + "]";
    Node* inNode1 = findNode(name);
    assert(inNode1 != NULL);
    
    name = input2 + "[" + sstr.str() + "]";
    Node* inNode2 = findNode(name);
    assert(inNode2 != NULL);
    
    //internal node for c(n-1) to c0
    name = output+"c";
    name = name + "[" + sstr.str() + "]";
    Node* internal_c = findNode(name);
    assert(internal_c != NULL);
    
    //internal node1
    name = output+"d";
    name = name + "[" + sstr.str() + "]";
    Node* dd = findNode(name);
    assert(dd != NULL);
    
    //internal node2
    name = output+"e";
    name = name + "[" + sstr.str() + "]";
    Node* ee = findNode(name);
    assert(ee != NULL);
    
    //internal node3
    name = output+"f";
    name = name + "[" + sstr.str() + "]";
    Node* ff = findNode(name);
    assert(ff != NULL);
    
    //internal node4
    name = output+"g";
    name = name + "[" + sstr.str() + "]";
    Node* gg = findNode(name);
    assert(gg != NULL);

    Node* c_in = findNode(cin);
    assert(c_in != NULL);
    Node* c_out = findNode(cout);
    assert(c_out != NULL);
    
    
    //To calculate each bit of the adder
    
    if (i==0)
    {
    		//s0=a0^b0^cin;
    		createXOR3Node(inNode1, inNode2, c_in, outNode);
    		
    		//c0=a0*b0+b0*cin+cin*a0;
    		createAND2Node(inNode1,inNode2,dd);
    		createAND2Node(inNode1,c_in,ee);
    		createAND2Node(inNode2,c_in,ff);
    		createOR2Node(dd,ee,gg);
    		createOR2Node(gg,ff,internal_c);
    }
    else if ( i==(numBits-1) )
    {
    		//sn=an^bn^c(n-1);
    		createXOR3Node(inNode1, inNode2, internal_c_previous, outNode);
    		
    		//cn=an*bn+bn*c(n-1)+c(n-1)*an;
    		createAND2Node(inNode1,inNode2,dd);
    		createAND2Node(inNode1,internal_c_previous,ee);
    		createAND2Node(inNode2,internal_c_previous,ff);
    		createOR2Node(dd,ee,gg);
    		createOR2Node(gg,ff,c_out);
    }
    else
    {
    		//sk=ak^bk^c(k-1);
    		createXOR3Node(inNode1, inNode2, internal_c_previous, outNode);
    		
    		//ck=ak*bk+bk*c(k-1)+c(k-1)*ak;
    		createAND2Node(inNode1,inNode2,dd);
    		createAND2Node(inNode1,internal_c_previous,ee);
    		createAND2Node(inNode2,internal_c_previous,ff);
    		createOR2Node(dd,ee,gg);
    		createOR2Node(gg,ff,internal_c);
    }
  }
  
  // when you have implemented this function,
  // change 'return -1' to 'return 0'
  return 0;
}
示例#6
0
/**
 * Wrapper to findNode()
 *
 * @param graph   Input graph
 * @param node    Node id to find
 * @return  A pointer to the node or NULL if node does not exist
 */
node_t* find_node(graph_t* graph, int node)
{
  return findNode(graph, node);
}
示例#7
0
      void getLocalToGlobalMap(int (*local2global)[2],
                               int &off_global,
                               const Basis<Scalar,ArrayType> &basis,
                               const int *element) {
        const int local = 0, global = 1;
        const int nbf = basis.getCardinality();
        const shards::CellTopology cell = basis.getBaseCellTopology();
        const int dim = cell.getDimension();

        int cnt = 0, off_element = 0;
        int subcell_verts[4], nids;

        const int nvert = cell.getVertexCount();
        for (int i=0;i<nvert;++i) {
          const int ord_vert = (off_element < nbf ? basis.getDofOrdinal(0, i, 0) : 0);
          const int dof_vert = (off_element < nbf ? basis.getDofTag(ord_vert)[3] : 0);
      
          local2global[cnt][local] = off_element;
          off_element += dof_vert;
          Orientation::getElementNodeMap(subcell_verts, nids,
                                         cell, element,
                                         0, i);
      
          if (!findNode(local2global[cnt][global], subcell_verts, nids, true)) {
            addNode(subcell_verts, nids, off_global);
            local2global[cnt][global] = off_global;
            off_global += dof_vert;
          }
          ++cnt;
        }
        const int nedge = cell.getEdgeCount();
        for (int i=0;i<nedge;++i) {
          const int ord_edge = (off_element < nbf ? basis.getDofOrdinal(1, i, 0) : 0);
          const int dof_edge = (off_element < nbf ? basis.getDofTag(ord_edge)[3] : 0);
      
          local2global[cnt][local] = off_element;
          off_element += dof_edge;
          Orientation::getElementNodeMap(subcell_verts, nids,
                                         cell, element,
                                         1, i);
      
          if (!findNode(local2global[cnt][global], subcell_verts, nids, true)) {
            addNode(subcell_verts, nids, off_global);
            local2global[cnt][global] = off_global;
            off_global += dof_edge;
          }
          ++cnt;
        }
        const int nface = cell.getFaceCount();
        for (int i=0;i<nface;++i) {
          const int ord_face = (off_element < nbf ? basis.getDofOrdinal(2, i, 0) : 0);
          const int dof_face = (off_element < nbf ? basis.getDofTag(ord_face)[3] : 0);
      
          local2global[cnt][local] = off_element;
          off_element += dof_face;
          Orientation::getElementNodeMap(subcell_verts, nids,
                                         cell, element,
                                         2, i);
      
          if (!findNode(local2global[cnt][global], subcell_verts, nids, true)) {
            addNode(subcell_verts, nids, off_global);
            local2global[cnt][global] = off_global;
            off_global += dof_face;
          }
          ++cnt;
        }
        {
          const int i = 0;
          const int ord_intr = (off_element < nbf ? basis.getDofOrdinal(dim, i, 0) : 0);
          const int dof_intr = (off_element < nbf ? basis.getDofTag(ord_intr)[3]   : 0);
      
          local2global[cnt][local] = off_element;
          off_element += dof_intr;
          Orientation::getElementNodeMap(subcell_verts, nids,
                                         cell, element,
                                         dim, i);
      
          if (!findNode(local2global[cnt][global], subcell_verts, nids, true)) {
            addNode(subcell_verts, nids, off_global);
            local2global[cnt][global] = off_global;
            off_global += dof_intr;
          }
          ++cnt;
        }
    
        // add the last offset
        local2global[cnt][local] = off_element;
        local2global[cnt][global] = -1; // invalid values
      }
示例#8
0
void probabilitat_Segons_Fitxer(RBTree * tree){

	int i;
	Node *node;
	RBdata *data;

	char * paraula = malloc(sizeof(char) * MAXLINEA);
	
	printf("Paraula a buscar a l'arbre?\n");
	printf(">>> ");
	scanf("%s", paraula);

	/* Search if the word is in the tree */
	node = findNode(tree, paraula);

	if (node != NULL){

		float * prob = malloc(sizeof(float) * n_files);

		data = node->data;

		printf("La paraula %s surt un total de %d vegades.\n", data->key, data->num);

		/* Calculate and print the probability in each file with a bucle */
		for (i = 0; i < n_files; i++){
			printf("Al fitxer %d surt %d vegades,", i, data->vector[i]);
			prob[i] = (float) data->vector[i] / (float) data->num;
			printf(" prob: %f \n", prob[i]);
		}

		/* Sort the probabilities */
		qsort(prob, n_files, sizeof(float), compare_floats);

		FILE *fp_data, *fp_gnuplot;

		fp_data = fopen("vector.data","w");

		if (!fp_data){
			printf("ERROR: no he pogut obrir el fitxer.\n");
			exit(EXIT_FAILURE);
		}

		printf("The ordered vector is: ");

		/* Store probabilities in a file */
		
		fprintf(fp_data, "%s\n", "#Funcio prob(paraula)" );
		fprintf(fp_data, "%s\n", "#x   prob(x)" );

		for(i = 0; i < n_files; i++){
			fprintf(fp_data, "%d %f\n", i, prob[i]);
			printf("%f ", prob[i]);
		}

		printf("\n");
		
		/* Close file and release memory */
		fclose(fp_data);
		free(prob);

		/* Print a graphic of probs using gnuplot with a pipe */
		
		fp_gnuplot = popen("gnuplot", "w");
		if (!fp_gnuplot){
			printf("ERROR: no he pogut obrir el fitxer.\n");
			exit(EXIT_FAILURE);
		}

		fprintf(fp_gnuplot, "set xlabel \"apareix en el fitxer x\"\n");
		fprintf(fp_gnuplot, "set ylabel \"amb probabilitat y\"\n");

		fprintf(fp_gnuplot, "plot \"vector.data\" with lines title \"la paraula %s\"\n", data->key);
		fflush(fp_gnuplot);

		printf("\nEnviat....\n");

		sleep(10);

		pclose(fp_gnuplot);	

	}else{

		printf("No s'ha trobat la paraula a l'arbre!");

	}

	/* Release memory */
	free(paraula);
}
示例#9
0
void Domain::writeClickFiles() {
    ofstream click_conf;

    for (int i = 0; i < network_nodes.size(); i++) {
        vector<string> unique_ifaces;
        vector<string> unique_srcips;
        NetworkNode *nn = network_nodes[i];
        click_conf.open((write_conf + nn->label + ".conf").c_str());
        click_conf << "require(blackadder);" << endl << endl;
        /*Blackadder Elements First*/
        click_conf << "globalconf::GlobalConf(MODE " << overlay_mode << ", NODEID " << nn->label << "," << endl;
        click_conf << "DEFAULTRV " << nn->FID_to_RV.to_string() << "," << endl;
        click_conf << "TMFID     " << nn->FID_to_TM.to_string() << "," << endl;
        click_conf << "iLID      " << nn->iLid.to_string() << ");" << endl << endl;

        click_conf << "localRV::LocalRV(globalconf," << nn->connections.size() /*number of neighbours*/ << "," << endl;
        for (int j = 0; j < nn->connections.size(); j++) {
            NetworkConnection *nc = nn->connections[j];
            NetworkNode *dest_nn = findNode(nc->dst_label);
            if (j == nn->connections.size() - 1) {
                click_conf << /*a neighbour*/dest_nn->label << "," << /*LID to it*/dest_nn->iLid.to_string() << "," << /*iLID of it*/ nc->LID.to_string() << ");" << endl << endl;
            } else {
                click_conf << /*a neighbour*/dest_nn->label << "," << /*LID to it*/dest_nn->iLid.to_string() << "," << /*iLID of it*/ nc->LID.to_string() << "," << endl;
            }
        }
        click_conf << "netlink::Netlink();" << endl << "tonetlink::ToNetlink(netlink);" << endl << "fromnetlink::FromNetlink(netlink);" << endl << endl;
        click_conf << "proxy::LocalProxy(globalconf);" << endl << endl;

        click_conf << "fw::Forwarder(globalconf," << nn->connections.size() << "," << endl;
        for (int j = 0; j < nn->connections.size(); j++) {
            NetworkConnection *nc = nn->connections[j];
            int offset;
            if (overlay_mode.compare("mac") == 0) {
                if ((offset = findOffset(unique_ifaces, nc->src_if)) == -1) {
                    unique_ifaces.push_back(nc->src_if);
                    if (j == nn->connections.size() - 1) {
                        click_conf << unique_ifaces.size() << "," << nc->src_mac << "," << nc->dst_mac << "," << nc->LID.to_string() << ");" << endl << endl;
                    } else {
                        click_conf << unique_ifaces.size() << "," << nc->src_mac << "," << nc->dst_mac << "," << nc->LID.to_string() << "," << endl;
                    }
                } else {
                    if (j == nn->connections.size() - 1) {
                        click_conf << offset + 1 << "," << nc->src_mac << "," << nc->dst_mac << "," << nc->LID.to_string() << ");" << endl << endl;
                    } else {
                        click_conf << offset + 1 << "," << nc->src_mac << "," << nc->dst_mac << "," << nc->LID.to_string() << "," << endl;
                    }
                }
            } else {
                if ((offset = findOffset(unique_srcips, nc->src_ip)) == -1) {
                    unique_srcips.push_back(nc->src_ip);
                    //cout << "PUSHING BACK " << nc->src_ip << endl;
                    //cout << unique_srcips.size() << endl;
                    if (j == nn->connections.size() - 1) {
                        click_conf << unique_srcips.size() << "," << nc->src_ip << "," << nc->dst_ip << "," << nc->LID.to_string() << ");" << endl << endl;
                    } else {
                        click_conf << unique_srcips.size() << "," << nc->src_ip << "," << nc->dst_ip << "," << nc->LID.to_string() << "," << endl;
                    }
                } else {
                    if (j == nn->connections.size() - 1) {
                        click_conf << offset + 1 << "," << nc->src_ip << "," << nc->dst_ip << "," << nc->LID.to_string() << ");" << endl << endl;
                    } else {
                        click_conf << offset + 1 << "," << nc->src_ip << "," << nc->dst_ip << "," << nc->LID.to_string() << "," << endl;
                    }
                }
            }
        }
        if (overlay_mode.compare("mac") == 0) {
            for (int j = 0; j < unique_ifaces.size(); j++) {
                click_conf << "tsf" << j << "::ThreadSafeQueue(1000);" << endl;
                if (nn->running_mode.compare("user") == 0) {
                    click_conf << "fromdev" << j << "::FromDevice(" << unique_ifaces[j] << ");" << endl << "todev" << j << "::ToDevice(" << unique_ifaces[j] << ");" << endl;
                } else {
                    click_conf << "fromdev" << j << "::FromDevice(" << unique_ifaces[j] << ", BURST 8);" << endl << "todev" << j << "::ToDevice(" << unique_ifaces[j] << ", BURST 8);" << endl;
                }
            }
            /*Necessary Click Elements*/
            if (nn->running_mode.compare("user") == 0) {
                click_conf << "classifier::Classifier(12/080a);" << endl;
            } else {
                click_conf << "classifier::Classifier(12/080a, -);" << endl;
                click_conf << "tohost::ToHost();" << endl;
            }
        } else {
            /*raw sockets here*/
            click_conf << "tsf" << "::ThreadSafeQueue(1000);" << endl;
            if (nn->running_mode.compare("user") == 0) {
                click_conf << "rawsocket" << "::RawSocket(UDP, 7777)" << endl;
                click_conf << "classifier::IPClassifier(dst udp port 8888 and src udp port 7777)" << endl;
            } else {
                cerr << "Something is wrong...I should not build click config using raw sockets for node " << nn->label << "that will run in kernel space" << endl;
            }
        }

        /*Now link all the elements appropriately*/
        click_conf << endl << endl << "proxy[0]->tonetlink;" << endl << "fromnetlink->[0]proxy;" << endl << "localRV[0]->[1]proxy[1]->[0]localRV;" << endl << "proxy[2]-> [0]fw[0] -> [2]proxy;" << endl;
        if (overlay_mode.compare("mac") == 0) {
            for (int j = 0; j < unique_ifaces.size(); j++) {
                click_conf << "fw[" << (j + 1) << "]->tsf" << j << "->todev" << j << ";" << endl;
                click_conf << "fromdev" << j << "->classifier[0]->[" << (j + 1) << "]fw;" << endl;
            }
            if (nn->running_mode.compare("kernel") == 0) {
                click_conf << "classifier[1]->tohost;" << endl;
            }
        } else {
            /*raw sockets here*/
            click_conf << "fw[1] ->  tsf -> rawsocket -> classifier -> [1]fw" << endl;
        }
        click_conf.close();
    }
}
示例#10
0
int findBST(BST bt, book b){
	return findNode(bt->root, b);
}
示例#11
0
int MtpStorage::getObjectPropertyList(MtpObjectHandle handle, uint32_t format, uint32_t property, int groupCode, int depth, MtpDataPacket& packet) {
	MTPD("MtpStorage::getObjectPropertyList handle: %u, format: %x, property: %x\n", handle, format, property);
	if (groupCode != 0)
	{
		MTPE("getObjectPropertyList: groupCode unsupported\n");
		return -1; // TODO: RESPONSE_SPECIFICATION_BY_GROUP_UNSUPPORTED
	}
	// TODO: support all the special stuff, like:
	// handle == 0 -> all objects at the root level
	// handle == 0xffffffff -> all objects (on all storages? how could we support that?)
	// format == 0 -> all formats, otherwise filter by ObjectFormatCode
	// property == 0xffffffff -> all properties except those with group code 0xffffffff
	// if property == 0 then use groupCode
	//   groupCode == 0 -> return Specification_By_Group_Unsupported
	// depth == 0xffffffff -> all objects incl. and below handle

	std::vector<PropEntry> results;

	if (handle == 0xffffffff) {
		// TODO: all object on all storages (needs a different design, result packet needs to be built by server instead of storage)
	} else if (handle == 0)	{
		// all objects at the root level
		Tree* root = mtpmap[0];
		MtpObjectHandleList list;
		root->getmtpids(&list);
		for (MtpObjectHandleList::iterator it = list.begin(); it != list.end(); ++it) {
			Node* node = root->findNode(*it);
			if (!node) {
				MTPE("BUG: node not found for root entry with handle %u\n", *it);
				break;
			}
			queryNodeProperties(results, node, property, groupCode, mStorageID);
		}
	} else {
		// single object
		Node* node = findNode(handle);
		if (!node) {
			// Item is not on this storage device
			return -1;
		}
		queryNodeProperties(results, node, property, groupCode, mStorageID);
	}

	MTPD("count: %u\n", results.size());
	packet.putUInt32(results.size());

	for (size_t i = 0; i < results.size(); ++i) {
		PropEntry& p = results[i];
		MTPD("handle: %u, propertyCode: %x = %s, datatype: %x, value: %llu\n",
				p.handle, p.property, MtpDebug::getObjectPropCodeName(p.property),
				p.datatype, p.intvalue);
		packet.putUInt32(p.handle);
		packet.putUInt16(p.property);
		packet.putUInt16(p.datatype);
		switch (p.datatype) {
			case MTP_TYPE_INT8:
				MTPD("MTP_TYPE_INT8\n");
				packet.putInt8(p.intvalue);
				break;
			case MTP_TYPE_UINT8:
				MTPD("MTP_TYPE_UINT8\n");
				packet.putUInt8(p.intvalue);
				break;
			case MTP_TYPE_INT16:
				MTPD("MTP_TYPE_INT16\n");
				packet.putInt16(p.intvalue);
				break;
			case MTP_TYPE_UINT16:
				MTPD("MTP_TYPE_UINT16\n");
				packet.putUInt16(p.intvalue);
				break;
			case MTP_TYPE_INT32:
				MTPD("MTP_TYPE_INT32\n");
				packet.putInt32(p.intvalue);
				break;
			case MTP_TYPE_UINT32:
				MTPD("MTP_TYPE_UINT32\n");
				packet.putUInt32(p.intvalue);
				break;
			case MTP_TYPE_INT64:
				MTPD("MTP_TYPE_INT64\n");
				packet.putInt64(p.intvalue);
				break;
			case MTP_TYPE_UINT64:
				MTPD("MTP_TYPE_UINT64\n");
				packet.putUInt64(p.intvalue);
				break;
			case MTP_TYPE_INT128:
				MTPD("MTP_TYPE_INT128\n");
				packet.putInt128(p.intvalue);
				break;
			case MTP_TYPE_UINT128:
				MTPD("MTP_TYPE_UINT128\n");
				packet.putUInt128(p.intvalue);
				break;
			case MTP_TYPE_STR:
				MTPD("MTP_TYPE_STR: %s\n", p.strvalue.c_str());
				packet.putString(p.strvalue.c_str());
				break;
			default:
				MTPE("bad or unsupported data type: %x in MyMtpDatabase::getObjectPropertyList", p.datatype);
				break;
		}
	}
	return 0;
}
示例#12
0
	//findNode- finds the node at the passed in position
	//node- the node 
	//x- the x coord of the position
	//y- the y coord of the position
	//outputHeight- the output to assign the height to
	void TerrainQuadTree::findNode(Node* node, float x, float z, float& outputHeight)
	{
		float xMin, xMax, zMin, zMax;
		int count, i, index;
		float vertex1[3], vertex2[3], vertex3[3];
		bool foundHeight;


		// Calculate the dimensions of this node.
		xMin = node->positionX - (node->width / 2.0f);
		xMax = node->positionX + (node->width / 2.0f);

		zMin = node->positionZ - (node->width / 2.0f);
		zMax = node->positionZ + (node->width / 2.0f);

		// See if the x and z coordinate are in this node, if not then stop traversing this part of the tree.
		if ((x < xMin) || (x > xMax) || (z < zMin) || (z > zMax))
		{
			return;
		}

		// If the coordinates are in this node then check first to see if children nodes exist.
		count = 0;

		for (i = 0; i<4; i++)
		{
			if (node->nodes[i] != 0)
			{
				count++;
				findNode(node->nodes[i], x, z, outputHeight);
			}
		}

		// If there were children nodes then return since the polygon will be in one of the children.
		if (count > 0)
		{
			return;
		}

		// If there were no children then the polygon must be in this node.  Check all the polygons in this node to find 
		// the height of which one the polygon we are looking for.
		for (i = 0; i<node->triangleCount; i++)
		{
			index = i * 3;
			vertex1[0] = node->vertexArray[index].x;
			vertex1[1] = node->vertexArray[index].y;
			vertex1[2] = node->vertexArray[index].z;

			index++;
			vertex2[0] = node->vertexArray[index].x;
			vertex2[1] = node->vertexArray[index].y;
			vertex2[2] = node->vertexArray[index].z;

			index++;
			vertex3[0] = node->vertexArray[index].x;
			vertex3[1] = node->vertexArray[index].y;
			vertex3[2] = node->vertexArray[index].z;

			// Check to see if this is the polygon we are looking for.
			foundHeight = checkHeightOfTriangle(x, z, outputHeight, vertex1, vertex2, vertex3);

			// If this was the triangle then quit the function and the height will be returned to the calling function.
			if (foundHeight)
			{
				return;
			}
		}

	}
示例#13
0
 _redblacktree::tree* _redblacktree::nodeWithSizeNotLessThen( size_t size ) {
     return findNode( root, size );
 }
示例#14
0
const char *xml_get_string_attribute(xmlDoc *doc, char *format, ...)
{
  va_list ap;
  char str[4096];

  va_start(ap, format);
  vsnprintf(str, 4095, format, ap);
  va_end(ap);

  int i,n;
  char **arr;
  int found = TRUE;

  split_into_array(str, '.', &n, &arr);

  xmlNode *cur = xmlDocGetRootElement(doc);

  // first item much match the name of the root
  if (strcmp(arr[0], (char*)cur->name)!=0) {
    // root node doesn't match -- return empty string
    strcpy(buf, "");
  }
  else {
    // subsequent items specify the search path through the xml tree
    // all except the last one -- that is the attribute name
    for (i=1; i<n-1; ++i) {
      char *elem;
      int k;
      extract_array_specifier(arr[i], &elem, &k);

      xmlNode *next = findNode(doc, cur, elem, k);
      if (!next) {
        // not found -- return NULL
        found = FALSE;
        strcpy(buf, "");
        FREE(elem);
        break;
      }
      
      FREE(elem);
      cur = next;
    }
  }

  if (found) {
    assert(cur != NULL);
    xmlChar *val = xmlGetProp(cur, (xmlChar*)(arr[n-1]));
    if (val) {
      strncpy_safe(buf, (char*)val, MAX_LEN-1);
      xmlFree(val);
    }
    else {
      // found the node, but it did not have the requested attribute
      found = FALSE;
    }
  }

  if (!found) {
    strcpy(buf, MAGIC_UNSET_STRING);
  }

  free_char_array(&arr, n);
  return buf;
}
示例#15
0
void findNode( Node* node, Bolt bolt, std::vector<Pair>& result, unsigned int& cmp )
{
	// Если болт меньше гайки в текущем узле, то нужно посмотреть есть ли слева
	// пара.
	if (bolt.size < node->pair.nut.size)
	{
		++cmp;
		// Если пара есть, то вызываем findNode для нее.
		if (node->left)
		{
			findNode(node->left, bolt, result, cmp);
		}
		// Если же пары нет, то это значит, что мы достигли листа дерева. Значит
		// нужно разделить находящуюся здесь кучку гаек на две.
		else
		{
			Node* newNode = new Node();
			
			// Между прочим, для уменьшения количества сравнений можно сделать
			// дополнительный цикл, который будет запускаться после того, как
			// соответствующая гайка будет найдена. Тогда нам не придется проверять
			// два условия (> и <), а можно будет проверять только одно (например, >),
			// ибо среди оставшихся гаек не найдется еще одной равной текущему болту.
			std::vector<Nut>::iterator beginFrom;
			
			// Начинаем разбирать кучку гаек.
			for (std::vector<Nut>::iterator nut = node->lower.begin(); nut != node->lower.end(); ++nut)
			{
				// Если текущий болт больше гайки, то отправляем эту гайку в левую кучку.
				if (bolt.size > (*nut).size)
				{
					cmp += 1;
					newNode->lower.push_back(*nut);
					continue;
				}
				// Иначе, если болт меньше гайки, отправляем ее в правую кучку.
				else if (bolt.size < (*nut).size)
				{
					cmp += 2;
					newNode->upper.push_back(*nut);
					continue;
				}
				// Иначе мы нашли соответствующую гайку. Сохраним пару и прервем
				// цикл, чтобы оставшиеся гайки перебирать уже в другом цикле,
				// с меньшим количеством сравнений.
				else
				{
					newNode->pair.bolt = bolt;
					newNode->pair.nut = *nut;
					result.push_back(newNode->pair);
					beginFrom = ++nut;
					break;
				}
			}
			for (std::vector<Nut>::iterator nut = beginFrom; nut != node->lower.end(); ++nut)
			{
				++cmp;
				if (bolt.size > (*nut).size)
				{
					newNode->lower.push_back(*nut);
					continue;
				}
				else
				{
					newNode->upper.push_back(*nut);
					continue;
				}
			}
			
			// Удаляем гайки из левой кучки текущего узла, чтобы не держать их
			// в памяти за зря.
			node->lower.clear();
			
			// Сохраняем новый узел в дереве
			node->left = newNode;
		}
	}
	
	// Иначе болт больше гайки в текущем узле. То есть смотрим есть ли пара справа.
	else
	{
		++cmp;
		// Если пара есть, то вызываем findNode для нее.
		if (node->right)
		{
			findNode(node->right, bolt, result, cmp);
		}
		// Если же пары нет, то это значит, что мы достигли листа дерева. Значит
		// нужно разделить находящуюся здесь кучку гаек на две.
		else
		{
			Node* newNode = new Node();
			std::vector<Nut>::iterator beginFrom;
			
			for (std::vector<Nut>::iterator nut = node->upper.begin(); nut != node->upper.end(); ++nut)
			{
				if (bolt.size > (*nut).size)
				{
					cmp += 1;
					newNode->lower.push_back(*nut);
					continue;
				}
				else if (bolt.size < (*nut).size)
				{
					cmp += 2;
					newNode->upper.push_back(*nut);
					continue;
				}
				else
				{
					newNode->pair.bolt = bolt;
					newNode->pair.nut = *nut;
					result.push_back(newNode->pair);
					beginFrom = ++nut;
					break;
				}
			}
			for (std::vector<Nut>::iterator nut = beginFrom; nut != node->upper.end(); ++nut)
			{
				++cmp;
				if (bolt.size > (*nut).size)
				{
					newNode->lower.push_back(*nut);
					continue;
				}
				else
				{
					newNode->upper.push_back(*nut);
					continue;
				}
			}
			
			node->upper.clear();
			
			// Сохраняем новый узел в дереве
			node->right = newNode;
		}
	}
}
示例#16
0
Node *findKey(HashTable *table,char *key){
	uint32_t k = prehash(key);
	//printf("The key is : %s %08x\n",key,k);
	//printf("Looking at address : %08x\n",k % table->maxSize);
	return findNode(table->values[k % table->maxSize],key);
}
示例#17
0
void CNetwork::getLinks(FILE *file)
{
    // get the information about the links in the TRAF file and create the link list
    char line[81] = { '\0' };
    int card_type = 0;
    int index = 0;
    CLink *link = NULL;
    // link data
    char up[5] = { '\0' };
    char dn[5] = { '\0' };
    char th[5] = { '\0' };
    char le[5] = { '\0' };
    char ri[5] = { '\0' };
    char op[5] = { '\0' };
    char length[5] = { '\0' };
    char speed[5] = { '\0' };
    char left_bays_len[5] = { '\0' };
    char right_bays_len[5] = { '\0' };
    char full_lanes_num[5] = { '\0' };
    char left_bays_num[5] = { '\0' };
    char right_bays_num[5] = { '\0' };
    char ch[net_max_lanes][5] = { '\0' };
    // search the TRAF file for link data records
    while (!feof(file))
    {
        // read a line of the file
        card_type = readTRFLine(file, line);
        // parse the type 11 (link data) cards
        if (card_type == 11)
        {
            // initialize all the character data strings
            for (index = 0; index < 5; index++)
            {
                up[index] = '\0';
                dn[index] = '\0';
                th[index] = '\0';
                le[index] = '\0';
                ri[index] = '\0';
                op[index] = '\0';
                length[index] = '\0';
                speed[index] = '\0';
                left_bays_len[index] = '\0';
                right_bays_len[index] = '\0';
                full_lanes_num[index] = '\0';
                left_bays_num[index] = '\0';
                right_bays_num[index] = '\0';
                // iterate ch with net_max_lanes
                for (int li = 0; li < net_max_lanes; li++)
                {
                    ch[li][index] = '\0';
                }
            }
            // parse the line, which contains: the upstream node number, the downstream node number, the link length, etc. - see card 11
            for (index = 0; index < 4; index++)
            {
                up[index] = line[index];
                dn[index] = line[index + 4];
                length[index] = line[index + 8];
                left_bays_len[index] = line[index + 12];
                right_bays_len[index] = line[index + 16];
                th[index] = line[index + 40];
                le[index] = line[index + 36];
                ri[index] = line[index + 44];
                op[index] = line[index + 52];
                speed[index] = line[index + 64];
            }
            // read the channelization codes for each lane
            for (index = 0; index < net_max_lanes; index++)
            {
                ch[index][1] = line[index + 29];
            }
            full_lanes_num[0] = line[21];
            left_bays_num[0] = line[23];
            right_bays_num[0] = line[25];
            if ((atoi(dn) < 8000) && (atoi(up) < 8000))
            {
                // link is not a source link so create it
                link = new CLink();
                link->m_full_lanes_num = atoi(full_lanes_num);
                link->m_left_turn_bays_num = atoi(left_bays_num);
                link->m_left_bays_len = atoi(left_bays_len);
                link->m_right_turn_bays_num = atoi(right_bays_num);
                link->m_right_bays_len = atoi(right_bays_len);
                link->m_length = atoi(length);
                link->m_free_flow_speed = atoi(speed);
                if (link->m_free_flow_speed == 0)
                    link->m_free_flow_speed = 44;
                link->m_up_node = findNode(atoi(up));
                link->m_dn_node = findNode(atoi(dn));
                link->m_thru_node = findNode(atoi(th));
                link->m_left_node = findNode(atoi(le));
                link->m_right_node = findNode(atoi(ri));
                link->m_corsim_id = getLinkCorsimId(link->m_up_node->getId(), link->m_dn_node->getId());
                link->setOpposingNodeId(atoi(op));
                if ((atoi(up) < 8000) && (atoi(dn) < 8000))
                    link->m_travel_time = link->computeTravelTime();
                for (index = 0; index < net_max_lanes; index++)
                {
                    link->m_str_channel_code[index] = _T(ch[index][1]);
                }
                m_link_list.AddTail(link);
            }
        }
        else if (card_type > 11)
        {
            // because corsim expects the cards to be in ascending order by card type, we can jump out of the loop as soon as we encounter a card type greater than 11
            break;
        }
    }
}
示例#18
0
文件: hashmap.cpp 项目: kayw/mnb
const_iterator HashMap<Key, T, Hasher, EqualKey, Alloc>::
  find(const Key& key) const {
    return const_iterator(findNode(key) );
  }
示例#19
0
/**
 * Find the shortest path between two nodes
 * using a simple implementation of dijkstra's algorithm:
 * http://en.wikipedia.org/wiki/Dijkstra's_algorithm
 *
 * @param graph   Graph to traverse
 * @param node1   Starting node
 * @param node2   Destination node
 * @return  The id which is the nexthop otherwise NULL if no path exists
 */
int shortest_path(graph_t* graph, int node1, int node2)
{
  node_t* u = NULL;
  node_t* v = NULL;
  node_t* target = NULL;
  edge_t* e = NULL;
  int* lut = NULL;
  int* d = NULL;
  int numnodes = 0;
  int i = 0;
  int j = 0;
  int idx = 0;
  int mindist = INFINITY;
  int minidx = -1;
  int ret = 0;

  if(graph == NULL)
    return -1;

  u = findNode(graph, node1);
  v = target = findNode(graph, node2);

  if(u == NULL || v == NULL)
    return -1;


  numnodes = u->edgecount;

  lut = malloc(numnodes * sizeof(int));
  d = malloc(numnodes * sizeof(int));
  memset(d, INFINITY, numnodes * sizeof(int));

  // lut simply maps our node id's into a range from [0, nodecount)
  for(i = 0 ; i < numnodes ; ++i) {
    e = u->edges[i];
    lut[i] = (e->p1 == u) ? ((node_t*)e->p2)->id : ((node_t*)e->p1)->id;
    d[i] = INFINITY;
  }

  u->marked = 1;

  // Now, for each neighbor, find the distance to
  // the target node
  for(i = 0 ; i < numnodes ; ++i) {
    // Unmark all nodes
    for(j = 0 ; j < graph->nodecount ; ++j) {
      if(graph->nodes[j] != u)
        graph->nodes[j]->marked = 0;
    }
    e = u->edges[i];
    if(e->weight == INFINITY) // No longer exists
      continue;
    v = (node_t*)((e->p1 == u) ? e->p2 : e->p1);
    idx = findIdx(lut, v->id, numnodes);
    d[idx] = shortest_path_helper(graph, v, target);
    d[idx] += (d[idx] != INFINITY) ? e->weight : 0;
    if((d[idx] < mindist || mindist == INFINITY) && d[idx] != INFINITY) {
      mindist = d[idx];
      minidx  = idx;
    }
  }

  ret = (minidx >= 0 && minidx < numnodes) ? lut[minidx] : -1;

  free(d);
  free(lut);

  return ret;
}
示例#20
0
bool BinaryNodeTree<ItemType>:: contains(const ItemType& anEntry) const
{
   bool isSuccessful = false;
   findNode(rootPtr, anEntry, isSuccessful);
   return isSuccessful;   
}  // end contains
示例#21
0
    void test(bool mirrorX, bool mirrorY, qreal rotation, bool mirrorDabX, bool mirrorDabY, qreal dabRotation) {

        KisSurrogateUndoStore *undoStore = new KisSurrogateUndoStore();
        KisImageSP image = createTrivialImage(undoStore);
        image->initialRefreshGraph();

        KisNodeSP paint1 = findNode(image->root(), "paint1");

        QVERIFY(paint1->extent().isEmpty());

        KisPainter gc(paint1->paintDevice());

        QScopedPointer<KoCanvasResourceManager> manager(
            utils::createResourceManager(image, 0, m_presetFileName));

        KisPaintOpPresetSP preset =
            manager->resource(KisCanvasResourceProvider::CurrentPaintOpPreset).value<KisPaintOpPresetSP>();

        preset->settings()->setCanvasRotation(rotation);
        preset->settings()->setCanvasMirroring(mirrorY, mirrorX);


        if (mirrorDabX || mirrorDabY) {
            KisPaintOpSettingsSP settings = preset->settings()->clone();

            KisPressureMirrorOption mirrorOption;
            mirrorOption.readOptionSetting(settings);

            mirrorOption.setChecked(true);
            mirrorOption.setCurveUsed(false);

            mirrorOption.enableHorizontalMirror(mirrorDabX);
            mirrorOption.enableVerticalMirror(mirrorDabY);

            mirrorOption.writeOptionSetting(settings.data());

            preset->setSettings(settings);
        }

        if (dabRotation != 0.0) {
            KisPaintOpSettingsSP settings = preset->settings()->clone();

            KisPressureRotationOption rotationOption;
            rotationOption.readOptionSetting(settings);

            rotationOption.setChecked(true);
            rotationOption.setCurveUsed(false);

            rotationOption.setValue(dabRotation / 360.0);

            rotationOption.writeOptionSetting(settings.data());

            preset->setSettings(settings);
        }


        QString testName =
            QString("%7_cmY_%1_cmX_%2_cR_%3_dmX_%4_dmY_%5_dR_%6")
            .arg(mirrorY)
            .arg(mirrorX)
            .arg(rotation)
            .arg(mirrorDabX)
            .arg(mirrorDabY)
            .arg(std::fmod(360.0 - dabRotation, 360.0))
            .arg(m_prefix);

        KisResourcesSnapshotSP resources =
            new KisResourcesSnapshot(image,
                                     paint1,
                                     manager.data());

        resources->setupPainter(&gc);

        doPaint(gc);

        checkOneLayer(image, paint1, testName);
    }
示例#22
0
文件: types.c 项目: Lanozavr/pvs
static void printTypeExample(Tree *example, unsigned num, char *names[], 
			     char orders[], unsigned indices[], 
			     int *univs[], int trees[])
{
  trace_descr bools;
  int i;

  bools = find_one_path(example->bddm,
			BDD_ROOT(example->bddm,
				 example->behavior_handle), 
			example->state);
  for (i = 0; i < num; i++) {
    printf(" %s = ", names[i]);
    switch (orders[i]) {
    case 0: /* Boolean variable */
      { 
	trace_descr t = bools;
	while (t && (t->index != indices[i]))
	  t = t->next;
	if (t && t->value) 
	  printf("true\n");
	else 
	  printf("false\n");
	break;
      }
    case 1: /* first-order variable */
      {
	int j, first = 1, any = 0;
	for (j = 0; univs[i][j] != -1; j++) {
	  int u = univs[i][j];
	  Tree *t = findNode(example, guide.univPos[u], 0);
	  if (t) {
	    char *univname = guide.univName[u];
	    char *path = (char *) mem_alloc(strlen(univname)+2);
	    sprintf(path, "%s:", univname);
	    printTypePositions(t, indices[i], &first, 1, 0, path,
			       guide.ssType[t->d]);
	    if (!first)
	      any = 1;
	    mem_free(path);
	  }
	}
	if (!any)
	  printf("?");
	printf("\n");
	break;
      }
    case 2: /* second-order variable */
      {
	if (trees[i]) { /* print as typed tree */
	  int j, any = 0;
	  for (j = 0; univs[i][j] != -1 && !any; j++) {
	    int u = univs[i][j];
	    Tree *t = findNode(example, guide.univPos[u], 0);
	    if (t) {
	      char *univname = guide.univName[u];
	      char *path = (char *) mem_alloc(strlen(univname)+2);
	      sprintf(path, "%s:", univname);
	      t = printTreeRoot(t, indices[i], guide.ssType[t->d], path);
	      mem_free(path);
	      if (t) {
		printTypedTree(guide.ssType[t->d], t, indices[i]);
		any = 1;
	      }
	    }
	  }
	  if (!any)
	    printf("?");
	  printf("\n");
	}
	else { /* print as set of positions */
	  int j, first = 1;
	  printf("{");
	  for (j = 0; univs[i][j] != -1; j++) {
	    int u = univs[i][j];
	    Tree *t = findNode(example, guide.univPos[u], 0);
	    if (t) {
	      char *univname = guide.univName[u];
	      char *path = (char *) mem_alloc(strlen(univname)+2);
	      sprintf(path, "%s:", univname);
	      printTypePositions(t, indices[i], &first, 1, 1, path,
				 guide.ssType[t->d]);
	      mem_free(path);
	    }
	  }
	  printf("}\n");
	}
	break;
      }
    }
  }
  kill_trace(bools);
}
示例#23
0
bool ZLBlockTreeView::onStylusMove(int x, int y) {
	ZLBlockTreeNode *node = findNode(y);
	ZLApplication::Instance().setHyperlinkCursor(node != 0 && node->isOverHyperlink(x, y));
	return true;
}
示例#24
0
int main(void)
{
	HuffmanTree *hft = createHFTree();
	
	int erro, pos;
	char code[100];
	short verbose = 1;
	
	//Inserir código novo
	strcpy(code, "000");
	erro = addNode(hft, code, 0, verbose);

	//Inserir código já inserido
	strcpy(code, "000");
	erro = addNode(hft, code, 1, verbose);

	//Tentar derivar folha
	strcpy(code, "00001");
	erro = addNode(hft, code, 1, verbose);
		
	//Inserir código novo
	strcpy(code, "11100");
	erro = addNode(hft, code, 3, verbose);

	//Inserir código já inserido
	strcpy(code, "11100");
	erro = addNode(hft, code, 3, verbose);

	//Tentar derivar folha
	strcpy(code, "111001");
	erro = addNode(hft, code, 3, verbose);

	printf("---------------\n");


	//---- pesquisar código bit a bit (simula situação correspondente ao deflate)
	//exemplo 1
	char buffer[100];
	strcpy (buffer, "11100010");
	int lv = 0, lenc, len = (int) strlen(buffer);
	int sair = false;
	strcpy (code, "");
	char nextBit;
	
	while(!sair && lv < len)
	{
		nextBit = buffer[lv];
		
		//actualizar code com o próximo bit
		lenc = (int) strlen(code);
		code[lenc] = nextBit;
		code[lenc+1] = 0;

		//pesquisar next bit na árvore, a partir do nó corrente
		pos = nextNode(hft, nextBit);
		//printf("%d    %d    %d    %d\n", lv, hft->curNode->index, hft->curNode->left, hft->curNode->right);
					
		if (pos != -2)
			sair = true;
		else
			lv = lv + 1;
	}
	if (pos == -1)
		printf("Código '%s' não encontrado\n", code);
	else if (pos == -2)
		printf("Código '%s' não encontrado, mas prefixo\n", code);
	else
		printf("Código '%s' corresponde à posição %d do alfabeto\n", code, pos);
		
	//exemplo 2
	resetCurNode(hft);  //volta a possicionar curNode na raíz da árvore
	strcpy (buffer, "1110");
	lv = 0; 
	len = (int) strlen(buffer);
	sair = 0;
	strcpy (code, "");
	
	while(!sair && lv < len)
	{
		nextBit = buffer[lv];
		
		//actualizar code com o próximo bit
		lenc = (int) strlen(code);
		code[lenc] = nextBit;
		code[lenc+1] = 0;

		//pesquisar next bit na árvore, a partir do nó corrente
		pos = nextNode(hft, nextBit);
		//printf("%d    %d    %d    %d\n", lv, hft->curNode->index, hft->curNode->left, hft->curNode->right);
					
		if (pos != -2)
			sair = true;
		else
			lv = lv + 1;
	}
	if (pos == -1)
		printf("Código '%s' não encontrado\n", code);
	else if (pos == -2)
		printf("Código '%s' não encontrado, mas prefixo\n", code);
	else
		printf("Código '%s' corresponde à posição %d do alfabeto\n", code, pos);

	printf("---------------\n");



	// ------------------- Pesquisa de códigos inteiros
	
	strcpy(code, "000");
	pos = findNode(hft, code, verbose);
	
	strcpy(code, "11100");
	pos = findNode(hft, code, verbose);

	strcpy(code, "111");
	pos = findNode(hft, code, verbose);


    system("PAUSE");
    return EXIT_SUCCESS;
}
示例#25
0
int Circuit::createSUBModule(const string &input1, const string &input2, const string &output, unsigned int numBits)
{
  Node* node;
  // create input nodes
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = input1 + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = input2 + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // create output nodes
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // create one node and zero node
  Node* zeroNode = createNode("ZERO");
  createZERONode(zeroNode);
  
  Node* oneNode = createNode("ONE");
  createONENode(oneNode);
  
  // create c_out node
  Node* c_out = createNode("cout");
  
  // create internal1 nodes
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output+"h";
    name = name + "[" + sstr.str() + "]";
    
    node = createNode(name);
  }
  
  // inverse the input2
  for (unsigned int i = 0; i < numBits; ++i)
  {
    stringstream sstr;
    sstr << i;
    string name = output +"h";
    name = name + "[" + sstr.str() + "]";
    Node* hh = findNode(name);
    assert(hh != NULL);
    
    name = input2 + "[" + sstr.str() + "]";
    Node* inNode2 = findNode(name);
    assert(inNode2 != NULL);
    
    createXOR3Node(zeroNode, oneNode, inNode2, hh);
  }
  
  // add input1 and the complemented input2
  createADDModule(input1, output+"h", "ONE", output, "cout" ,numBits);
  
  // when you have implemented this function,
  // change 'return -1' to 'return 0'
  return 0;
}
示例#26
0
int ccTreeMap::findValue(const char* key, ICompareStrings *comparer) {
    ccTreeMap *result = findNode(key, comparer);
    if (result == NULL)
        return -1;
    return result->value;
}
void Tree::deleteNode(int key)
{
	// Find the node.
	Node* thisKey = findNode(key, root);
	MTPD("Tree::deleteNode found node: %d\n", thisKey);
	MTPD("handle: %d\n", thisKey->Mtpid());

	if (thisKey == root) {
		if (thisKey->Right()) {
			root = thisKey->Right();
			root->setParent(NULL);
			return;
		}
		if (thisKey->Left()) {
			root = thisKey->Left();
			root->setParent(NULL);
			return;
		}
		root = NULL;
		delete thisKey;
		return;
	}

	if ( thisKey->Left() == NULL && thisKey->Right() == NULL )
	{
		if ( thisKey->Mtpid() > thisKey->Parent()->Mtpid() ) {
			thisKey->Parent()->setRight(NULL);
		}
		else {
			thisKey->Parent()->setLeft(NULL);
		}
		delete thisKey;
		return;
	}

	if ( thisKey->Left() == NULL && thisKey->Right() != NULL )
	{
		if ( thisKey->Mtpid() > thisKey->Parent()->Mtpid() )
			thisKey->Parent()->setRight(thisKey->Right());
		else
			thisKey->Parent()->setLeft(thisKey->Right());
		thisKey->Right()->setParent(thisKey->Parent());
		delete thisKey;
		return;
	}
	if ( thisKey->Left() != NULL && thisKey->Right() == NULL )
	{
		if ( thisKey->Mtpid() > thisKey->Parent()->Mtpid() )
			thisKey->Parent()->setRight(thisKey->Left());
		else
			thisKey->Parent()->setLeft(thisKey->Left());
		thisKey->Left()->setParent(thisKey->Parent());
		delete thisKey;
		return;
	}

	if ( thisKey->Left() != NULL && thisKey->Right() != NULL )
	{
		Node* sub = predecessor(thisKey->Mtpid(), thisKey);
		if ( sub == NULL )
			sub = successor(thisKey->Mtpid(), thisKey);

		if ( sub->Parent()->Mtpid() <= sub->Mtpid() )
			sub->Parent()->setRight(sub->Right());
		else
			sub->Parent()->setLeft(sub->Left());

		thisKey->setMtpid(sub->Mtpid());
		delete sub;
		return;
	}
}
示例#28
0
int main(int argc, char *argv[]) {
	/*
	printf("Argument count: %d\n", argc);
	for (int i = 0; i < argc; i++) {
		printf("Argument vector values:%s at %p memory\n", argv[i], argv[i]);
		for (char *j=argv[i]; *j!='\0'; j++) {
			printf("Another way to print argument vector values: "
                               "%c at %p memory\n", *j, j);
		}
	}
	*/

	//int arr[MAX_LEN] = {5,60,14,50,9,10,5,14,130,14,0,1,2,13,4,10,5,14,130,14,0,1,2,13,4};
	//int arr[MAX_LEN] = {14,14,14,14,14,14,14,14,14,14,14,14,14,14,14};
	int arr[MAX_LEN] = {14,60,14,50,9,10,5,14,130,14,0,1,2,15,14};
	//int arr[MAX_LEN] = {5,5,5,5,5,0,2,7,2,15,6,6,0,15,5};
	//int arr[MAX_LEN] = {5,5,5,5,5,5,5,15,15,5,5,5,5,5,5};
	//int arr[MAX_LEN] = {5,5,5,5,5,5,5,5,5,5,5,5,5,5,5};

	struct node *head = NULL; /* beginning */
	struct node *end = NULL; /* end */

	head = newNode(arr[0]);

	//printf("Start Pointer of Linked List is: %p\n",head);
	//printf("Start Data of Linked List is: %d\n",head->data);

	end = newNode(arr[1]);
	head->next = end;
	//printf("Initial End Pointer of Linked List is: %p\n",end);
	//printf("Initial End Data of Linked List is: %d\n",end->data);

	for (int num = 2; num<MAX_LEN; num++) {
		end = appendNode(end,arr[num]);
		//printf("Appended Pointer of Linked List is: %p\n",end);
		//printf("Appended Data of Linked List is: %d\n",end->data);
	}

	iterateNodes(head);

	//head = addNodetoFront(head,14);
	//iterateNodes(head);

	int findVal = 14;
	struct node *foundNode, *newHead = NULL;

	foundNode = findNode(head,findVal);
	if (foundNode) {
		printf("Value: %d found at address: %p\n",findVal,foundNode);
		newHead = sortAroundVal(&head,newHead,findVal);
	}
	else {
		printf("Value: %d not found\n",findVal);
	}

	iterateNodes(newHead);

	iterateNodes(head);

	printf("\nFreeing Linked List old:\n");
	struct node *temp;
	while (head!=NULL) {
		temp = head;
		head=head->next;
		free(temp);
	}
	//head = NULL;     /* Mark list as empty*/

	printf("\nFreeing Linked List new:\n");
	while (newHead!=NULL) {
		temp = newHead;
		newHead=newHead->next;
		free(temp);
	}

	return 0;
}
示例#29
0
void FixAspectRatio(){
	unsigned int cameraNode = findNode("avatar_camera");

	if(cameraNode)
		setCameraAspectRatio(cameraNode, (float)getScreenWidth() / (float)getScreenHeight());
}
示例#30
0
// Removes one element from the dictionary
bool
AVLDictionary::removeElement(KeyType key)
{
	if (debug)
	{
		printf("------------------------------------\n");
		printf("removeElement(\"%s\")\n",  key);
		printf("---------- Before -----------------\n");
		printNode("", root, 0);
	}

	AVLNode *node;
	node = findNode(key);
	
	if (node == NULL)
	{
     	return false;
    }
   
	if (node->left == NULL && node->right == NULL)
	{
		if ( node == node->parent->left)
		{
			node->parent->left = NULL;
		}
		else
		{
			node->parent->right = NULL;
		}

		AVLNode *m;
		m = node->parent;
		
		while(m != NULL)
		{
			int maxheight = 0;
			if(m->left != NULL)
			{
				maxheight = m->left->height;
			}
			if (m->right != NULL && maxheight < m->right->height)
			{
				maxheight = m->right->height;
			}
			m->height = maxheight +1;
			m = m->parent;
		}

		restructure(node->parent);

		delete node;
    }
	else if (node->left == NULL)
	{
	    AVLNode temp;
   	
     	temp.height = node->height;
     	strcpy((char*)temp.key, node->key);
     	temp.data = node->data;
      
     	node->height = node->right->height;
     	strcpy((char*)node->key, node->right->key);
     	node->data = node->right->data;
 
     	node->right->height = temp.height;
     	strcpy((char*)node->right->key, temp.key);
     	node->right->data = temp.data;
   
     	delete node->right;
   
     	node->right = NULL;   
   
     	AVLNode *m = node->parent;
     	while(m != NULL)
		{
     		int maxheight = 0;
     		if(m->left != NULL)
			{
     			maxheight = m->left->height;
     		}
     		if (m->right != NULL && maxheight < m->right->height)
			{
     			maxheight = m->right->height;
     		}
     		m->height = maxheight +1;
     		m = m->parent;
   
     	}
   
     	restructure(node);
    }
	else if (node->right == NULL)
	{
     	AVLNode temp;
   
     	temp.height = node->height;
     	strcpy((char*)temp.key, node->key);
     	temp.data = node->data;
 
     	node->height = node->left->height;
     	strcpy((char*)node->key, node->left->key);
     	node->data = node->left->data;
   
     	node->left->height = temp.height;
     	strcpy((char*)node->left->key, temp.key);
     	node->left->data = temp.data;
   
     	delete node->left;
   
     	node->left = NULL;   	
   
     	AVLNode *m;
		m = node->parent;
		
     	while(m != NULL)
		{
     		int maxheight = 0;
     		if( m->left != NULL)
			{
     			maxheight = m->left->height;
     		}
     		if (m->right != NULL && maxheight < m->right->height)
			{
     			maxheight = m->right->height;
     		}
     		m->height = maxheight +1;
     		m = m->parent;
   
     	}
   
     	restructure(node);
    }
	else
	{
		AVLNode *replacement;   
		replacement = node->left;
		
     	if (replacement->right == NULL)
		{
     		replacement = node->right;
     		while(replacement->left != NULL)
			{
     			replacement = replacement->left;
     		}
     	}
		else
		{
			while (replacement->right != NULL)
			{
     			replacement = replacement->right;
     		}
   
     	}
		
		AVLNode temp;
       
		temp.height = node->height;
     	strcpy((char*)temp.key, node->key);
     	temp.data = node->data;
   
     	node->height = replacement->height;
     	strcpy((char*)node->key, replacement->key);
     	node->data = replacement->data;
 	
     	replacement->height = temp.height;
     	strcpy((char*)replacement->key, temp.key);
     	replacement->data = temp.data;
   	
     	AVLNode *n;
		n = replacement->parent;
		
     	if (n != NULL)
		{
			if (replacement == n->left)
			{
     			n->left = NULL;   
     			delete replacement;
     		}
			else
			{
     			n->right = NULL;
     			delete replacement;
     		}
   
			AVLNode *m = n;
			while(m != NULL)
			{
				int maxheight = 0;
				if(m->left != NULL)
				{
					maxheight = m->left->height;
				}
				if (m->right != NULL && maxheight < m->right->height)
				{
					maxheight = m->right->height;
				}
				m->height = maxheight +1;
				m = m->parent;   
			}
	   
			restructure(n);
		}
	}
	
	nElements--;
	
	if (debug)
	{
		printf("---------- After -----------------\n");
		printNode("", root, 0);

		checkRecursive(root);
	}
	
	return true;
}