Exemplo n.º 1
0
StringValueList* groupSymbols(char * input, char *alphabet)
{
	if(input == NULL || alphabet == NULL){
		return NULL;
	}

	char *inputCopy = NULL;
	StringValueList* auxExpandPrefix = NULL;
	StringValueList* symbolsGrouped = malloc(sizeof(StringValueList));
	initStringValueList(symbolsGrouped);
	int* symbolCount = NULL;
	char *bestCombination = NULL;
	double bestEvaluation = 0.0;
	double evaluation = 0.0;
	int inputLength = 0;

	
	inputLength = strlen(input);
	inputCopy = malloc((inputLength + 1) * sizeof(char));
	inputCopy = strncpy(inputCopy, input, inputLength);
	inputCopy[inputLength] = '\0';


	do{
		/* Contamos cada simbolo del alfabeto en input. */
		symbolCount = charCount(inputCopy, alphabet);
		bestEvaluation = 0;
		/* Buscamos el simbolo que tiene una evaluacion mayor para seguir buscando un patron a partir de el. */
		for(int i = 0; i < strlen(alphabet); i++){
			evaluation = evaluate(symbolCount[i], strlen(input), 1);
			if (evaluation > bestEvaluation){
				free(bestCombination);
				bestCombination = createString(alphabet[i]);
				bestEvaluation = evaluation;
			} 
		}
		free(symbolCount);

		/* A partir del simbolo mas puntos, se empiezan a buscar subcadenas a partir de el en input */
		//printf("Mejor simbolo encontrado: %s -> %.3f\n", bestCombination, bestEvaluation);
		auxExpandPrefix = malloc(sizeof(StringValueList));
		initStringValueList(auxExpandPrefix);
		expandBestCombination(inputCopy, alphabet, bestCombination, bestEvaluation, auxExpandPrefix);
		/* Insertamos el elemento de mas valor en la lista de simbolos agrupados. */
		int posMaxValue = getPosMaxStringValue(auxExpandPrefix);
		addStringValue(symbolsGrouped, strdup(auxExpandPrefix->string[posMaxValue]), auxExpandPrefix->value[posMaxValue]);
		freeStringValueList(auxExpandPrefix);
		/* Eliminamos de la copia de input las repeticiones de la agrupacion encontrada, sustituyendola por BLANK_CHAR */
		//printf("%s\n", inputCopy);
		deleteSubstring(inputCopy, symbolsGrouped->string[symbolsGrouped->length - 1]);
		
		inputLength = countValidCharacters(inputCopy);
		//printf("%s\n", inputCopy);
	/* Repetimos todo el proceso hasta que se haya agrupado todo el input */
	} while(inputLength != 0);

	free(inputCopy);
	free(bestCombination);
	return symbolsGrouped;
}
Exemplo n.º 2
0
int HashTable::hash(std::string pKey){

	std::string binary = BytesHandler::string2bin(pKey, pKey.length());
	std::string binLong = bin2long2bin(binary);

	int oneCount = charCount(binary, '1');
	int zeroCount = charCount(binary, '0');

	std::string oneBin = BytesHandler::unum2bin(oneCount, 4);
	std::string zeroBin = BytesHandler::unum2bin(zeroCount, 4);

	std::string out = strXor(binLong.substr(binLong.length()-17, 16), binLong.substr(16, 16));
	out += zeroBin.substr(zeroBin.length()-9, 8);
	out += oneBin.substr(oneBin.length()-9, 8);

	return (int)BytesHandler::to_ulong(out);
}
Exemplo n.º 3
0
std::string CRtfWord::toString() const {
    std::string result;
    result.reserve(charCount());
    for (CharIteratorConst it = chars_.begin(), e = chars_.end(); it != e; ++it) {
        result.append(1, (*it)->first().getChar());
    }
    return result;
}
Exemplo n.º 4
0
int main()
{
   char word[20], search, result;

   printf("Input a word: ");
   scanf("%s", word);
   printf("Character to search for: ");
   scanf(" %c", &search);

   result = charCount(word, search);

   printf("Occurs %d times!\n", result);

   return 0;
}
int characterReplacement(std::string s, int k) 
{
	std::vector<int> charCount(26, 0);
	int start = 0, max_count = 0;

	for (int end = 0; end < s.size(); ++end)
	{
		++charCount[s[end] - 'A'];
		max_count = std::max(max_count, charCount[s[end] - 'A']);
		if (max_count + k < end - start + 1)//不能通过k次操作把滑动窗口中的元素变成相同字符
		{
			--charCount[s[start] - 'A'];
			++start;
		}
	}
	return s.size() - start;
}
Exemplo n.º 6
0
int charCount(char *str, char c)
{
   int result;

    /**0 is same as '\0'
    *reach the end of the string - return
    **/
   if (*str == 0)
      result = 0;
   else {
      if (*str == c)  /**found the match set result to 1*/
         result = 1;
      else
         result = 0;
         /**add the result to the next match if there is*/
      result += charCount(str+1, c);
   }
   return result;
}
Exemplo n.º 7
0
// -----------------Initial call to program  -----------------
int main(int argc, char *argv[]) {
    // ---------deprecated for #3 ----------
    // if a file name for input is passed
    // use that name instead of the default in
    // FNS[0] = input.txt
    // ---------deprecated for #3 ----------
    
    int i = 0;
    
    // -------must redo this section to take -l -a -v user input from console
    // ---------deprecated for #3 ----------
    if(argc > 1) {
        FNS[input_txt] = argv[1];
    }
    
    // initialize global ctype int arrays
    gInitGlobalintIsCharArrays();
    // create file pointers for input output
    // createFilePointers handles null pointer exception
    createFilePointers();
    // copy input file pointer
    FILE *ifp = m_FPS[input_txt];
    // copy clean input file pointer
    FILE *cifp = m_FPS[cleaninput_txt];
    
    
    // how many characters in file
    int count = charCount(ifp);
    if (count < 0) {
        printError(err27, FNS[input_txt]);
        //fileReadError(FNS[input_txt], input_txt);
        // this is fatal error
        exit(EXIT_FAILURE);
    }
    
    char code[count];
    // cleanCode will have input without comments
    char cleanCode[count];
    // initialize code arrays
    for (i = 0; i < count; i++) {
        code[i] = ' ';
        cleanCode[i] = ' ';
    }
    
    // read input file into array code[]
    readInput(ifp, code);
    // close the input file
    fclose(ifp);
    
    
    // remove comments from input
    //cleanCode[] will contain -comments free- input
    cleanInput(cifp, code, count, cleanCode);
    // close the -clean input- file
    fclose(cifp);
    
    // there will be at most m_nCleanCount separate string tokens
    char *caCleanInputTokens[m_nCleanCount];
    // separate cleanCode into tokens, allocate space as needed with calloc
    // need to free each caCleanInputTokens[] array index that calloc was done to
    // if caCleanInputTokens[] is not null, free it before exiting program
    // or after printing it to file
    splitInputTokens(cleanCode, caCleanInputTokens);
    
    // there will be at most m_nCleanCount separate namerecord_t tokens
    namerecord_t namerecord_table[m_nCleanCount];
    initializeNamerecord_table(namerecord_table);
    
    // identify what kind of lexeme each token is
    IdentifyInputToken(caCleanInputTokens, namerecord_table);
    
    // print each record to both lexemelist.txt and lexemetable.txt
    printNamerecord_table(namerecord_table);
    
    // call freeInputTokenCalloc after finishing the use of the array
    freeInputTokenCalloc(caCleanInputTokens);
    
    // program finished, if no error were found, it will reach this point
    
    
    // ---------------------- deprecated for #3 ----------------------
    /* / deprecated for #3
    printf("\nYou can find the input/ output files: \n");
    for (i = 0; i < MAX_FILES; i++) {
        // print the file names that were used and created
        printf("%s \n", FNS[i]);
        
    }
    printf("in the same folder where scanner.c is located \n\n");
    */ // deprecated for #3
    // ---------------------- deprecated for #3 ----------------------
    
    // program finished, if no error were found, it will reach this point

    
    return 0;
}
Exemplo n.º 8
0
//this function could be merged with populateProductsFromFile to reduce the program size
//takes a pointer to listings structure, a path to a file to read, and a pointer to memory (management) structure
int populateListingsFromFile(Listings *listings,const char *path,Memory *memory){
    unsigned int i;
    unsigned int j=0;
    unsigned int k;
    unsigned int count=0;
    string *temp;
    struct stat fileStat;
    unsigned long fileLength;
    char *fileCString;
    unsigned long listingCount;
    
    FILE* f;
    
    //if true something has gone wrong accessing the file
    if (stat(path, &fileStat)  || !(f= fopen (path, "rb"))){return -1;}
    
    assignMemory(memory, (void **) &(listings->file.cString),fileStat.st_size); //allocate memory for storing the file contents
    listings->file.length = fread(listings->file.cString,1,fileStat.st_size,f); //read file
    fclose(f);//close file
    
    listings->count=charCount(listings->file, '\n'); //number of entries set by number of newline characters (not foolproof but it works)
    
    //makes code easier to read
    fileLength=listings->file.length;
    fileCString=listings->file.cString;
    listingCount=listings->count;
    
    assignMemory(memory, (void **) &(listings->entry),listingCount*sizeof(string));
    assignMemory(memory, (void **) &(listings->currency),listingCount*sizeof(string));
    assignMemory(memory, (void **) &(listings->manufacturer),listingCount*sizeof(string));
    assignMemory(memory, (void **) &(listings->price),listingCount*sizeof(string));
    assignMemory(memory, (void **) &(listings->title),listingCount*sizeof(string));
    
    //parse listing buffer (listing file content)
    for (i=0; i<fileLength && count< listingCount; i++) {       //loop through entire listing buffer
        if(j==0 && fileCString[i]!='\r'){   //begining of new entry/listing/line
            listings->entry[count].cString=&(fileCString[i]);
        }
        if (fileCString[i]=='\n') {     //end of an entry/listing/line
            listings->entry[count].length=j;
            j=0;
            count++;
        }
        else if(fileCString[i]=='"'){   //start of a header
            j++;
            i++;
            if (cStringCmp(&(fileCString[i]), "price\":\"")==8) {
                j+=8;
                i+=8;
                temp=&(listings->price[count]);
            }
            else if (cStringCmp(&(fileCString[i]), "title\":\"")==8) {
                j+=8;
                i+=8;
                temp=&(listings->title[count]);
            }
            else if (cStringCmp(&(fileCString[i]), "currency\":\"")==11) {
                j+=11;
                i+=11;
                temp=&(listings->currency[count]);
            }
            else if (cStringCmp(&(fileCString[i]), "manufacturer\":\"")==15) {
                j+=15;
                i+=15;
                temp=&(listings->manufacturer[count]);
            }
            else{break;}
            temp->cString=&(fileCString[i]);
            for (k=0; (i+k)<fileLength && fileCString[i+k]!=0 && (fileCString[i+k]!='"' || fileCString[i+k-1]=='\\') && fileCString[i+k]!='\n' && fileCString[i+k]!='\r'; k++) {}//find end of property (property length)
            j+=k+1;
            i+=k;
            temp->length=k;
        }
        else{
            if(fileCString[i]!='\r'){   //other characters not cared about (",{}" and what not)
                j++;
            }
        }
    }
    return 0;
}