static bool searchRecur(Edge* e, int size, int currentPoint, int prevPoint, int* previousPoints, int nbPreviousPoints){
  bool returnRecur = false;

  // Pour chaque arête du tableau et tant qu'on a pas de retour à vrai
  for (int i=0; i<size && returnRecur == false; i++){
    // Si on trouve une arête du type (pointActuel, pointDifferentDuPrecedent)
    if (e[i]->start == currentPoint && e[i]->end != prevPoint){
      // On regarde si on a déjà traversé cette ville
      if (isInArray(e[i]->end, previousPoints, nbPreviousPoints))
        return true;
      
      // Sinon, on avance vers la prochaine ville
      previousPoints[nbPreviousPoints] = e[i]->end;
      nbPreviousPoints++;
      returnRecur = searchRecur(e, size, e[i]->end, e[i]->start, previousPoints,nbPreviousPoints);
      // On retire la ville des villes visitées
      nbPreviousPoints--;
    }
    // Si on trouve une arête du type (pointDifferentDuPrecedent, pointActuel)
    else if (e[i]->end == currentPoint && e[i]->start != prevPoint){
      if (isInArray(e[i]->start, previousPoints, nbPreviousPoints))
        return true;
      
      previousPoints[nbPreviousPoints] = e[i]->start;
      nbPreviousPoints++;
      returnRecur = searchRecur(e, size, e[i]->start,e[i]->end, previousPoints,nbPreviousPoints);
      nbPreviousPoints--;
    }
  }

  return returnRecur;
}
void raw_string::validateSpecialSymbols()
{
	// Looks that some symbols, should not present in expression
	char cSpecialSymbols[] = "$";

	for (int i = 0; cRawString[i]; i++)
	{
		if (isInArray(cRawString[i], cSpecialSymbols)) throw NotAllowedSybolError;
	};
}
Esempio n. 3
0
string getColorInput()
{
  string input;
  bool valid = false;
  do
  {
    cout << "Input the color of the car: ";
    cin >> input;
    if (!isInArray(input, NUM_COLORS, COLORS) || input != QUIT)
      cout << "Your input must be in the list of available colors." << endl;
    else
      valid = true;
  } while (!valid);

  return input;
}
/**********************************************************************
 * Assigns a subset of allRooms to usedRooms.
 * Rooms are not assigned if allRooms size is less than usedRooms size.
 *********************************************************************/
void chooseRooms( char* allRooms[], int ALL_ROOMS_SIZE, char* usedRooms[], int USED_ROOMS_SIZE ) {
	if ( ALL_ROOMS_SIZE < USED_ROOMS_SIZE ) {
		printf( "in chooseRooms: ALL_ROOMS_SIZE must be at least 7\n" );
		exit(1);
	}

	char *random_room = allRooms[randInRange(0, USED_ROOMS_SIZE - 1)];
	int count = 0;
	char *chosen_room = NULL;
	for ( count; count < USED_ROOMS_SIZE; ++count ) {
		while (isInArray(random_room, usedRooms, USED_ROOMS_SIZE - 1)) {
			 random_room = allRooms[randInRange(0, ALL_ROOMS_SIZE - 1)];
		}
		chosen_room = (char*)malloc( 100 * sizeof(char) );
		strcpy( chosen_room, random_room );
		usedRooms[count] = chosen_room;
	}

}
void raw_materials::doOperationGroup(char *pOperationGroup,const int *pOperationGroupLim, int &iProcDigits)
{
    char cCurOperation = '\0';
    for (int i = 0; i < iCountDigits-1; i++){
        cCurOperation = isInArray(opOperations[i].symbol, pOperationGroup, *(pOperationGroupLim), *(pOperationGroupLim + 1));
        if (cCurOperation) {
            fOperands[opOperations[i].left_op] = opOperations[i].doOperation(fOperands[opOperations[i].left_op],
                                                                             fOperands[opOperations[i].right_op]);
            opOperations[i].processed = 1;
            iProcDigits += 1;
            if (iProcDigits != iCountDigits-1)
            {
                int z = i + 1;
                // Check left operand index, which is not changed, if it is last operation
                while (opOperations[z].processed && (opOperations[z].right_op + 1 != iCountDigits)) z++;
                opOperations[z].left_op = opOperations[i].left_op;
            };
        }
    }
}
void raw_string::validateParentheses()
{
    // Check parentless and also check operation symbol before open parentheses
    // and digits before closed parentheses

    int iOpened = 0, iClosed = 0;
    char cSymbols[] = "*/+-", cDigits[] = "0123456789";
    char cBeforeOpen[] = "(,", cAfterOpen[]="(-", cAfterClose[] = ",)";
    for (int i=0; cRawString[i];i++ )
    {
        switch (cRawString[i])
        {
            case '(':
                iOpened += 1;
                if (i!=0 &&
					!(isInArray(cRawString[i-1],cBeforeOpen)) &&
					!(isChar(cRawString[i-1])) &&
					!(isInArray(cRawString[i-1],cSymbols))) throw PreAfterParentlessError;
				if (cRawString[i + 1] &&
					!(isChar(cRawString[i+1])) &&
					!(isInArray(cRawString[i + 1], cDigits)) &&
					!(isInArray(cRawString[i + 1], cAfterOpen))) throw PreAfterParentlessError;
                break;
            case ')':
                iClosed += 1;
                if (i!=0 && cRawString[i-1]!=')' &&
					!(isChar(cRawString[i - 1])) &&
					!(isInArray(cRawString[i-1],cDigits))) throw PreAfterParentlessError;
				if (cRawString[i + 1] &&
					!(isInArray(cRawString[i + 1], cAfterClose)) &&
					!(isInArray(cRawString[i + 1], cSymbols))) throw PreAfterParentlessError;
                if (iClosed>iOpened) throw ParentlessError;
                break;
            default:
                continue;

        }
    }

    if (iClosed != iOpened) throw ParentlessError;
}
Esempio n. 7
0
//test begin----------------------------
void testJson(char* buf,int n){
   int i,j;
   printf(">>testJson() ~000>>buf size:%d >>buf is:%s \n",n,buf);
   printf(">>testJson() ~000>>buf size:%d  \n",n);
   if(n<=0)
     return;
   char bufNew[n];
   for(i=0;i<n;i++){
     bufNew[i] = buf[i];
   } 
/*    //test begin lilei
   char ** str;
   char a[2] ="ab";
   int len;
   len = base64DecodeStringRemoveEndZero(a,str);
   printf(">>testJson() 111.2.1 a is:%s\n",a);
   printf(">>testJson() 111.2>>decode str is:%s >>len:%d \n",*str,len);
   return;
   //test end  */
   char packageName[SMALL_TEXT_BUFFER_SIZE];
   char className[SMALL_TEXT_BUFFER_SIZE];
   char title[SMALL_TEXT_BUFFER_SIZE];
   char byteMap[BYTEMAP_BUFFER_SIZE];
   char * jsonStr;
    
   cJSON *fmt = NULL,*JSONroot = NULL,*mJSONroot;
   JSONroot = cJSON_Parse(bufNew);
   int num = cJSON_GetArraySize(JSONroot);//check arrays 
   printf(">>testJson() 222>>json root size is:%d \n",num);
   
   fmt = cJSON_GetObjectItem(JSONroot,KEY_MESSAGE_TYPE);
   int msgType = fmt->valueint;
   printf(">>testJson() 33>>msgType is:%d \n",msgType);
    
   
   if(isInArray(msgType,jsonContainPackage,sizeof(jsonContainPackage)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_PACKAGE_NAME);
     bzero(packageName,SMALL_TEXT_BUFFER_SIZE);     //clear packageName
     snprintf(packageName,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     printf(">>testJson() 33>>packageName is:%s \n",packageName);
   }
   
   if(isInArray(msgType,jsonContainClass,sizeof(jsonContainClass)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_CLASS_NAME);
     bzero(className,SMALL_TEXT_BUFFER_SIZE);         //clear className
     snprintf(className,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     printf(">>testJson() 33>className is:%s>>className len is:%ld \n",className,strlen(className));
   }
   if(isInArray(msgType,jsonContainTitle,sizeof(jsonContainTitle)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_CLASS_TITLE);
     bzero(title,SMALL_TEXT_BUFFER_SIZE);             //clear title
     snprintf(title,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     int length  = strlen(title);
     int lenDec = -1;
     char * convert = base64_decode(title,length,&lenDec);
     int lenBase64 = strlen(convert);
     printf(">>testJson() 33>>base64 decode title is:%s >>title is:%s \n",convert,title); 
     int i;
     printf(">>testJson() 33>>base64 decode title length is:%d >>origin title length is:%d \n",lenBase64,length);
     for(i = 0;i<lenBase64;i++){
       printf(">>testJson() 33>titile convert[%d]:%d \n",i,convert[i]);
     }
   }
   
   if(isInArray(msgType,jsonContainBytemap,sizeof(jsonContainBytemap)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_BYTEMAP);
     bzero(byteMap,BYTEMAP_BUFFER_SIZE);               //clear byteMap
     snprintf(byteMap,BYTEMAP_BUFFER_SIZE,"%s",fmt->valuestring);
     //printf(">>testJson() 33>byteMap is:%s \n",byteMap);
     printf(">>testJson() 33>byteMap length is:%ld \n",strlen(byteMap));
     writePngFileBase64(byteMap,strlen(byteMap),className,strlen(className));//save image
     printf(">>testJson() 33>byteMap of %s save end>>time is:%ld \n",className,getNowMills());
   }
   if(isInArray(msgType,jsonContainAllAppInfo,sizeof(jsonContainAllAppInfo)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_ALL_APPS); //this fmt is array [...]
     //char allAppInfo[LONG_TEXT_BUFFER_SIZE];
     int arraySize = cJSON_GetArraySize(fmt);
     //snprintf(allAppInfo,LONG_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     printf(">>testJson() 33>all app size is:%d \n",arraySize);
     cJSON * jsonApp = fmt->child;
     int appNum = 0;
     while(jsonApp != NULL){
       int count = cJSON_GetArraySize(jsonApp);

       fmt = cJSON_GetObjectItem(jsonApp,KEY_PACKAGE_NAME); //this fmt is object
       bzero(packageName,SMALL_TEXT_BUFFER_SIZE);           //clear packageName
       snprintf(packageName,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
       
       fmt = cJSON_GetObjectItem(jsonApp,KEY_CLASS_NAME);       
       bzero(className,SMALL_TEXT_BUFFER_SIZE);             //clear className
       snprintf(className,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
       jsonApp = jsonApp->next;
       //printf(">>testJson() 33>>packageName:%s >>className:%s \n",packageName,className);
       //get one app
       appNum++;
       if(appNum >= 0){
         printf(">>testJson() 33>>packageName:%s >>className:%s \n",packageName,className);
         mJSONroot = cJSON_CreateObject();  //for send to android
         cJSON_AddItemToObject(mJSONroot,KEY_MESSAGE_TYPE,cJSON_CreateNumber(MESSAGE_LINUX_GETONEAPP));
         cJSON_AddItemToObject(mJSONroot,KEY_PACKAGE_NAME,cJSON_CreateString(packageName));
         cJSON_AddItemToObject(mJSONroot,KEY_CLASS_NAME,cJSON_CreateString(className)); 
         jsonStr = cJSON_Print(mJSONroot);
         cJSON_Delete(mJSONroot);
         printf(">>testJson() 33>>appNum == %d~~~~~~~~~~~~~~should send\n",appNum);
         sendMsgToAndroid(jsonStr); //if get all app should not do below
       }
     }
    // cJSON_Delete(JSONroot);
    // return;   //if get all app should not do below
   }
   //perse action
   mJSONroot = cJSON_CreateObject();  //for send to android
   switch(msgType){
     case MESSAGE_ANDROID_READY:
        cJSON_AddItemToObject(mJSONroot,KEY_MESSAGE_TYPE,cJSON_CreateNumber(MESSAGE_LINUX_GETALL));
        jsonStr = cJSON_Print(mJSONroot);  
        //printf(">>testJson() 444>>should send message is:%s >>length is:%ld \n",jsonStr,strlen(jsonStr));      
        sendMsgToAndroid(jsonStr);    
	break;
     
     default:
     ;   
   }
   //cJSON_Delete(fmt);
   cJSON_Delete(JSONroot);
   cJSON_Delete(mJSONroot);
}
Esempio n. 8
0
int main(int argc , char *argv[])
{
    char str[60];
    int pagesToGet[1024];
    int totalPagesRequested = 0;
    char *cacheSizeString = argv[1];
    int cacheSize = atoi(cacheSizeString);
    page *cache[cacheSize];
    int itemsInCache = 0;
    
    //Get a line from stdin
    while(fgets(str, 60, stdin) != NULL)
    {
        //If the line doesn't start with a number, go to next line
        if(!isdigit(str[0])) continue;
        else {
            int i = 0;
            char currentPage[10];
            
            //Get the number at the beginning of line and put into currentPage
            while(isdigit(str[i])) {
                currentPage[i] = str[i];
                i++;
            }
            
            //After the last digit of the page number we're getting, put a \0
            currentPage[i] = '\0';
            
            //Convert currentPage to an int and add that page number to pagesToGet
            int pageNum = atoi(currentPage);
            pagesToGet[totalPagesRequested] = pageNum;
            totalPagesRequested++;
        }
    }
    
    ///////////////////////////
    // IMPLEMENTATION OF LRU //
    ///////////////////////////
    
    int i;
    int pageFaultCount = 0;
    for(i = 0; i < totalPagesRequested; i++) {
        int positionInCache = isInArray(pagesToGet[i], cache, itemsInCache);
        
        //If the page already exists in cache, continue
        if(positionInCache != -1) {
            cache[positionInCache]->timeInCache = 0;
        }
        else {
            printf("Page fault for page %d\n", pagesToGet[i]);
            pageFaultCount++;
            
            //If there is still empty space in cache, insert page
            if(itemsInCache < cacheSize) {
                page *currentPage = (page *)malloc(sizeof(page));
                cache[itemsInCache] = currentPage;
                cache[itemsInCache]->pageNumber = pagesToGet[i];
                cache[itemsInCache]->timeInCache = 0;
                itemsInCache++;
            }
            
            //We're going to have to remove an old page
            else {
                int indexOfRemoval = findOldestPage(cache, itemsInCache);
                cache[indexOfRemoval]->pageNumber = pagesToGet[i];
                cache[indexOfRemoval]->timeInCache = 0;
            }
        }
        
        incrementTimes(cache, itemsInCache);
    }
    
    printf("Total of %d page requests, total of %d page faults\n", totalPagesRequested, pageFaultCount);
    cleanUp(cache, itemsInCache);
    
    return 0;
}
// RAW_MATERIALS
void raw_materials::getTokens(char *p, subexp *pSubExp, variable_scope &varScope )
{
    int iStartNum = -1, iEndNum = 0, iOperandsPos = 0, iOperationsPos = 0;
    char cSymbols[] = "*/+-", cDigits[] = "0123456789", cSpecialSymbols[] = ".$,";
    parser parParser;
	string_func stringFunc;
	statment_type statmentType = Equation;

    for (int i = 0; p[i]; i++) {

        // Parse digits block
        if (isDigit(p[i])) {
            fOperands[iOperandsPos] = parParser.parseDigit(p,i,true);
            iCountDigits++;
			iOperandsPos++;
        }
		// Parse digit with unary minus
        else if(i == 0 && p[i] == '-') {
            i++;
            fOperands[iOperandsPos] = parParser.parseDigit(p,i,true,true);
            iCountDigits++;
            iOperandsPos++;
        }
		// Parse sub expression
		else if (p[i] == '$') {
			fOperands[iOperandsPos] = pSubExp[parParser.parseSubExp(p, i, pSubExp, varScope, true)].result;
			iCountDigits++;
			iOperandsPos++;
		}
        // Parse symbols block
        else if (isInArray(p[i], cSymbols)) {

			// Validate that no dublicated symbols
			if (i > 0 && isInArray(p[i - 1], cSymbols)) throw SymbolDuplication;
            opOperations[iOperationsPos].symbol = p[i];
            opOperations[iOperationsPos].left_op = iOperationsPos;
            opOperations[iOperationsPos].right_op = iOperationsPos + 1;
            iOperationsPos++;
            iCountSymbols++;
        }
        // Parse build in function
		else if (isChar(p[i]) && isFunc(p,i)) {
			fOperands[iOperandsPos] = pSubExp[parParser.parseBuildInFunc(p, i, pSubExp, varScope, true)].result;
			iCountDigits++;
			iOperandsPos++;
		}
		// Parse variable 
		else if (isChar(p[i]))
		{
			// !Here we become aware, whether it variable set or variable use
			int iCurVarIndex = parParser.parseVariable(p, i, varScope);
			if (iOperandsPos == 0 && p[i] && p[i] == '=' && stringFunc.isSameStr(p, pSubExp[0].exp))
			{
				i++;
				statmentType = Setter;
				varScope.vScope[iCurVarIndex].setValue(pSubExp[parParser.parseSubExp(p, i, pSubExp, varScope, true)].result);
			}
			else if (varScope.vScope[iCurVarIndex].isInit())
			{
				// As after parse our "i" is higher than it previous was on 1.
				i--;
				fOperands[iOperandsPos] = varScope.vScope[iCurVarIndex].getValue();
				iCountDigits++;
				iOperandsPos++;
			}
			else
			{
				throw VariableInitError;
			}
				
		}
        else {
			throw SyntaxError;
        }
    }
    if (iCountDigits - iCountSymbols != 1 && statmentType == Equation) throw SyntaxError;
}