void test(const std::vector<int>& v, const std::vector<int>& tests) { for (unsigned int i = 0; i < tests.size(); i++) { std::cout << "In " << v << std::endl; std::cout << tests[i] << " apare de " << count_occurances(v, tests[i], 0, v.size() - 1) << " ori." << std::endl; std::cout << std::endl; } }
int count_occurances(const std::vector<int>& v, int key, int lower, int upper) { // TODO // Calculati recursiv numarul de aparitii ale lui key in v, // intre pozitiile lower si upper // In caz negativ, intoarceti not_found // // Good to know! // La calcularea pozitiei de mijloc folositi // int m = lower + (upper - lower) / 2; // nu // int m = (lower + upper) / 2; // Pentru a evita overflow la adunarea pe numere intregi. int m = lower + ( upper - lower ) / 2; if( lower < 0 ) return 0; if( lower == upper) if( v[lower] == key ) return 1; else return 0; return count_occurances ( v , key , lower , m) + count_occurances( v , key , m+1 , upper ); }
int main(int argc, char **argv) { int help_requested = 0, i, j; int words_start = 1, num_words = 0; int files_start = -1, num_files = 0; for(i = 1; i < argc; i++) { if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { help_requested = 1; break; } else if(!strcmp(argv[i], "--")) { files_start = i+1; continue; } if(files_start > 0) { num_files++; } else { num_words++; } } if(argc < 3 || help_requested) { usage(); exit(1); } char* words[num_words]; char* files[num_files]; for(i = words_start; i < words_start + num_words; i++) { /* uppercase word */ for(j = 0; j < strlen(argv[i]); j++) { argv[i][j] = toupper(argv[i][j]); } words[i-words_start] = argv[i]; } for(i = files_start; i < files_start + num_files; i++) { files[i-files_start] = argv[i]; } for(i = 0; i < num_files; i++) { int match_count; /* see if a directory is specified */ DIR* dir = opendir(files[i]); if(dir) { /* we got a directory */ int filesilen = strlen(files[i]); if(files[i][filesilen-1] == '/') { /* strip off trailing / if present */ files[i][filesilen-1] = '\0'; } struct dirent* entry; char path[PATH_MAX]; while((entry = readdir(dir))) { /* traverse the files in the directory */ struct stat buf; snprintf(path, PATH_MAX, "%s/%s", files[i], entry->d_name); stat(path, &buf); if(S_ISDIR(buf.st_mode)) { /* skip directories */ continue; } /* do match count */ match_count = count_occurances(words, num_words, path); if(match_count > 0) { fprintf(stdout, "%d\t%s\n", match_count, path); } } closedir(dir); } else { /* we have a file specified, do match count */ match_count = count_occurances(words, num_words, files[i]); if(match_count > 0) { fprintf(stdout, "%d\t%s\n", match_count, files[i]); } } } return 0; }