示例#1
0
文件: Hash.cpp 项目: amorsey/Pokedex
void Hash::addPokes(int num, string pokeName, string pokeType1, string pokeType2){
    
    int indexI = hashFunc(pokeType1);
    int indexJ = hashFunc(pokeType2);
    
    if(hashTable[indexI][indexJ] == nullptr){
        hashTable[indexI][indexJ] = new Pokes;
        hashTable[indexI][indexJ]->number = num;
        hashTable[indexI][indexJ]->next = nullptr;
        hashTable[indexI][indexJ]->name = pokeName;
        hashTable[indexI][indexJ]->type1 = pokeType1;
        hashTable[indexI][indexJ]->type2 = pokeType2;
    } else {
        Pokes* p = hashTable[indexI][indexJ];
        while(p->next){
            p = p->next;
        }
        Pokes* t = new Pokes;
        t->number = num;
        t->next = nullptr;
        t->name = pokeName;
        t->type1 = pokeType1;
        t->type2 = pokeType2;
        p->next = t;
    }
}
示例#2
0
int OneSideHashJoin::getRow(PosVal **pv_, unsigned int pvNum_){
	int returnCode;
	//ONESIDE_HASH_NODE *hnp;
	unsigned int hashkey;
	
	if(getRowFlag == 0){
		while(1){
			returnCode = outerOpeNode->getRow(&pv[innerAttriNum], outerAttriNum);
			if(returnCode != 0){
				delHash();
				getRowFlag = -1;
				return -1;
			}else{
				hashkey = 0;
				for(unsigned int i = 0; i < nodeNum; i++)
					hashkey += hashFunc(pv[outerPos[i]]);
				hashkey = hashkey%HASH_SIZE;
				innerHash->ScanNode->setHashkey(hashkey);
				getRowFlag = 1;
				break;
			}
		}
	}			

	if(getRowFlag == -1){
		return -1;
	}

	while(1){
		returnCode = innerHash->ScanNode->getRow(pv, innerAttriNum);
		if(returnCode == 0){
			unsigned int posIndex;
			for(posIndex = 0; posIndex < nodeNum; posIndex++){
				if(!(*pv[innerPos[posIndex]] == pv[outerPos[posIndex]]))
					break;
			}
			if(posIndex == nodeNum){
				for(unsigned int i = 0; i < attriNum; i++) *pv_[i] = *pv[i];
				return 0;
			}
			continue;
		}

		returnCode = outerOpeNode->getRow(&pv[innerAttriNum], outerAttriNum);
		if(returnCode != 0){
			getRowFlag = -1;
			delHash();
			return -1;
		}else{
			hashkey = 0;
			for(unsigned int i = 0; i < nodeNum; i++)
				hashkey += hashFunc(pv[outerPos[i]]);
			hashkey %= HASH_SIZE;
			innerHash->ScanNode->setHashkey(hashkey);
		}
	}	
}			
示例#3
0
//확장성 해시 인덱스 함수.
int extendible_Hash_Indexing(RECORD* recordPtr) {
	unsigned __int64 bitstringedKey;
	unsigned __int64 hashed_Key = hashFunc(recordPtr->name);
	int resultAdd;	//addToBucket 의 결과를 저장할 변수.
	BUCKET* targeted_Bkt = NULL;	//레코드가 들어갈 버켓 주소.

	//전역 깊이에 따라 들어온 키의 비트스트링을 잘라서 저장한다.
	bitstringedKey = bitstring(hashed_Key, global_Depth);

	targeted_Bkt = dir_Ptr[bitstringedKey].bktPtr;

	if (targeted_Bkt == NULL) return -1;	//매치되는 비트스트링이 디렉토리에 없는 경우. 정상적인 환경에서는 있을 수 없는 경우.

	resultAdd = add_To_Bucket(targeted_Bkt, recordPtr);

	if (resultAdd == 0);

	//버킷이 오버플로우 된 경우 split.
	else if (resultAdd == BKT_OVERFLOW) {
		if (bkt_Split(targeted_Bkt) == -1) {
			printf("Memory realloc 과정중 오류가 생겼습니다.\n 충분한 메모리를 확보 후 다시 실행하십시오.\n");
			return -1;
		}
		extendible_Hash_Indexing(recordPtr);
	}

	else return 0;
}
int AddOrReplaceElementInHashMap(SimpleHashMap *oHashMap, const char *iElementID, void *iElement)
{
    tHashMapElement *newElement;
    if (_createNewElement(&newElement, iElementID, iElement)) return -1;
    unsigned long index = hashFunc(oHashMap, iElementID, oHashMap->numberOfBuckets);
    tLinkedListElement *current = oHashMap->elements[index].head;
    /*
     Advance iterator while we haven't reached end of the list and the current element ID differs from the inserted one
     */
    while (current && strcmp(((tHashMapElement*) current->element)->elementID, iElementID))
        current = current->next;
    
    /*
     If no element with similar ID was found - insert new element in list.
     */
    if (!current) {
        if (AddElementToLinkedList(&oHashMap->IDs, (void*)iElementID) == -1) return -1;

        if (AddElementToLinkedList(&oHashMap->elements[index], newElement))
            return -1;
        oHashMap->count++;
    }
    else
    {
        /*
         Replace existing element with the inserted one.
         */
        current->element = newElement;
    }
    return 0;
}
示例#5
0
void set_ht( HashTable * hashtable, Node * node){

    int cell=0;
    
    HeadNode * headNode;
    
    
    cell=hashFunc(hashtable,node->record->phone);
    
    
    if((hashtable->table[cell])== NULL) {
         
        headNode=(HeadNode *)malloc(sizeof(HeadNode));
        initHeadNode(headNode);
        hashtable->table[cell]=headNode;
        insert_Tolist(headNode,node);
        
    }
    
    else
    {
        
        insert_Tolist(hashtable->table[cell],node);
        
    }
       
        
    
}
示例#6
0
void 
test__hash_func(void **state)
{   
    HASH_TABLE_SIZE = 1000;
    Oid o = 100;
	int result = hashFunc(o);
    assert_true(result == 100);
}
示例#7
0
void 
test__hash_func_range(void **state)
{   
    HASH_TABLE_SIZE = 1000;
    Oid o = 1000000;
	int result = hashFunc(o);
    assert_true(result < HASH_TABLE_SIZE && result >= 0);
}
示例#8
0
/* ----------------------------------------------------------------
 *	ExecHashGetBucket
 *
 *	Get the hash value for a tuple
 * ----------------------------------------------------------------
 */
int
ExecHashGetBucket(HashJoinTable hashtable,
		  ExprContext *econtext,
		  Var *hashkey)
{
    int 	bucketno;
    Datum 	keyval;
    bool isNull;
    
    
    /* ----------------
     *	Get the join attribute value of the tuple
     * ----------------
     */
    keyval = ExecEvalVar(hashkey, econtext, &isNull);
    
    /*
     * keyval could be null, so we better point it to something
     * valid before trying to run hashFunc on it. --djm 8/17/96
     */
    if(isNull) {
	execConstByVal = 0;
	execConstLen = 0;
	keyval = (Datum)"";
    }

    /* ------------------
     *  compute the hash function
     * ------------------
     */
    if (execConstByVal)
        bucketno =
	    hashFunc((char *) &keyval, execConstLen) % hashtable->totalbuckets;
    else
        bucketno =
	    hashFunc((char *) keyval, execConstLen) % hashtable->totalbuckets;
#ifdef HJDEBUG
    if (bucketno >= hashtable->nbuckets)
	printf("hash(%d) = %d SAVED\n", keyval, bucketno);
    else
	printf("hash(%d) = %d\n", keyval, bucketno);
#endif
    
    return(bucketno);
}
示例#9
0
文件: Hash.cpp 项目: amorsey/Pokedex
void Hash::get(string type)
{
    for(int i = 0; i < 18; i++){
        Pokes* p = hashTable[hashFunc(type)][i];
        while(!(p == nullptr)){
            display(p);
            p = p->next;
        }
    }
    
    for(int i = 0; i < 18; i++){
        Pokes* p = hashTable[i][hashFunc(type)];
        while(!(p == nullptr)){
            display(p);
            p = p->next;
        }
    }
}
int AddElementToHashMapWithoutChecks(SimpleHashMap *oHashMap, const char *iElementID, void *iElement)
{
    if (AddElementToLinkedList(&oHashMap->IDs, (void*) iElementID) == -1) return -1;
    tHashMapElement *newElement;
    if (_createNewElement(&newElement, iElementID, iElement)) return -1;
    unsigned long index = hashFunc(oHashMap, iElementID, oHashMap->numberOfBuckets);
    if (AddElementToLinkedList(&oHashMap->elements[index], newElement) == -1) return -1;
    oHashMap->count++;
    return 0;
}
示例#11
0
 void hashSet(DepthEntry** entries, POINTER_SIZE_INT eip, U_32 hashTableSize,StackDepthInfo info, MemoryManager& mm) {
     POINTER_SIZE_INT key = hashFunc(eip,hashTableSize);
     DepthEntry * e = entries[key];
     if(!e) {
         entries[key] = new(mm) DepthEntry(eip, info, NULL);
     } else {
         for(;e->next!=NULL;e = e->next) ;
         e->next =  new(mm) DepthEntry(eip, info, NULL);
     }
 }
示例#12
0
 StackDepthInfo hashGet(DepthEntry** entries, POINTER_SIZE_INT key, U_32 hashTableSize) {
     DepthEntry * e = entries[hashFunc(key,hashTableSize)];
     assert(e);
     for(;e !=NULL;) {
         if(e->eip == key) 
             return e->info;
         else
             e = e->next;
         assert(e);
     }
     return e->info;
 }
示例#13
0
DepthEntry * getHashEntry(U_8* data, POINTER_SIZE_INT eip, U_32 size) 
{
    if(!size)
        return NULL;
    POINTER_SIZE_INT key = hashFunc(eip,size);
    data += sizeof(StackInfo) + key * sizeof(POINTER_SIZE_INT);
    DepthEntry * entry = (DepthEntry *)*(POINTER_SIZE_INT*)data;
    for(;entry && entry->eip != eip; entry = entry->next) {
        assert(entry!=entry->next);
    }
    return entry;
}
/*!
  Implementation for traverse so always true.
*/
bool SdFixture::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)
{
    debug("SdFixture::execute");
    bool returnValue = true;
#ifdef Q_OS_SYMBIAN
    const TUid fixtureUid = TUid::Uid(0x20026F7E);    
    THashFunction32<RBuf8> hashFunc( RBufHashFunction );
    TIdentityRelation<RBuf8> idFunc( RBufIdentityFunction );
    RHashMap<RBuf8, RBuf8> paramPairs( hashFunc, idFunc );
    CleanupClosePushL( paramPairs );
    debug("SdFixture::execute read params");
    QHashIterator<QString, QString> i(parameters);
    while (i.hasNext()) {
        i.next();
        if(!i.key().isEmpty() && !i.value().isEmpty() && i.key() != OBJECT_TYPE){
            debug("parametrit: " + i.key()+";"+ i.value());
            debug("SdFixture::execute read key");
            RBuf8 keyBuf;
            RBuf8 valueBuf;
            TPtrC16 keyStr(reinterpret_cast<const TUint16*>(i.key().utf16()));
            TPtrC16 valueStr(reinterpret_cast<const TUint16*>(i.value().utf16()));
            keyBuf.Create(keyStr.Length());
            valueBuf.Create(valueStr.Length());
            keyBuf.Copy(keyStr);
            valueBuf.Copy(valueStr);
            debug("SdFixture::execute insert to hash");    
            paramPairs.InsertL( keyBuf, valueBuf );
            debug("SdFixture::execute pop hbufs");    
        }
    }
    debug("SdFixture::execute make fixture");
    CTasFixturePluginInterface* fixture = CTasFixturePluginInterface::NewL( fixtureUid );
    CleanupStack::PushL( fixture );
    debug("SdFixture::execute conver actionname");
    TPtrC16 actionStr(reinterpret_cast<const TUint16*>(actionName.utf16()));
    RBuf8 actionBuf;
    actionBuf.Create(actionStr.Length());
    CleanupClosePushL( actionBuf );
    actionBuf.Copy(actionStr);
    debug("SdFixture::execute execute fixture");
    RBuf8 response;
    CleanupClosePushL( response );
    if(fixture->Execute( NULL, actionBuf, paramPairs, response ) != KErrNone){
        returnValue = false;
    }
    debug("SdFixture::execute convert response");
    stdOut  = XQConversions::s60Desc8ToQString(response);
    CleanupStack::PopAndDestroy( 4 );//response, fixture, paramPairs
#endif    
    debug("SdFixture::execute done");
    return returnValue;
}
示例#15
0
void insertTab( struct SymTable *table, struct SymNode *newNode )
{
	int location = hashFunc( newNode->name );

	if( table->entry[location] == 0 ) {	// the first
		table->entry[location] = newNode;
	} 
	else {
		struct SymNode *nodePtr;
		for( nodePtr=table->entry[location] ; (nodePtr->next)!=0 ; nodePtr=nodePtr->next );
		nodePtr->next = newNode;
		newNode->prev = nodePtr;
	}
}
int main()
{
	const int lengthArray = 30000;
	Word **m = createArray(lengthArray);

	FILE *f = fopen("input.txt", "r");
	
	while (!feof(f))
	{
		char s[50];
		scanWord(s, f);
		if (s[0] != '\0')
		{
			unsigned int a = hashFunc(s, lengthArray);
			if (m[a] == NULL)
				m[a] = createWord(s);
			else
			{
				Word *tmp = m[a];
				while ((tmp->next != NULL) && (strcmp(tmp->s, s) != 0))
				{
					tmp = tmp->next;
				}
				if (strcmp(tmp->s, s) == 0)
					tmp->repeats++;
				else
					tmp->next = createWord(s);
			}
		}
	}
	fclose(f);
	
	for (int i = 0; i < lengthArray; i++)
	{
		if (m[i] != NULL)
		{
			Word *tmp = m[i];
			while (tmp != NULL)
			{
				printf("%s  -  %i\n", tmp->s, tmp->repeats);
				tmp = tmp->next;
			}
		}
	}

	clear(m, lengthArray);
	delete[] m;
	scanf("%*");
	return 0;
}
示例#17
0
htEntry *htGet(hashtb *ht, char *key)
{
    int index, i = 0;

    index = hashFunc(key, strlen(key)) % ht->size;
    while (ht->table[index] != NULL) {
        if (!strcmp(ht->table[index]->key, key)) {
            return ht->table[index];
        }
        index = 2 * ++i - 1;
        if (index >= ht->size) index -= ht->size;
    }
    return NULL;
}
void* PointerSetBase::removeItem(void* obj, HashFunction hashFunc) {
    if (!validValue(obj)) {
        return NULL;
    }
    size_t objHash = hashFunc(obj);
    size_t pos = probeItems(obj, objHash, mItems, mShift);
    DCHECK(pos < (1U << mShift));

    void* result = mItems[pos];
    if (!validValue(result)) {
        // Item was not in the array.
        return NULL;
    }
    mItems[pos] = TOMBSTONE;
    mCount--;
    return result;
}
int DisposeHashMapWithIDs(SimpleHashMap *oHashMap)
{
    tLinkedListElement *current = oHashMap->IDs.head;
    tLinkedListElement *tmp;
    SimpleLinkedList elementsAtIndex;
    unsigned long index;
    while (current) {
        index = hashFunc(oHashMap, current->element, oHashMap->numberOfBuckets);
        DisposeLinkedListAndElements(&oHashMap->elements[index]);
        free(current->element);
        current = (tmp=current)->next;
        free(tmp);
    }
    free(oHashMap->_coeffs);
    free(oHashMap->elements);
    return 0;
}
void* GetElementInHashMapByID(SimpleHashMap *iHashMap, const char *iElementID)
{
    /* The length of iElementID is greater than the length  of any key in iHashMap - hence, definitely no element will match - return NULL. */
    if (strlen(iElementID) > iHashMap->_coeffsCount) return NULL;
    /*Since if we are here, length of searched key is definetely <= max length of key in the iHashMap, the 'hashFunc' function won't change iHashMap.*/
    unsigned long index = hashFunc(iHashMap, iElementID, iHashMap->numberOfBuckets);
    
    SimpleLinkedList elementsAtIndex = iHashMap->elements[index];
    
    tLinkedListElement* current = elementsAtIndex.head;
    while (current && strcmp((char*)((tHashMapElement*)current->element)->elementID, iElementID)) {
        current = current->next;
    }
    
    if (current) return ((tHashMapElement*)current->element)->element;
    else return NULL;
}
void TestAppSimplexGrid::eraseSimplex( double x, double y ){
	double da,db; UHALF ia,ib;
	bool  s      = grid.simplexIndex        ( mouse_begin_x, mouse_begin_y, ia,ib, da, db );
    ULONG bucket = grid.getBucketInt        ( ia, ib );
    int index  = grid.getFirstBucketIndex   ( bucket );
    MySimplexField* p;
    if( index >= 0 ){
        //printf( " errasing tile, index %i \n", index );
        p = grid.fields[ index ].object;
        if( s ){ p->hi=false; }else{ p->lo=false; };
        if( !( p->hi || p->lo ) ){
            printf( " removed (%i,%i) index %i hash %i bucket %i \n", ia, ib, index, grid.mask & hashFunc( bucket ), bucket );
            //printf( " empty field %i removed from HashMap \n", index );
            grid.HashMap<MySimplexField>::remove( index, grid.mask & hashFunc( bucket ) );
            delete p;
        }
    };
};
示例#22
0
Record * find_record(HashTable * hashtable, char * phone){
    
    HeadNode * headNode;
    Node * node;
    int cell;
    Record * rec=NULL;
    
    cell=hashFunc(hashtable,phone);
    
    headNode=hashtable->table[cell];
    
    if(headNode==NULL){
       // printf("find_record: The HeadNode is NULL\n");
        return NULL;
    }
    
    
    node=headNode->firstNode;
    
    if(node==NULL){
       //printf("find_record: The List is empty\n");
        return NULL;
    }
    
    while(node!=NULL){
       
        if(strcmp(node->record->phone,phone)==0){
         
           // printf("find_record: The record is found\n");
            rec=node->record;
            return rec;
        }
      
      node=node->next;
    
    }
    
    if(rec==NULL){
      //printf("find_record:No record found \n");
      return rec;
    }
}
示例#23
0
struct SymNode *lookupSymbol( struct SymTable *table, const char *id, int scope, __BOOLEAN currentScope )
{
	int index = hashFunc( id );

	struct SymNode *nodePtr, *result=0;
	for( nodePtr=(table->entry[index]) ; nodePtr!=0 ; nodePtr=(nodePtr->next) ) {
		if( !strcmp(nodePtr->name,id) && ((nodePtr->scope)==scope) ) {
			return nodePtr;
		}
	}
	// not found...
	if( scope == 0 )	return 0;	// null
	else {
		if( currentScope == __TRUE ) {
			return 0;
		}
		else {
			return lookupSymbol( table, id, scope-1, __FALSE );
		}
	}
}
示例#24
0
// Add key:val to hashtable.
//
// returns:
//     -1: out of memory.
//      0: success.
//      1: key already exists, its val be overwrited by the new val.
int htSet(hashtb *ht, char *key, void *val)
{
    int index, i = 0;
    htEntry *e;

    index = hashFunc(key, strlen(key)) % ht->size;
    while (ht->table[index] != NULL) {
        if (!strcmp(ht->table[index]->key, key)) {
            ht->table[index]->val = val;
            return 1;
        }
        index = 2 * ++i - 1;
        if (index >= ht->size) index -= ht->size;
    }
    if ((e = malloc(sizeof(*e))) == NULL)
        return -1;
    e->key = key;
    e->val = val;
    ht->table[index] = e;
    ht->used++;
    return 0;
}
示例#25
0
void OneSideHashJoin::storeInnerNode(void){
	unsigned int hashkey;
	//ONESIDE_HASH_NODE *setNode;
	int returnCode;
	unsigned int dataSize;
	int buffSize = getInnerDataBuffSize();
	char innerDataBuffer[buffSize];

	while(1){
		returnCode = innerOpeNode->getRow(pv, innerAttriNum);
		if(returnCode == -1)break;
		hashkey = 0;
		for(unsigned int i = 0; i < nodeNum; i++)
			hashkey += hashFunc(pv[innerPos[i]]);
		hashkey %= HASH_SIZE;

		//setNode = findSetHashTable(innerHashTable, hashkey, innerPos);
		
		dataSize = getDataBuffer(innerDataBuffer, buffSize, 0 , innerAttriNum);
		innerHash->db->writeRecord(&hashkey, sizeof(hashkey), innerDataBuffer, dataSize, true);
		//setNode->num++;
	}
}
示例#26
0
bool hashTable::init(const list<string>& listToBeInserted, double factor)
{
	if (listToBeInserted.empty() || factor <= 0.f)
	{
		return false;
	}

	int nrElems = listToBeInserted.size();
	int len = getNextPrime(nrElems/factor);

	table_.clear();
	table_.resize(len);

	for (list<string>::const_iterator it = listToBeInserted.begin(); it != listToBeInserted.end(); ++it)
	{
		string q = (*it);
		unsigned int ind = hashFunc(q);
		ind = ind % table_.size();
		table_[ind].push_back(q);
	}

	return true;
}
void* PointerSetBase::addItem(void* obj, HashFunction hashFunc) {
    if (!validValue(obj)) {
        return NULL;
    }
    size_t objHash = hashFunc(obj);
    size_t pos = probeItems(obj, objHash, mItems, mShift);
    DCHECK(pos < (1U << mShift));

    void* result = mItems[pos];
    if (validValue(result)) {
        // Simple replacement.
        DCHECK(result == obj);
        return result;
    }
    mItems[pos] = obj;
    mCount++;

    if (result != TOMBSTONE) {
        // No need to resize when replacing tombstone.
        maybeResize(hashFunc);
    }

    return NULL;
}
/**
 * FUNCTION NAME: hashFunction
 *
 * DESCRIPTION: This functions hashes the key and returns the position on the ring
 * 				HASH FUNCTION USED FOR CONSISTENT HASHING
 *
 * RETURNS:
 * size_t position on the ring
 */
size_t MP2Node::hashFunction(string key) {
	std::hash<string> hashFunc;
	size_t ret = hashFunc(key);
	return ret%RING_SIZE;
}
示例#29
0
SolverMIP::SOLVERSTAT FacilityLocation::solveLRExtentedFormulations(MulltipleCutSetSeparation _cutSetSepFunc, double _tol)
{
	int pos = 0;
	int nbCuts = 0;
	int sentinel = 0;
	int MAX_ITER = 100;
	int tailOffCounter = 0;
	int tailOffTol = 3;
	int printInterval = 5;
	double currentLp = 0., lastLp = 0.;
	bool noViolatedCutFound = true;
	std::set<long> hashTable;
	TypeVariableHashPtr vHashPtr = &(vHash);
	std::vector<std::set<int>*> cutSets;
	SolverMIP::SOLVERSTAT ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_UNKNOWN;

	if (xSol != NULL)
		delete[] xSol;

	xSol = new double[getNCols()];
	
	clock_t start = clock();
	do
	{
		lastLp = currentLp;
		status = SolverMIP::solve(SolverMIP::METHOD::METHOD_DUAL);

		if (status == SolverMIP::SOLVERSTAT::SOLVERSTAT_MIPOPTIMAL || status == SolverMIP::SOLVERSTAT::SOLVERSTAT_LPOPTIMAL ||
			status == SolverMIP::SOLVERSTAT::SOLVERSTAT_FEASIBLE)
		{
			ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_FEASIBLE;
			currentLp = getObjVal();

			// Getting fractional node solution
			getX();

			if (sentinel % printInterval == 0)
			{
				printf("\n---- iter: %d\n", sentinel + 1);
				printf("OBJ_VAL = %lf\n", currentLp);
			}

#ifndef DEBUG
			//Printing xNode solution
			printf("\n\n---- iter: %d\n", sentinel + 1);
			for (int varType = Variable::V_X; varType != Variable::V_UNKNOWN; varType += 10)
			{
				VariableHash::iterator vit = vHashPtr->at((Variable::VARTYPE)varType).begin();
				for (; vit != vHashPtr->at((Variable::VARTYPE)varType).end(); ++vit)
				{
					int idx = vit->second;

					if (xSol[idx] > SOLVER_EPS)
						std::cout << (vit->first).toString() << "(" << idx << "); " << xSol[idx] << std::endl;
					printf("");
				}
				printf("");
			}
#endif
			// Verifying optimality conditions
			if (fabs(currentLp - lastLp) < _tol)
			{
				++tailOffCounter;
				if (tailOffCounter > tailOffTol)
				{
					ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_LPOPTIMAL;
					break;
				}
			}
			else
				tailOffCounter = 0;

			// Calling the separation routine
			pos = cutSets.size();
			int cutSize = _cutSetSepFunc(g, vHashPtr, xSol, cutSets, true);

			// If a fractional cycle is found...
			if (cutSets.size() - pos > 0)
			{
				noViolatedCutFound = false;

				for (int i = pos; i < cutSets.size(); ++i)
				{
					std::set<int>* sPtr = cutSets[i];
					// Check whether the cut has already been generated
					unsigned long hashVal = hashFunc(*sPtr);
					std::set<long>::iterator it = hashTable.find(hashVal);
					if (it != hashTable.end())
					{
#ifdef DEBUG
						int warnCode = 990;
						std::string aux = convertSetToString(s);
						std::string msg = "The identified cut set was already separated " + convertSetToString(s);
						warningMsg(NULL, __func__, msg.data(), warnCode);
#endif
					}
					else
						hashTable.insert(hashVal);

					// ... we must find the cut set ...
					std::vector<Variable> cutSet;
					for (VariableHash::iterator vit = vHashPtr->at(Variable::V_Z).begin(); vit != vHashPtr->at(Variable::V_Z).end(); ++vit)
					{
						Variable z = vit->first;
						int head = z.getArc().getHead().getCode();
						int tail = z.getArc().getTail().getCode();

						std::set<int>::iterator hIt = sPtr->find(head);
						std::set<int>::iterator tIt = sPtr->find(tail);

						// ... which is composed by those arcs with one endpoint in S
						bool isHeadInS = hIt != sPtr->end();
						bool isTailInS = tIt != sPtr->end();
						if (!(isHeadInS && isTailInS) && (isHeadInS || isTailInS))
						{
							cutSet.push_back(z);
						}
					}

					// Identifying the y-variables involved in cut set constraints
					// And split them into two sets
					std::vector<Variable> sVec;
					std::vector<Variable> sCompVec;
					for (VariableHash::iterator vit = vHashPtr->at(Variable::V_Y).begin(); vit != vHashPtr->at(Variable::V_Y).end(); ++vit)
					{
						Variable v = vit->first;
						int nodeIdx = v.getVertex1().getCode();

						if (sPtr->find(nodeIdx) != sPtr->end())
						{
							sVec.push_back(v);
						}
						else
						{
							sCompVec.push_back(v);
						}
					}

					// Translating valid inequalities found into cplex/matrix representation
					int nzcnt = cutSet.size() + 2;
					std::vector<int> idx(nzcnt);
					std::vector<double> val(nzcnt);
					for (int i = 0; i < sVec.size(); ++i)
					{
						idx[0] = sVec[i].getColIdx();
						val[0] = -1.0;
						for (int j = 0; j < sCompVec.size(); ++j)
						{
							idx[1] = sCompVec[j].getColIdx();
							val[1] = -1.0;

							for (int k = 0; k < cutSet.size(); ++k)
							{
								idx[k + 2] = cutSet[k].getColIdx();
								val[k + 2] = 1.0;
							}

							// Adding user generated cut
							int nRows = 1;
							double rhs = -1;
							char sense = 'G';
							int rmatbeg = 0;
							int newColsAdded = 0;
							status = CPXaddrows(env, lp, newColsAdded, nRows, nzcnt, &rhs, &sense, &rmatbeg, &idx[0], &val[0], NULL, NULL);
							//status = CPXcutcallbackadd(_env, _cbdata, _wherefrom, nzcnt, -1, 'G', &idx[0], &val[0], CPX_USECUT_FORCE);
							if (status)
							{
								int warnCode = 999;
								std::string msg = "Failed to add integer cut.";
								warningMsg(NULL, __func__, msg.data(), warnCode);
							}
							else
								nbCuts++;

							printf("");
						}
					}
				}
#ifdef DEBUG
					// salva um arquivo .lp com o LP atual
					writeProbLP(".\\lpRelax");
#endif
			}
			else
			{
				// No violated cut was found
				noViolatedCutFound = true;
			}
		
			// If no violated cut was found
			if (noViolatedCutFound)
			{
				ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_LPOPTIMAL;
				break;
			}
		}
		else
		{
			int warnCode = 201;
			std::string msg = "Model is infeasible";
			warningMsg(typeid(*this).name(), __func__, msg.data(), warnCode);

			// salva um arquivo .lp com o LP atual
			writeProbLP(".\\infeasible");

			ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_INFEASIBLE;
			break;
		}

	} while (++sentinel < MAX_ITER);

	// Deallocating memory
	for (int i = 0; i < cutSets.size(); ++i)
	{
		if (cutSets[i] != NULL)
		{
			delete cutSets[i];
			cutSets[i] = NULL;
		}
	}

	clock_t end = clock();
	printf("\n-----");
	printf("\n----- iter: %d", sentinel + 1);
	printf("\n----- OBJ_VAL = %lf", currentLp);
	printf("\n----- Exectution time: %.4f", (end - start) / (double)CLOCKS_PER_SEC);

	return ret;
}
示例#30
0
void table_remove(obj_table *table, obj* key_obj){
    int key = hashFunc(key_obj);
    raw_table_remove(table, key);
}