示例#1
0
HashObjectPtr wordSearch()
{
	char delims[] =  ",.;:\"&!? -_\n\t\r@()#$%^*+={}[]|<>/~`";
	char * input = (char *)malloc(sizeof(char)*MAX_INPUT_LENGTH);
	char * token;
	HashObjectPtr obj;

	printf("Please enter a word\n\n");
	fgets(input, MAX_INPUT_LENGTH, stdin);

	if (strtok(input, delims) != NULL)
	{
		token = strtok(input, delims);
	}
	if ((obj = HashSearch(table, token)) != NULL)
	{
		printf("%s %d\n", (char*)obj->obj, obj->frequency);
		return obj;
	}
	else
	{
		printf("%s\n", "The word was not found\n\n");
		return NULL;
	}
	free(input);
}
示例#2
0
/*
 * ============================================================================
 * Object callback mechanism - 'dehashes' and invokes the appropriate jobs
 * ============================================================================
 */
char *obj_get_ops(int inum) {
    extern HTablePtr csplot_hash[HASHMODULUS];
    obj_generic *obj;
    char *ops;

    if (NULL == (obj = (obj_generic *)HashSearch(csplot_hash, inum))) {
        verror(ERR_FATAL, "obj_get_ops",
               "Unknown canvas item number! (%d)\n", inum);
        return NULL;
    }

    if (!obj->call.func)
        return NULL;

    ops = obj->call.func(OBJ_LIST_OPERATIONS, NULL, obj, obj->call.data);

    /*
        printf("\n==== Operations allowed ====\n");
        while (l = strlen(ops)) {
    	printf("%d. %s\n", op++, ops);
    	ops += l+1;
        }
        printf("\n");
    */
    return ops;
}
示例#3
0
LBCommData* LBCommTable::HashInsertUnique(const LBCommData &data)
{
    LBCommData* item = HashSearch(data);
    if (!item) {
        item = HashInsert(data);
    }
    return item;
}
int hash::HashDelete(int k)
{
	int j=HashSearch(k);
	if(T[j]!=NIL && T[j]!=DELETED)
	{
		T[j]=DELETED;
		return j;
	}
	else
		return NIL;
}
示例#5
0
void obj_invoke_op(int inum, int op) {
    extern HTablePtr csplot_hash[HASHMODULUS];
    obj_generic *obj;

    if (NULL == (obj = (obj_generic *)HashSearch(csplot_hash, inum))) {
        verror(ERR_FATAL, "obj_invoke_op",
               "Unknown canvas item number! (%d)\n", inum);
        return;
    }

    if (obj->call.func)
        obj->call.func(OBJ_INVOKE_OPERATION, &op, obj, obj->call.data);
}
示例#6
0
char *obj_get_brief(int inum) {
    extern HTablePtr csplot_hash[HASHMODULUS];
    obj_generic *obj;

    if (NULL == (obj = (obj_generic *)HashSearch(csplot_hash, inum))) {
        verror(ERR_FATAL, "obj_get_brief",
               "Unknown canvas item number! (%d)\n", inum);
        return NULL;
    }

    if (obj->call.func)
        return obj->call.func(OBJ_GET_BRIEF, NULL, obj, obj->call.data);
    else
        return NULL;
}
示例#7
0
END_TEST

START_TEST(HashTableInsertTest) {
    struct HashTable _Table = {NULL, 0, 0};
    int _Data = 5;

    _Table.Table = calloc(sizeof(struct HashNode*), 20);
    //Should not add a element add not crash the test.
    HashInsert(&_Table, "Hello", &_Data);
    _Table.TblSize = 20;
    HashInsert(&_Table, "Hello", &_Data);
    ck_assert_ptr_eq(HashSearch(&_Table, "Hello"), &_Data);
    HashInsert(&_Table, NULL, &_Data);
    ck_assert_int_eq(_Table.Size, 1);
}
示例#8
0
struct Population* PopulationLoad(lua_State* _State, int _Index) {
    int i;
    const char* _Key = NULL;
    const char* _Name = NULL;
    struct Constraint** _Ages = NULL;
    struct LinkedList _List = {0, NULL, NULL};
    struct Population* _Pop = NULL;
    struct FoodBase** _Eats = NULL;
    struct LnkLst_Node* _Itr = NULL;
    int _Young = 0;
    int _Old = 0;
    int _Death = 0;
    int _Nutrition = 0;
    int _Meat = 0;
    int _Milk = 0;
    int _IsShearable = 0;
    int _FMRatio = 0;
    int _SpaceReq = 0;
    const struct GoodBase* _SkinGood = NULL;
    const struct GoodBase* _HairGood = NULL;
    double _SkinPounds = 0.0;
    double _HairPounds = 0.0;
    double _MaleRatio = 0;
    double _ReproduceMin = 0.0f;
    double _ReproduceMax = 0.0f;
    int _Return = -2;
    int _Top = lua_gettop(_State);

    lua_getmetatable(_State, _Index);
    lua_pushnil(_State);
    while(lua_next(_State, -2) != 0) {
        if(lua_isstring(_State, -2))
            _Key = lua_tostring(_State, -2);
        else
            continue;
        if (!strcmp("Nutrition", _Key))
            _Return = LuaGetInteger(_State, -1, &_Nutrition);
        else if(!strcmp("Name", _Key))
            _Return = LuaGetString(_State, -1, &_Name);
        else if(!strcmp("MaleRatio", _Key))
            _Return = LuaGetNumber(_State, -1, &_MaleRatio);
        else if(!strcmp("Meat", _Key))
            _Return = LuaGetInteger(_State, -1, &_Meat);
        else if(!strcmp("Milk", _Key))
            _Return = LuaGetInteger(_State, -1, &_Milk);
        else if(!strcmp("MatureAge", _Key)) {
            _Return = LuaIntPair(_State, -1, &_Young, &_Old);
            _Young = YearToDays(_Young);
            _Old = YearToDays(_Old);
        } else if(!strcmp("DeathAge", _Key)) {
            _Return = LuaGetInteger(_State, -1, &_Death);
            _Death = YearToDays(_Death);
        } else if (!strcmp("SpaceReq", _Key)) {
            _Return = LuaGetInteger(_State, -1, &_SpaceReq);
        } else if(!strcmp("FMRatio", _Key)) {
            _Return = LuaGetInteger(_State, -1, &_FMRatio);
        } else if(!strcmp("Reproduce", _Key)) {
            if(lua_type(_State, -1) != LUA_TTABLE)
                _Return = 0;
            lua_rawgeti(_State, -1, 1);
            if((_Return = LuaGetNumber(_State, -1, &_ReproduceMin)) <= 0)
                goto loop_end;
            lua_rawgeti(_State, -2, 2);
            if((_Return = LuaGetNumber(_State, -1, &_ReproduceMax)) <= 0)
                goto loop_end;
            lua_pop(_State, 2);

        } else if(!strcmp("Eats", _Key)) {
            _Return = 1;
            lua_pushnil(_State);
            while(lua_next(_State, -2) != 0) {
                void* _Data = NULL;

                if(lua_isstring(_State, -1) == 0)
                    goto EatsEnd;
                if((_Data = HashSearch(&g_Goods, lua_tostring(_State, -1))) == NULL) {
                    Log(ELOG_WARNING, "Food %s could not be found.", lua_tostring(_State, -1));
                    goto EatsEnd;
                }
                LnkLstPushBack(&_List, _Data);
EatsEnd:
                lua_pop(_State, 1);
            }
        } else if(!strcmp("Skin", _Key)) {
            if(lua_type(_State, -1) != LUA_TTABLE) {
                if(lua_isnil(_State, -1) == 0)
                    Log(ELOG_INFO, "Population skin variable is not a table.");
                goto loop_end;
            }
            lua_pushstring(_State, "Type");
            lua_rawget(_State, -2);
            if(lua_type(_State, -1) != LUA_TSTRING) {
                Log(ELOG_INFO, "Population skin.Type variable is not a table.");
                goto loop_end;
            }
            if((_SkinGood = HashSearch(&g_Goods, lua_tostring(_State, -1))) == NULL) {
                Log(ELOG_INFO, "Population skin.Type: %s is not a good.", lua_tostring(_State, -1));
                lua_pop(_State, 2);
                continue;
            }
            lua_pop(_State, 1);
            lua_pushstring(_State, "Pounds");
            lua_rawget(_State, -2);
            if(lua_type(_State, LUA_TNUMBER) == 0) {
                Log(ELOG_INFO, "Population skin.Pounds variable is not a number.");
                lua_pop(_State, 2);
                continue;;
            }
            _SkinPounds = lua_tonumber(_State, -1);
            lua_pop(_State, 1);
        } else if(!strcmp("Hair", _Key)) {
            if(lua_type(_State, -1) != LUA_TTABLE) {
                if(lua_isnil(_State, -1) == 0)
                    Log(ELOG_INFO, "Population hair variable is not a table.");
                goto loop_end;
            }
            lua_pushstring(_State, "Type");
            lua_rawget(_State, -2);
            if(lua_type(_State, -1) != LUA_TSTRING) {
                Log(ELOG_INFO, "Population hair.Type variable is not a table.");
                goto loop_end;
            }
            if((_HairGood = HashSearch(&g_Goods, lua_tostring(_State, -1))) == NULL) {
                Log(ELOG_INFO, "Population hair.Type: %s is not a good.", lua_tostring(_State, -1));
                goto loop_end;
            }
            lua_pop(_State, 1);
            lua_pushstring(_State, "Pounds");
            lua_rawget(_State, -2);
            if(lua_type(_State, LUA_TNUMBER) == 0) {
                Log(ELOG_INFO, "Population hair.Pounds variable is not a number.");
                lua_pop(_State, 2);
                continue;
            }
            _HairPounds = lua_tonumber(_State, -1);
            lua_pop(_State, 1);
            lua_pushstring(_State, "IsShearable");
            lua_rawget(_State, -2);
            if(lua_type(_State, -1) != LUA_TBOOLEAN) {
                Log(ELOG_INFO, "Population hair.IsShearable variable is not a number.");
                lua_pop(_State, 2);
                continue;
            }
            _IsShearable = lua_toboolean(_State, -1);
            lua_pop(_State, 1);
        } else {
            Log(ELOG_WARNING, "%s is not a field of a Population.", _Key);
            goto fail;
        }
        if(!(_Return > 0)) {
            Log(ELOG_WARNING, "%s contains invalid data for a Population.", _Key);
            goto fail;
        }
loop_end:
        lua_pop(_State, 1);
    }
    if(_Young > _Old || _Old > _Death || _Death < 0) {
        Log(ELOG_WARNING, "%s age limits are invalid.", _Name);
        goto fail;
    }
    _Ages = CreateConstrntBnds(4, 0, _Young, _Old, _Death);
    _Pop = CreatePopulation(_Name, _Nutrition, _Meat, _Milk, _Ages, _MaleRatio, _FMRatio, _ReproduceMin, _ReproduceMax, _SpaceReq);
    _Eats = calloc(_List.Size, sizeof(struct FoodBase*));
    _Itr = _List.Front;
    i = 0;
    while(_Itr != NULL) {
        _Eats[i] =_Itr->Data;
        InsertionSort(_Eats, i + 1, GoodBaseCmp, sizeof(*_Eats));
        _Itr = _Itr->Next;
        ++i;
    }
    _Pop->Skin.Skin = _SkinGood;
    _Pop->Skin.Pounds = _SkinPounds;
    _Pop->Hair.Hair = _HairGood;
    _Pop->Hair.Pounds = _HairPounds;
    _Pop->Hair.Shearable = _IsShearable;
    _Pop->Outputs = malloc(sizeof(struct Good*));
    _Pop->Outputs[0] = NULL;
    _Pop->Eats = _Eats;
    _Pop->EatsSize = _List.Size;
    if(_Pop->EatsSize == 0)
        Log(ELOG_WARNING, "Population %s has zero food types to consume.", _Name);
    return _Pop;
fail:
    lua_settop(_State, _Top);
    return NULL;
}
示例#9
0
/*++
        Procedure generates the C- code from the FSM data structures:
            * Fsm procedure: the conditon and executive switches
            * [state][input] table
            * the conditon execution table
            * Input code enumeration
            * State enumeration
        The generated code is printed to marked places in the given
        c- source file. Another program has read the file to a link list
        and filtered away the previous FSM state machine.
        The input data has been got in global variables.
--*/
VOID FsmCodeGeneration( 
        FILE *      fd,         // the handle of the c- file
        PLINK_FILE  pFileBase,  // file read to a linked list
        PFSM_TRANSIT pBase,     // linked fsm state transitions
        PSZ         pszName     // the default body of all names
        )
{
    USHORT      i, j;
    PLINK_FILE  pFile;
    PFSM_ACTION pActions;
    PFSM_TRANSIT pCur;
    PSZ         pszDefault = "DefaultAction";
    PFSM_STR_REDEF pDefAction;
    PSZ         pszSpaces, pszPrevLine = "";
    BOOL        boolNoGoto;
    
    // 
    pFile = pFileBase;
    do
    {
        // print always the c- code line
        fprintf( fd, "%s", pFile->pszLine );

        // 
        switch (pFile->usState)
        {
        case FSM_ENUMERATIONS:
            // print the input enumerations (this should be a .h file!)
            // The input definitions must start from 0!
            fprintf(  fd, "enum e%sInput {\n", pszName );
            for (i = 0; i < cInputs - 1; i++)
            {
                fprintf(  fd, "    %s = %u,\n", ppInputDefs[i]->pszToken, i );
            }
            fprintf(  fd, "    %s = %u\n};\n", ppInputDefs[i]->pszToken, i );

            // and the states, they be be used elsewhere!
            fprintf(  fd, "enum e%sState {\n", pszName );
            for (i = 0; i < cStates - 1; i++)
            {
                fprintf(  fd, "    %s = %u,\n", ppStateDefs[i]->pszToken, i );
            }
            fprintf(  fd, "    %s = %u\n};\n", ppStateDefs[i]->pszToken, i );
            break;
        case FSM_GLOBAL_ARRAYS:
            // print [state][input] jump table
            fprintf( 
                fd, 
                "// Flag for the predicate switch\n#define PC     0x8000\n");
//            if (cStates < 256 && cInputs < 256)
//            {
//                fprintf( 
//                    fd,
//                    "UCHAR a%sStateInput[%u][%u] = {\n",
//                    pszName, cStates, cInputs);
//            }
//            else
//            {
                fprintf( 
                    fd,
                    "USHORT a%sStateInput[%u][%u] = {\n",
                    pszName, cStates, cInputs);
//            }
            for (i = 0;; i++)
            {
                fprintf( fd, "{" );
                for (j = 0; j < cInputs - 1; j++)
                {
                    if (j % 10 == 0 && j)
                        fprintf( fd, "\n ");
                    if (ppusStateInputs[i][j] & 0x8000)
                        fprintf( fd, "%3u|PC,", ppusStateInputs[i][j] & 0x7fff);
                    else
                        fprintf( fd, "%6u,", ppusStateInputs[i][j] );
                }
                if (j % 10 == 0)
                    fprintf( fd, "\n ");
                if (ppusStateInputs[i][j] & 0x8000)
                   fprintf( fd, "PC|%3u", ppusStateInputs[i][j] & 0x7fff);
                else
                   fprintf( fd, "%6u", ppusStateInputs[i][j] );
                if (i == cStates - 1)
                {
                    fprintf( fd, "}};\n" );
                    break;
                }
                else
                    fprintf( fd, "},\n");
            }
            // and print at next the condition jump table
//            if (cCondJumpTbl < 256)
//            {
//                fprintf( 
//                       fd, "UCHAR a%sCondJump[%u] = {\n", 
//                       pszName, cCondJumpTbl);
//            }
//            else
//            {
                fprintf( 
                    fd, "USHORT a%sCondJump[%u] = {\n", 
                    pszName, cCondJumpTbl);
//            }
            for (i = 0; i < cCondJumpTbl; i++)
            {
                if (i % 12 == 0 && i)
                    fprintf( fd, "\n");
                fprintf( fd, "%5u,", pusCondJumpTbl[i]);

                if (i == cCondJumpTbl - 2)
                {
                    i++;
                   if (i % 12 == 0 && i)
                        fprintf( fd, "\n");
                    fprintf( fd, "%5u};\n", pusCondJumpTbl[i]);
                    break;
                }
            }
            break;
        case FSM_CONDITION_SWITCH:
            // *** Print the condition switch *****
            // The produced code should look like this:
            //
            //  usAction = aMyFsmInputState[usState][usInput];
            //  if (usAction & 0x8000)
            //  {
            //      usActionIndex = usAction & 0x7fff;
            //      usAction = aMyFsmCondJump[usActionIndex++];
            //      switch (usAction)
            //      {
            //      case 1:
            //          if (<first cond1>)
            //              ;
            //          else if (<first cond2>)
            //              usActionIndex += 1;
            //          else if (<first cond3>)
            //              usActionIndex += 2;
            //          else
            //              usActionIndex = 0;
            //          break;
            //          ...
            //      case n:
            //          ....
            //          break;
            //      }
            //      usAction = aMyFsmCondJump[usActionIndex];
            //  }
            pszSpaces = GetSpacePadding( pszPrevLine );
            
            fprintf( 
                fd, "%susAction = a%sStateInput[usState][usInput];\n", 
                pszSpaces, pszName );
            fprintf( fd, "%sif (usAction & 0x8000)\n", pszSpaces );
            fprintf( fd, "%s{\n", pszSpaces );
            fprintf( 
                fd, "%s    usActionIndex = usAction & 0x7fff;\n",pszSpaces);
            fprintf( 
                fd, "%s    usAction = a%sCondJump[usActionIndex++];\n",
                pszSpaces, pszName);
            fprintf( fd, "%s    switch (usAction) {\n", pszSpaces );
            pCur = pBase;
            do
            {
                if (pCur->pInputActions->pAlternateConditions == NULL
                    && pCur->pInputActions->dt.ppCondActions[0]->pCond
                        != NULL)
                        
                {
                    fprintf( 
                        fd, "%s    case %u:\n",
                        pszSpaces, pCur->pInputActions->usCase );
                    fprintf( 
                        fd, "%s        if (%s)\n",
                        pszSpaces, 
                        pCur->pInputActions->dt.ppCondActions[0]->
                            pCond->pszC_Code);
                    fprintf( fd, "%s            ;\n", pszSpaces );
                    for (
                        i = 1;  
                        i < pCur->pInputActions->dt.cCondActions; 
                        i++)
                    {
                        fprintf( 
                            fd, "%s        else if (%s)\n",
                            pszSpaces, 
                            pCur->pInputActions->dt.ppCondActions[i]->
                                pCond->pszC_Code);
                        fprintf( 
                            fd, 
                            "%s            usActionIndex += %u;\n",
                            pszSpaces, i );
                    }
                    fprintf( fd, "%s        else\n", pszSpaces );
                    fprintf( 
                        fd, "%s            usActionIndex = 0;\n",
                        pszSpaces);
                    fprintf( fd, "%s        break;\n", pszSpaces );
                }
                pCur = pCur->pNext;
            } while (pCur != pBase);
            fprintf( fd, "%s    };\n", pszSpaces );
            fprintf( 
                fd, "%s    usAction = a%sCondJump[usActionIndex];\n",
                pszSpaces, pszName );
            fprintf( fd, "%s}\n", pszSpaces );
            break;
        case FSM_ACTION_SWITCH:
            // **** Print the action executive switch ****
            //      The produced code should look like this:
            //  switch (usAction)
            //  {
            //  case 1:
            //          <action primitive 1>;
            //      label_1_1:
            //          <action primitive 2>;
            //  case m:
            //      label_1_2:
            //          <action primitive 3>;
            //          break;
            //  ....
            //  case n:
            //          <action primitive n>;
            //    label_n_1:
            //          <action primitive 2>;
            //          goto label_1_2;
            //  case n+1:
            //          ...
            //  };
            pszSpaces = GetSpacePadding( pszPrevLine );
            fprintf( fd, "%sswitch (usAction) {\n", pszSpaces );

            // header for null commands
            fprintf( fd, "%scase 0:\n", pszSpaces );
            pDefAction = HashSearch( hDefines, &pszDefault );
	    if (pDefAction == NULL)
	    {
	        PrintErrMsg( 0, FSM_ERROR_NO_DEFAULT, NULL);
	        return;
	    }
            fprintf( fd, "%s        %s;\n", pszSpaces, pDefAction->pszReplace );
            fprintf( fd, "%s        break;\n", pszSpaces );
            pCur = pBase;
            do
            {
                for (i = 0;  i < pCur->pInputActions->dt.cCondActions; i++)
                {
                    pActions = 
                        pCur->pInputActions->dt.ppCondActions[i]->pAction;
                    if (pActions->dt.ppActPrim[0]->boolCodeGenerated)
			    // START THE NEXT FOR LOOP!!!!
                        continue;
                       
                    // else // make the case
                    pActions->dt.ppActPrim[0]->boolCodeGenerated = TRUE; 
                    fprintf(
                        fd, "%scase %u:\n",
                        pszSpaces,
                        pActions->dt.ppActPrim[0]->usCase);
                    if (pActions->dt.ppActPrim[0]->usLineInCase)
                        fprintf(
                            fd, "%s    label_%u_%u:\n",
                            pszSpaces,
                            pActions->dt.ppActPrim[0]->usCaseForLabel,
                            pActions->dt.ppActPrim[0]->usLineInCase);
                    fprintf(
                        fd, "%s        %s\n",
                        pszSpaces,
                        pActions->dt.ppActPrim[0]->pActCode->pszC_Code);
                    boolNoGoto = TRUE;
                    for (j = 1; j < pActions->dt.cActPrim; j++)
                    {
                        if (pActions->dt.ppActPrim[j]->boolCodeGenerated)
                        {
                            // jump to existing code path and exit the loop
                            fprintf(
                                fd, "%s        goto label_%u_%u;\n",
                                pszSpaces, 
                                pActions->dt.ppActPrim[j]->usCaseForLabel,
                                pActions->dt.ppActPrim[j]->usLineInCase);
                            boolNoGoto = FALSE;
                            break;
                        }
                        // else // print 
                        pActions->dt.ppActPrim[j]->boolCodeGenerated 
                            = TRUE; 
                        if (pActions->dt.ppActPrim[j]->usCase)
                            fprintf(
                                fd, "%scase %u:\n",
                                pszSpaces, 
                                pActions->dt.ppActPrim[j]->usCase );
                        if (pActions->dt.ppActPrim[j]->usLineInCase)
                            fprintf(
                                fd, "%s    label_%u_%u:\n",
                                pszSpaces,
                                pActions->dt.ppActPrim[j]->usCaseForLabel,
                                pActions->dt.ppActPrim[j]->usLineInCase);
                        fprintf(
                            fd, "%s        %s\n",
                            pszSpaces, 
                            pActions->dt.ppActPrim[j]->pActCode->pszC_Code);
                    }
                    // terminate the case with break, if we didn'y have
                    // any gotos
                    if (boolNoGoto)
                        fprintf( fd, "%s        break;\n", pszSpaces );
                }
                pCur = pCur->pNext;
            } while (pCur != pBase);
            fprintf( fd, "%s};\n", pszSpaces );
            break;
        default:
            // save the previous proper C- line the get the current
            // column in the procedure
            if (*(pFile->pszLine) && *(pFile->pszLine) != '\n')
                pszPrevLine = pFile->pszLine;
            break;
        }
        pFile = pFile->pNext;
    } while (pFile != pFileBase );
}
示例#10
0
GainType LinKernighan()
{
    Node *t1, *t2, *SUCt1;
    GainType Gain, G0, Cost;
    int X2, i, it = 0;
    Candidate *Nt1;
    Segment *S;
    SSegment *SS;
    double EntryTime = GetTime();

    Reversed = 0;
    S = FirstSegment;
    i = 0;
    do {
        S->Size = 0;
        S->Rank = ++i;
        S->Reversed = 0;
        S->First = S->Last = 0;
    }
    while ((S = S->Suc) != FirstSegment);
    SS = FirstSSegment;
    i = 0;
    do {
        SS->Size = 0;
        SS->Rank = ++i;
        SS->Reversed = 0;
        SS->First = SS->Last = 0;
    }
    while ((SS = SS->Suc) != FirstSSegment);

    FirstActive = LastActive = 0;
    Swaps = 0;

    /* Compute the cost of the initial tour, Cost.
       Compute the corresponding hash value, Hash.
       Initialize the segment list.
       Make all nodes "active" (so that they can be used as t1). */
    Cost = 0;
    Hash = 0;
    i = 0;
    t1 = FirstNode;
    do {
        t2 = t1->OldSuc = t1->Suc;
        t1->OldPred = t1->Pred;
        t1->Rank = ++i;
        Cost += (t1->SucCost = t2->PredCost = C(t1, t2)) - t1->Pi - t2->Pi;
        Hash ^= Rand[t1->Id] * Rand[t2->Id];
        t1->Cost = INT_MAX;
        for (Nt1 = t1->CandidateSet; (t2 = Nt1->To); Nt1++)
            if (t2 != t1->Pred && t2 != t1->Suc && Nt1->Cost < t1->Cost)
                t1->Cost = Nt1->Cost;
        t1->Parent = S;
        S->Size++;
        if (S->Size == 1)
            S->First = t1;
        S->Last = t1;
        if (SS->Size == 0)
            SS->First = S;
        S->Parent = SS;
        SS->Last = S;
        if (S->Size == GroupSize) {
            S = S->Suc;
            SS->Size++;
            if (SS->Size == SGroupSize)
                SS = SS->Suc;
        }
        t1->OldPredExcluded = t1->OldSucExcluded = 0;
        t1->Next = 0;
        if (KickType == 0 || Kicks == 0 ||
            !InBestTour(t1, t1->Pred) || !InBestTour(t1, t1->Suc))
            Activate(t1);
    }
    while ((t1 = t1->Suc) != FirstNode);
    if (S->Size < GroupSize)
        SS->Size++;
    Cost /= Precision;
    if (TraceLevel >= 3 || (TraceLevel == 2 && Cost < BetterCost)) {
        printff("Cost = " GainFormat, Cost);
        if (Optimum != MINUS_INFINITY && Optimum != 0)
            printff(", Gap = %0.4f%%", 100.0 * (Cost - Optimum) / Optimum);
        printff(", Time = %0.1f sec. %s\n", fabs(GetTime() - EntryTime),
                Cost < Optimum ? "<" : Cost == Optimum ? "=" : "");
    }
    PredSucCostAvailable = 1;

    /* Loop as long as improvements are found */
    do {
        /* Choose t1 as the first "active" node */
        while ((t1 = RemoveFirstActive())) {
            /* t1 is now "passive" */
            SUCt1 = SUC(t1);
            if ((TraceLevel >= 3 || (TraceLevel == 2 && Trial == 1)) &&
                ++it % (Dimension >= 100000 ? 10000 :
                        Dimension >= 10000 ? 1000 : 100) == 0)
                printff("#%d: Time = %0.1f sec.\n",
                        it, fabs(GetTime() - EntryTime));
            /* Choose t2 as one of t1's two neighbors on the tour */
            for (X2 = 1; X2 <= 2; X2++) {
                t2 = X2 == 1 ? PRED(t1) : SUCt1;
                if (FixedOrCommon(t1, t2) ||
                    (RestrictedSearch && Near(t1, t2) &&
                     (Trial == 1 ||
                      (Trial > BackboneTrials &&
                       (KickType == 0 || Kicks == 0)))))
                    continue;
                G0 = C(t1, t2);
                /* Try to find a tour-improving chain of moves */
                do
                    t2 = Swaps == 0 ? BestMove(t1, t2, &G0, &Gain) :
                        BestSubsequentMove(t1, t2, &G0, &Gain);
                while (t2);
                if (Gain > 0) {
                    /* An improvement has been found */
                    assert(Gain % Precision == 0);
                    Cost -= Gain / Precision;
                    if (TraceLevel >= 3 ||
                        (TraceLevel == 2 && Cost < BetterCost)) {
                        printff("Cost = " GainFormat, Cost);
                        if (Optimum != MINUS_INFINITY && Optimum != 0)
                            printff(", Gap = %0.4f%%",
                                    100.0 * (Cost - Optimum) / Optimum);
                        printff(", Time = %0.1f sec. %s\n",
                                fabs(GetTime() - EntryTime),
                                Cost < Optimum ? "<" : Cost ==
                                Optimum ? "=" : "");
                    }
                    StoreTour();
                    if (HashSearch(HTable, Hash, Cost))
                        goto End_LinKernighan;
                    /* Make t1 "active" again */
                    Activate(t1);
                    break;
                }
                RestoreTour();
            }
        }
        if (HashSearch(HTable, Hash, Cost))
            goto End_LinKernighan;
        HashInsert(HTable, Hash, Cost);
        /* Try to find improvements using non-sequential 4/5-opt moves */
        Gain = 0;
        if (Gain23Used && (Gain = Gain23()) > 0) {
            /* An improvement has been found */
            assert(Gain % Precision == 0);
            Cost -= Gain / Precision;
            StoreTour();
            if (TraceLevel >= 3 || (TraceLevel == 2 && Cost < BetterCost)) {
                printff("Cost = " GainFormat, Cost);
                if (Optimum != MINUS_INFINITY && Optimum != 0)
                    printff(", Gap = %0.4f%%",
                            100.0 * (Cost - Optimum) / Optimum);
                printff(", Time = %0.1f sec. + %s\n",
                        fabs(GetTime() - EntryTime),
                        Cost < Optimum ? "<" : Cost == Optimum ? "=" : "");
            }
            if (HashSearch(HTable, Hash, Cost))
                goto End_LinKernighan;
        }
    }
    while (Gain > 0);

  End_LinKernighan:
    PredSucCostAvailable = 0;
    NormalizeNodeList();
    NormalizeSegmentList();
    return Cost;
}
示例#11
0
/* Simple version of #define and #undef processor. */
int main() {
  char word[kMaxWord];
  char *name;
  char defn[kMaxWord];
  LinkNode *p;
  int len = 0, i = 0;
  enum ParserState state = kStart;

  HashTable hash_table[kHashSize];
  HashInit(hash_table, kHashSize);

  memset(word, 0, kMaxWord);
  memset(defn, 0, kMaxWord);

  while (GetWord(word, kMaxWord) != EOF) {
    switch (state) {
      case kStart:
        if (strcmp(word, "#define") == 0) {
          state = kDefine;
        } else if (strcmp(word, "#undef") == 0) {
          state = kUnDef;
        } else if (!isalpha(word[0])) {
          printf("%s", word);
        } else if ((p = HashSearch(hash_table, word)) == NULL) {
          printf("%s", word);
        } else {
          ungets(p->defn);
        }
        break;
      case kDefine:
        if (isalpha(word[0])) {
          name = strdup(word);
          state = kName;
        } else {
          printf("Error: non-alpha name");
          exit(1);
        }
        break;
      case kName:
        if (word[0] == '\n') {
          printf("Error: incomplate define");
          exit(1);
        } else {
          strcpy(defn, word);
          len += strlen(word);
          state = kDefn;
        }
        break;
      case kDefn:
        if (word[0] != '\n' && len < kMaxWord) {
          strcat(defn, word);
          len += strlen(word);
        } else {
          HashInsert(hash_table, name, defn);
          state = kStart;
        }
        break;
      case kUnDef:
        if (isalpha(word[0])) {
          HashDelete(hash_table, name);
          state = kStart;
        } else {
          printf("Error: non-alpha name");
          exit(1);
        }
        break;
    }
  }
  return 0;
}