int initializeSet(int lines, Cache test, int assoc, char *kind){ test->valid=0; test->miss=0; test->cold_misses=0; test->capacity_miss=0; test->conflict_miss=0; test->memory_access=0; test->hits=0; test->total_misses=0; int count=0; test->blocks=(CacheArray**)malloc(lines * sizeof(struct cache_array)); for (int i=0;i<lines;i++){ test->blocks[i]=(CacheArray*)malloc(assoc *sizeof(struct cache_array)); if((strlen(test->type)>=7)&&(strncmp(test->type,"assoc:", 5)==0)){ /*create a lru policy using dll for each individual set*/ if(strcmp(kind,"lru")==0){ test->blocks[i]->LRU=SLCreate(); test->blocks[i]->FIFO=NULL; // printf("LRU DLL created\n"); } /*create a queue for each individual set*/ if(strcmp(kind,"fifo")==0){ test->blocks[i]->FIFO=queueCreate(assoc); test->blocks[i]->LRU=NULL; // printf("LRU DLL created\n"); } } for(int j=0;j<assoc;j++){ test->blocks[i][j].valid=0; test->blocks[i][j].tag=-1; test->blocks[i][j].indexSet=-1; test->blocks[i][j].offSet=-1; count++; // printf("%d, Valid %d Tag %lld\n", j, test->blocks[i][j].valid, test->blocks[i][j].tag); } count++; } if((strcmp(test->type,"FA")==0)||((strlen(test->type)==5)&& (strcmp(test->type,"assoc")==0))){ /*only for FA. Either lru policy or fifo*/ if(strcmp(kind,"lru")==0){ test->LRU=SLCreate(); test->FIFO=NULL; } if(strcmp(kind,"fifo")==0){ test->FIFO=queueCreate(lines); test->LRU=NULL; } } return 0; }
void add_record(char *word, char *filename) { struct Record *r; int record_id = djb2((unsigned char *) word); HASH_FIND_INT(records, &record_id, r); // linear probing to resolve collisions while (r != NULL) { // found word if (strcmp(r->word, word) == 0) { break; } record_id++; HASH_FIND_INT(records, &record_id, r); } if (r == NULL) { // found empty spot, proceed to add r = (struct Record *)malloc(sizeof(struct Record)); r->id = record_id; r->word = word; r->filenames = SLCreate(compareStrings, destroyStrings); SLInsert(r->filenames, filename); HASH_ADD_INT(records, id, r); } else { SLInsert(r->filenames, filename); } }
/* Given a line of file stats, create a Sorted List of file stats * and return it * */ SortedListPtr buildFileStatsList(char *line) { SortedListPtr newList = SLCreate(*compareStatsByFrequency); //tokenize by spaces char *result = NULL; result = strtok(line, " "); //tokenize until there are no more spaces char *filename = NULL; while(result != NULL) { int testNum = atoi(result); if(testNum == 0) //It must be a file name then { filename = result; } else { if(filename != NULL) { StatsPtr newStatsStruct = createStatsStruct(filename); newStatsStruct->frequency = testNum; int insert = SLInsert(newList, newStatsStruct); if(insert == 0) //Need to force it in the list { SLInsertIndex(newList, newStatsStruct); } } } result = strtok(NULL, " "); } return newList; }
/* test 7: 1. create list with compare and destroy functions 2. check SLInsert, add 1, 2, 3, 4, 5, SLRemove 3. create list iterate 4. check SLGetItem, SLNextItem 5. destroy list iterator 6. destroy list */ void test7(){ SortedListPtr list = SLCreate(compare, destroy); SortedListIteratorPtr iter; int i; int* value; for (i = 1; i <= 5; i++) { value = (int*)malloc(sizeof(int)); *value = i; SLInsert(list, (void*)value); } iter = SLCreateIterator(list); i = SLRemove(list, value); printf("SLRemove 5 returned %d\n", i); i = SLRemove(list, value); printf("SLRemove 5 returned %d\n", i); value = (int*)SLGetItem(iter); while (value != NULL) { printf("Value = %d\n", *value); value = (int*)SLNextItem(iter); } SLDestroy(list); SLDestroyIterator(iter); printf("Test 7 completed\n"); }
/* test 1: 1. create list, check it is empty 2. use 1, create list iterate, check empty 3. use 2, check SLGetItem 4. use 3, check SLNextItem 5. destroy list iterator 6. destroy list */ void test1(){ SortedListPtr list = SLCreate(compare, destroy); SortedListIteratorPtr iter; int* value; if (list == NULL) { printf("Cannot created list\n"); exit(0); } iter = SLCreateIterator(list); value = (int*)SLGetItem(iter); if (value != NULL) { printf("Value must be null\n"); exit(0); } value = (int*)SLNextItem(iter); if (value != NULL) { printf("Value must be null\n"); exit(0); } SLDestroy(list); SLDestroyIterator(iter); printf("Test 1 completed\n"); }
/* test 6: 1. Do the test 5 with SLNextItem over list */ void test6(){ SortedListPtr list = SLCreate(compare, destroy); SortedListIteratorPtr iter; int i; int* value; for (i = 1; i <= 5; i++) { value = (int*)malloc(sizeof(int)); *value = i; SLInsert(list, (void*)value); } iter = SLCreateIterator(list); value = (int*)SLGetItem(iter); while (value != NULL) { printf("Value = %d\n", *value); value = (int*)SLNextItem(iter); } value = (int*)SLNextItem(iter); if (value != NULL) { printf("Over end of list, must be null\n"); exit(0); } SLDestroy(list); SLDestroyIterator(iter); printf("Test 6 completed\n"); }
void ht_merge(SortedListPtr list, const char* filepath, HashTable *hashtable, SortedListPtr wordlist) { FileCountPair *fcp; WordCountPair *wcp; SortedListIteratorPtr iterator; SortedListIteratorPtr mainListIterator; char *word; WordListPair *wlp; iterator = SLCreateIterator(wordlist); while ((word = SLNextItem(iterator)) != NULL) { mainListIterator = SLCreateIterator(list); wcp = ht_get(hashtable, word); fcp = malloc(sizeof(FileCountPair)); fcp->filepath = filepath; fcp->count = wcp->count; while ((wlp = SLNextItem(mainListIterator)) != NULL) { if (strcmp(wlp->word, word) == 0) { break; } } if (wlp == NULL) { //the word is not already in the main list SortedListPtr newlist = SLCreate(&compareFileCounts); SLInsert(newlist, fcp); wlp = malloc(sizeof(WordListPair)); wlp->word = word; wlp->list = newlist; SLInsert(list, wlp); } else { SLInsert(wlp->list, fcp); } SLDestroyIterator(mainListIterator); } SLDestroyIterator(iterator); }
int addWord(char * word, char * filename){ //intialisation WordCount fileToAdd; fileToAdd = (WordCount)malloc(sizeof(WordCount)); fileToAdd->filename = (char*)malloc((sizeof(char)*100)); fileToAdd->count = 1; fileToAdd->filename = filename; ll word = (ll)malloc(sizeof(ll)); word->word = (char*)malloc((sizeof(char)*100)); word->word = word; //need to look at sorted list ll wordexists; wordexists = (ll) SLFindNode(wordList, word); //if exists if(wordexists != NULL){ printf("word %s exists\n", word); SortedListIteratorPtr iter; iter = SLCreateIterator(wordexists->file); void *object = NULL; while((object = SLNextItem(iter))){ WordCount file; file = object; if(compareCounts(file, object) == 0){ file->count++; break; } //addWord(file->file->filename); } SLDestroyIterator(iter); if(object == NULL){ //does not found, add!! SLInsert(wordexists->file, fileToAdd); //adding //free free(word->word); free(word); return 1; } else{ //free everything printf("error when adding word\n"); free(fileToAdd->filename); free(fileToAdd); free(word->word); free(word); } return 0; } else{ //file not found word->file = SLCreate(compareCounts); SLInsert(word->file,fileToAdd); SLInsert(wordList, word); return 1; } }
/* test 3: 1. create list, null destroy 2. use 1, check null list */ void test3(){ SortedListPtr list = SLCreate(compare, NULL); if (list != NULL) { printf("List must be NULL due to invalid argument\n"); exit(0); } printf("Test 3 completed\n"); }
/* test 2: 1. create list, null compare 2. use 1, check null list */ void test2(){ SortedListPtr list = SLCreate(NULL, destroy); if (list != NULL) { printf("List must be NULL due to invalid argument\n"); exit(0); } printf("Test 2 completed\n"); }
int main(int argc, const char **argv) { /*Check for args*/ if (argc != 3) { fprintf(stderr, "USAGE: index <inverted-index file name> " "<directory or file name>\n"); return 1; } if (argv[2][0] == ')') { /*Don't allow from root directory*/ fprintf(stderr,"ERROR: Indexing from root is disallowed!\n"); return EXIT_FAILURE; } wordList = SLCreate(compareWords); /*Check if arg2 is directory or file*/ struct stat s; if( stat(argv[2],&s) == 0 ) { if( s.st_mode & S_IFDIR ) { /*Directory*/ char *dir; dir = (char *) malloc ( BUFSIZ ); snprintf(dir, BUFSIZ-1, "%s", argv[2]); openAndIndexDirectory(dir); free (dir); } else if( s.st_mode & S_IFREG ) { /*File*/ char *file; file = (char *) malloc ( BUFSIZ ); snprintf(file, BUFSIZ-1, "%s", argv[2]); openAndIndexFile(file); free (file); } else { /*Don't know what it is*/ fprintf(stderr,"STAT: Unknown data type\n"); return EXIT_FAILURE; } } else { fprintf(stderr,"STAT: Unknown fatal error (Check file/dir name)\n"); return EXIT_FAILURE; } /*Write inverted index to specified file*/ writeWordListToFile(argv[1]); /*Destroy word list*/ destroyWordList(); }
SortedListPtr inputToLinkedList(char* tokenInput) { //create new list SortedListPtr inputList = SLCreate(*compareStrings); //add words to linked list until the tokenstream is null while(tokenInput != NULL) { SLInsert(inputList, tokenInput); tokenInput = strtok(NULL, " "); } return inputList; }
/* main method invokes exploreDirectories() to create the TokenList datastructure Then invokes writFile to write the inverted-index file. */ int main(int argc, char **argv) { TokenList = SLCreate(compareTokenStructs, destroyTokenStruct); argCheck(argc, argv); exploreDirectories(argv[2]); writeFile(argv[1]); SLDestroy(TokenList); return 0; }
int main(int argc, char **argv){ if(argc != 3){ printf("Error: invalid number of arguments\n"); return -1; } if(strcmp(argv[1],argv[2])==0){ printf("input arguments are the same file. Cannot overwrite. Exiting Indexer.\n"); return 0; } int rval; char* output=argv[1]; rval = access(output,F_OK); if(rval==0){ //file exists } else if(errno==EACCES){ printf("%s is not accessible\n", output); return 0; } rval = access(output, W_OK); if(rval==0){ //permission to write }else if (errno==EACCES){ printf("you do not have permission to write to %s\n",output); return 0; } struct List *list = SLCreate(); //create list to store words struct stat fileStat; //check if directory or file to be indexed exists if(stat(argv[2], &fileStat) == 0){ directoryTraverse(list, argv[2]); }else{ fprintf(stderr, "Directory or file you are trying to index does not exist.\n"); return -1; } writefile(argv[1],list); destroyList(list); return 0; }
void process(char *myToken, char *myFilePath) //Change the parameters to (char * str1, char * str2) { rust = SLCreate(compareStrings); char * buffer= (char*)malloc(101); FILE * f = fopen("aux.txt", "r"); char * trok = (char*)malloc(101); NNodePtr him = (NNodePtr)malloc(sizeof(NNode)); while(fscanf(f, "%s %s", buffer, trok)!=EOF){ char * copyone = malloc(strlen(trok)+1); strcpy(copyone, trok); char * copytwo = malloc(strlen(buffer) +1); strcpy(copytwo, buffer); him->key = copyone; him->filename = copytwo; insert(him); Insert(rust, him->key, him->key); //free(him); //him = (NNodePtr)malloc(sizeof(NNode)); // printAll(); } fclose(f); // printAll(); return; }
int main(int argc, char **argv) { /* int i7,i5,i3,i4; */ /* double d1, d2, d3, d4, d5; */ char *s1, *s2, *s3, *s4, *s5; SortedListPtr sl; SortedListIteratorPtr slip; sl = SLCreate(compareInts); s1 = "Hello"; s2 = "World"; s3 = "Dawgs"; s4 = "Tacos"; s5 = "Zebra"; SLInsert(sl, s1); // => ['HELLO'] printListString(sl); SLInsert(sl, s2); // => ['WORLD', 'HELLO'] printListString(sl); SLInsert(sl, s3); // => ['WORLD', 'HELLO', 'DOGS'] printListString(sl); SLInsert(sl, s4); // => ['WORLD', 'HELLO', 'DOGS'] printListString(sl); SLInsert(sl, s5); // => ['ZZZ', 'WORLD', 'HELLO', 'DOGS'] printListString(sl); SLRemove(sl, s2); // => ['ZZZ', 'HELLO', 'DOGS'] printListString(sl); slip = SLCreateIterator(sl); printf("------------------------------\n"); printf("%s\n", (char*)SLNextItem(slip)); SLRemove(sl, s1); printf("%s\n", (char*)SLNextItem(slip)); printListString(sl); printf("%s\n", (char*)SLNextItem(slip)); SLDestroyIterator(slip); SLDestroy(sl); return 0; }
/* Given the name of a file exported from indexer, parse it back into * the linked list form. * */ SortedListPtr parseFileToList(char *filename) { FILE *fp = fopen(filename,"r"); if(fp == NULL) { printf("Unable to open file %s\n",filename); return NULL; } SortedListPtr newList = SLCreate(*compareWordStruct); WordPtr curWord = NULL; char line[128]; while(fgets(line,128,fp) != NULL) { //Trim the newline character. if(strlen(line) > 0) { line[strlen(line)-1] = '\0'; //printf("Input trimmed.\n"); } //Classify the type of line. enum lineType curLine = classifyLine(line); //printf("Line type: %d\n",curLine); switch(curLine) { case WordLine: //Extract the word from the line. curWord = extractWord(line); //printf("Inserting new word into list.\n"); SLInsert(newList, curWord); break; case FileStatsLine: //Parse the line //Add the file stats to curWord's filestatslist curWord->filestats = buildFileStatsList(line); break; case Throwaway: //Do nothing I guess. break; } } fclose(fp); return newList; }
int main(int argc, char **argv) { if(argc != 3){ printf("Error: invalid input\n"); return -1; } CompareFuncT cf = &compareWordListPairs; SortedListPtr words = SLCreate(cf); char *filepath = argv[2]; if (filepath[strlen(filepath)-1] == '/') { filepath[strlen(filepath)-1] = '\0'; } scan_dir(filepath, filepath, words); outputPairsToFile(argv[1],words); SLDestroy(words); return 0; }
void insert(NNodePtr item){ HashBucket * current_token; char * KEY = item->key; HASH_FIND_STR(tokens, KEY , current_token); // printf("KEY: %s\n", KEY); if(current_token==NULL){ current_token = (HashBucket*)malloc(sizeof(HashBucket)); current_token->name = item->key; CompareFuncT c = compareInts; SortedListPtr temp = SLCreate(c); int * one = malloc(sizeof(int)); *one = 1; int success; success = SLInsert(temp, (void*)one, item->filename); current_token->list = temp; HASH_ADD_STR(tokens, name, current_token); // free(item); } else{ // printf("Entered process\n"); SortedListPtr temp = current_token->list; int success = 0; int * one = malloc(sizeof(int)); *one = 1; void*zone = (void*)one; success = SLInsert(temp, zone, item->filename); current_token->list = temp; HASH_DEL(tokens, current_token); HASH_ADD_STR(tokens, name, current_token); //free(item); } return; }
/* process Token will add the (token, filename) tuple to the TokenList object. Duplicate (token, filename) will increment frequency. New tuples will create new objects to be added to the nested sorted-lists. @param word : Token to be added @param filename : Filename associated with word */ void processToken(char* word, char* filename) { Token *searchToken; fileRecord *searchRecord; Token *newToken = malloc(sizeof(Token)); fileRecord *newRecord = malloc(sizeof(fileRecord)); if (newRecord == NULL || newToken == NULL) { fprintf(stderr, "errno %d\n", errno); fprintf(stderr, "mesg: %s\n", strerror(errno)); exit(-1); } newToken->word = word; newToken->fileList = NULL; newRecord->filename = copyFileName(filename); newRecord->frequency = 1; if( (searchToken = SLSearch(TokenList, newToken, compareRecordName)) != NULL ){ if( (searchRecord = SLSearch(searchToken->fileList, newRecord, compareRecordName)) != NULL ){ int freq = searchRecord->frequency; newRecord->frequency = freq+1; SLInsert(searchToken->fileList, newRecord); SLRemove(searchToken->fileList, searchRecord); } else{ SLInsert(searchToken->fileList, newRecord); } destroyTokenStruct(newToken); } else{ newToken->fileList = SLCreate(compareRecordStructs, destroyFileRecord); SLInsert(newToken->fileList, newRecord); SLInsert(TokenList, newToken); } }
STDMETHODIMP CHashCheck::Initialize( LPCITEMIDLIST pidlFolder, LPDATAOBJECT pdtobj, HKEY hkeyProgID ) { // We'll be needing a buffer, and let's double it just to be safe TCHAR szPath[MAX_PATH << 1]; // Make sure that we are working with a fresh list SLRelease(m_hList); m_hList = SLCreate(); // This indent exists to facilitate diffing against the CmdOpen source { FORMATETC format = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; STGMEDIUM medium; if (!pdtobj || pdtobj->GetData(&format, &medium) != S_OK) return(E_INVALIDARG); if (HDROP hDrop = (HDROP)GlobalLock(medium.hGlobal)) { UINT uDrops = DragQueryFile(hDrop, -1, NULL, 0); for (UINT uDrop = 0; uDrop < uDrops; ++uDrop) { if (DragQueryFile(hDrop, uDrop, szPath, countof(szPath))) { SLAddStringI(m_hList, szPath); } } GlobalUnlock(medium.hGlobal); } ReleaseStgMedium(&medium); } // If there was any failure, the list would be empty... return((SLCheck(m_hList)) ? S_OK : E_INVALIDARG); }
SortedListPtr searchOr(SortedListPtr indexList, SortedListPtr inputList) { //need a result list SortedListPtr result = SLCreate(*compareStrings); //need to iterate through the inputList to check the words in the indexList SortedListIteratorPtr inputIterator = SLCreateIterator(inputList); do { SLNode inputListPtr = inputIterator->curNode; char* inputListWord = (char*)inputListPtr->value; //need to iterate through the indexListIterator for each item of inputList SortedListIteratorPtr indexListIterator = SLCreateIterator(indexList); do { //compare the word in the indexed list to the input list to see if they match SLNode indexListPtr = indexListIterator->curNode; WordPtr indexWord = (WordPtr) indexListPtr->value; int compareWords = strcmp(indexWord->wordArray, inputListWord); if(compareWords == 0) { //extract the filelist for the word SortedListPtr filePtr = indexWord->filestats; SortedListIteratorPtr fileIterator = SLCreateIterator(filePtr); //add the word to the result list do { SLNode fileHead = (SLNode)filePtr->headOfList; StatsPtr fileNamesPtr = (StatsPtr)fileHead->value; char* filenameToAdd = fileNamesPtr->filename; SLInsert(result, filenameToAdd); }while (SLNextItem(fileIterator) != NULL); SLDestroyIterator(fileIterator); } } while (SLNextItem(indexListIterator) != NULL); SLDestroyIterator(indexListIterator); } while(SLNextItem(inputIterator) != NULL); SLDestroyIterator(inputIterator); return result; }
/* Given two lists of file names, return a list of file names that * is in both lists. */ SortedListPtr findCommonElements(SortedListPtr firstList, SortedListPtr secondList) { SortedListPtr commonElements = SLCreate(*compareStrings); SortedListIteratorPtr outsideIter = SLCreateIterator(firstList); do { //printf("Grabbing outside node.\n"); SLNode outsideNode = outsideIter->curNode; SortedListIteratorPtr insideIter = SLCreateIterator(secondList); do { //For every element in the second list, compare it to whatever my outsideIter is pointing to. SLNode insideNode = insideIter->curNode; //printf("Attempting to compare file stats by file name\n"); //int compareVal = compareStatsByFilename(outsideNode->value, insideNode->value); if(outsideNode == NULL || insideNode == NULL || outsideNode->value == NULL || insideNode->value == NULL) { SLDestroyIterator(insideIter); SLDestroyIterator(outsideIter); SLDestroy(commonElements); //printf("Returning from findcommonelements because something is null.\n"); return NULL; } int compareVal = strcmp(outsideNode->value, insideNode->value); //printf("Compareval = %d\n",compareVal); if(compareVal == 0) //Same file name, add it to the results list { //Theyre the same, so I can just add the outside one char* outsideStats = outsideNode->value; //printf("Found common element: %s\n", outsideStats); SLInsert(commonElements, outsideStats); } }while(SLNextItem(insideIter) != NULL); SLDestroyIterator(insideIter); }while(SLNextItem(outsideIter) != NULL); SLDestroyIterator(outsideIter); return commonElements; }
/* test 4: 1. create list with compare and destroy functions 2. check SLInsert, add 1, 2, 3, 4, 5 3. create list iterate 4. check SLGetItem 5. destroy list iterator 6. destroy list */ void test4(){ SortedListPtr list = SLCreate(compare, destroy); SortedListIteratorPtr iter; int i; int* value; for (i = 1; i <= 5; i++) { value = (int*)malloc(sizeof(int)); *value = i; SLInsert(list, (void*)value); } iter = SLCreateIterator(list); value = (int*)SLGetItem(iter); printf("Value = %d\n", *value); SLDestroy(list); SLDestroyIterator(iter); printf("Test 4 completed\n"); }
int main(int argc, char** argv){ //***************** STRING TEST *********************** int i; const char* stringList[] = {"Hey", "Boy", "Zeus", "world", " ", "blah", " zzz", "aaa"}; char* stringPtr = (char*) malloc(sizeof(stringList)); SortedListPtr stringsl = SLCreate(compareStrings, NULL); /* for(i=0; i<(sizeof(stringList)/sizeof(stringList[0])); i++){ stringPtr = (char*) stringList[i]; SLInsert(stringsl, stringPtr); } */ SortedListIteratorPtr stringiterator2 = SLCreateIterator(stringsl); SLNextItem(stringiterator2); SLInsert(stringsl, "f"); SLInsert(stringsl, "d"); SLInsert(stringsl, "b"); //SLRemove(stringsl, "Apple"); SortedListIteratorPtr stringiterator = SLCreateIterator(stringsl); while((stringPtr = (char*) SLNextItem(stringiterator)) != NULL){ printf("%s\n", stringPtr); } //cleans mess free(stringPtr); SLDestroy(stringsl); SLDestroyIterator(stringiterator); }
/* Perform logical and search * * */ SortedListPtr searchLogicalAnd(SortedListPtr indexHead, SortedListPtr words) { SortedListPtr result = SLCreate(*compareStrings); SortedListPtr nextResult = NULL; SortedListPtr testResult = NULL; //Check if the first word exists SortedListIteratorPtr wordIter = SLCreateIterator(words); char *curWord = (char*)wordIter->curNode->value; int wordSearch = SLSearchWord(indexHead, curWord); //If the word is not in the list then just screw it, they get nothing. if(wordSearch == -1) { //printf("Returning becasue wordSearch=-1\n"); SLDestroyIterator(wordIter); SLDestroy(result); return NULL; } //First word is in the list, so just copy everything from its filestats to results SLNode firstwordNode = SLGetIndex(indexHead, wordSearch); //printf("Copying all first word's stuff into new list\n"); insertAllFilenames(result, firstwordNode); //Now hop into a while loop and check over and over. int i = 0; while(SLNextItem(wordIter) != NULL) { SortedListPtr nextWordList = SLCreate(*compareStrings); curWord = (char*)wordIter->curNode->value; int searchVal = SLSearchWord(indexHead, curWord); if(searchVal == -1) //Word not in the list, return nothing immediately. { //destroyAllStrings(result); //printf("Returning because searchVal = -1 inside while.\n"); SLDestroy(nextWordList); //SLDestroy(result); if(nextResult != NULL) { SLDestroy(nextResult); } SLDestroyIterator(wordIter); return NULL; } else { SLNode nextNode = SLGetIndex(indexHead, searchVal); //printf("Copying another word's file stats shit\n"); insertAllFilenames(nextWordList, nextNode); //printf("Attempting to find common elements.\n"); if(i == 0) { testResult = findCommonElements(result, nextWordList); if(testResult != NULL) { nextResult = testResult; } else { if(nextResult != NULL) { SLDestroy(nextResult); } SLDestroyIterator(wordIter); SLDestroy(nextWordList); return NULL; } SLDestroy(result); } else { testResult = findCommonElements(nextResult, nextWordList); if(testResult != NULL) { nextResult = testResult; } else { if(nextResult != NULL) { SLDestroy(nextResult); } SLDestroyIterator(wordIter); SLDestroy(nextWordList); return NULL; } } } //destroyAllStrings(nextWordList); SLDestroy(nextWordList); i++; } SLDestroyIterator(wordIter); if(i == 0) { return result; } else { return nextResult; } }
void * myMalloc(unsigned int size, char * fn, int ln) { void *ret_ptr; //Return pointer memEntry *ptr; memEntry *after; static memEntry *head = 0; //points to front of memEntry list static memEntry *tail = 0; //points to back of memEntry list ptr = head; while(ptr != 0) { if(ptr->isFree == 0 || (ptr->size < size)) { //This block is not free or is too small. ptr = ptr->next; } else if(ptr->size < (size + sizeof(memEntry))) { //This block is not big enough to cut up. ptr->isFree = 0; ret_ptr = (char *)ptr + sizeof(memEntry); // Adding this block to the list of blocks. SLInsert(sl, ret_ptr); printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr); return ret_ptr; } else { // Creating the split-up block to come after our newly allocated block. after = (memEntry *)((char *)ptr + sizeof(memEntry) + size); //offset from where ptr was; accounts for size of a mementry and the size of the block after->prev = ptr; after->next = ptr->next; if(ptr->next != 0){ ptr->next->prev = after; } ptr->next = after; after->size = ptr->size - sizeof(memEntry) - size; after->isFree = 1; ptr->size = size; ptr->isFree = 0; if (ptr == tail) { tail = after; } ret_ptr = (char *)ptr + sizeof(memEntry); // Adding this block to the list of blocks. SLInsert(sl, ret_ptr); printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr); return ret_ptr; } } ptr = (memEntry *)sbrk(size + sizeof(memEntry)); //Extending the heap by (size + sizeof(memEntry) bytes if there isn't enough space in any free blocks if(ptr == (void *)-1) { printf(KRED "Error: Malloc failed in file %s at line %d\n" KNRM, fn, ln); return 0; } else if(tail == 0) { // tail is null, adds first one ptr->prev = 0; ptr->next = 0; ptr->size = size; ptr->isFree = 0; head = ptr; tail = ptr; ret_ptr = (char *)ptr + sizeof(memEntry); sl = SLCreate(ptrcmp); // Adding this block to the list of blocks. SLInsert(sl, ret_ptr); printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr); return ret_ptr; } else { // otherwise add to existing list ptr->prev = tail; ptr->next = tail->next; ptr->size = size; ptr->isFree = 0; tail->next = ptr; tail = ptr; ret_ptr = (char *)ptr + sizeof(memEntry); // Adding this block to the list of blocks. SLInsert(sl, ret_ptr); printf(KGRN "Alloc\'d block 0x%x\n" KNRM, ret_ptr); return ret_ptr; } printf(KRED "Error: Malloc failed in file %s at line %d\n" KNRM, fn, ln); return 0; }
int main(int argc, char** argv){ printf("Sample test cases, for more test cases look at testcode.txt and at testplan.txt for its expected behavior\n\n"); printf("********************************************* TEST CASE 1 ***********************************************\n\n"); SortedListPtr sl1 = SLCreate(compareInts, NULL); SLDestroy(sl1); printf("\n"); printf("********************************************* TEST CASE 6 ***********************************************\n\n"); const char * stringArray[] = {"Zoid", "Brackets", "Apple"}; void * printer; SortedListPtr sl2 = SLCreate(compareStrings, destroyBasicTypeNoAlloc); int i; for(i=0; i<(sizeof(stringArray)/sizeof(stringArray[0])); i++){ if(SLInsert(sl2, (void *)stringArray[i])==0) printf("There was an error but the list was still created anyway\n"); } SortedListIteratorPtr iter2 = SLCreateIterator(sl2); printf("List: "); while((printer=SLNextItem(iter2)) != NULL) printf("%s ", (char *)printer); SLInsert(sl2, " zoom"); printf("%s ", (char *)SLNextItem(iter2)); printf("\n\n"); SLDestroy(sl2); SLDestroyIterator(iter2); printf("********************************************* TEST CASE 8 ***********************************************\n\n"); const char * stringArr[] = {"zoom", "wii", "Soccer", "Zoid", "Brackets", " zoom"}; void * print; void * print2; SortedListPtr sl = SLCreate(compareStrings, destroyBasicTypeNoAlloc); int p; for(p=0; p<(sizeof(stringArr)/sizeof(stringArr[0])); p++){ if(SLInsert(sl, (void *)stringArr[p])==0) printf("There was an error but the list was still created anyway\n"); } SortedListIteratorPtr iterator = SLCreateIterator(sl); SortedListIteratorPtr iterator2 = SLCreateIterator(sl); printf("iterator 1: "); print = SLNextItem(iterator); printf("%s \n", (char *)iterator->currentNode->data); printf("iterator 2: "); print2 = SLNextItem(iterator2); print2 = SLNextItem(iterator2); printf("%s \n", (char *)iterator2->currentNode->data); SLRemove(sl, iterator->currentNode->data); SLRemove(sl, iterator2->currentNode->data); printf("%s \n", (char *)SLNextItem(iterator)); printf("%s \n", (char *)SLNextItem(iterator2)); SLDestroyIterator(iterator); SLDestroy(sl); return 0; }
int main(int argc, char*argv[]) { int choice = atoi(argv[1]); printf("Choice: %d\n", choice); if(choice == 1){ //1. Normal SLInserts (@ beginning, middle, end of list) //a. integers SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[6] = {7,5,155,42,-1,6}; if(populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,NULL,NULL,NULL) == 0){ failure(); return 1; } SortedListIteratorPtr iter = SLCreateIterator(s); iterprint_all(s,iter,INT); //prints 155 42 7 6 5 -1 }else if(choice == 2){ //b. doubles SortedListPtr s = SLCreate(compareDoubles,destroyBasicTypeAlloc); double darr[6] = {7.43,5.55,155.26,42.1,-1.5,6.7}; if(populate_list(s,DOUBLE,sizeof(darr)/sizeof(double),NULL,darr,NULL,NULL) == 0){ failure(); return 1; } SortedListIteratorPtr iter = SLCreateIterator(s); iterprint_all(s,iter,DOUBLE); //prints 155.26 42.1 7.43 6.7 5.55 -1.5 }else if(choice == 3){ //c. strings SortedListPtr s = SLCreate(compareStrings,destroyBasicTypeAlloc); char *carr[6] = {"cat","dog","catamaran","apple","cormorant","zebra"}; if(populate_list(s,STRING,6,0,0,carr,NULL) == 0){ failure(); return 1; } SortedListIteratorPtr iter = SLCreateIterator(s); iterprint_all(s,iter,STRING); //prints apple cat catamaran cormorant dog zebra // should print zebra dog cormorant catamaran cat apple }else if(choice == 4){ //d. structs SortedListPtr s = SLCreate(compareTestStructs,destroyBasicTypeAlloc); TestStruct strtarr[6]; strtarr[0].field = 7; strtarr[1].field = 5; strtarr[2].field = 155; strtarr[3].field = 42; strtarr[4].field = -1; strtarr[5].field = 6; if(populate_list(s,STRUCT,6,0,0,0,strtarr) == 0){ failure(); return 1; } SortedListIteratorPtr iter = SLCreateIterator(s); iterprint_all(s,iter,STRUCT); //prints 155 42 7 6 5 -1 }else if(choice == 5){ //SLRemove nonexistent element SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[6] = {7,5,155,42,-1,6}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); int toremove = 54; if (SLRemove(s,&toremove) != 0) { failure(); }else{ success(); } }else if(choice == 6){ //SLRemove existing element (no duplicates; didn't handle them anyway) SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[6] = {7,5,155,42,-1,6}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); int toremove = 5; if (SLRemove(s,&toremove) != 0) { SortedListIteratorPtr iter = SLCreateIterator(s); iterprint_all_int(s,iter); //prints 155 42 7 6 -1 }else{ failure(); } }else if(choice == 7){ //Iterate on empty list //Should not fail SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); SortedListIteratorPtr iter = SLCreateIterator(s); iterprint_all_int(s,iter); }else if (choice == 8){ //SLInsert for item beyond iterator SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[6] = {7,5,155,42,-1,6}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); void *item = SLNextItem(iter); item = SLNextItem(iter); int *toins = malloc(sizeof(int)); *toins = 4; SLInsert(s,toins); iterprint_all_int(s,iter); //prints 7 6 5 4 -1 }else if(choice == 9){ //Create multiple iterators on same list, interleave iterations. //Delete item between iterators. SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[6] = {7,5,155,42,-1,6}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr olditer = SLCreateIterator(s); SortedListIteratorPtr iter = SLCreateIterator(s); void *item; int i; for(i = 0; i < 2; i++){ item = SLGetItem(olditer);//modify by lezi printf("%d ", *((int*)item)); item = SLNextItem(olditer);//modify by lezi } //prints 155 42 printf("\n"); for(i = 0; i < 4; i++){ item = SLGetItem(iter); //modify by lezi printf("%d ", *((int*)item)); item = SLNextItem(iter);//modify by lezi } //prints 155 42 7 6 printf("\n"); int itoremove = 6; if (SLRemove(s,&itoremove) == 0) { failure(); return 1; } item = SLGetItem(iter); //prints 5 //modufy by lezi printf("%d\n", *((int*)item)); item = SLGetItem(olditer); printf("%d\n", *((int*)item)); //prints 7 //modify by lezi iterprint_all_int(s,iter); //prints 5 -1 iterprint_all_int(s,olditer); //prints 7 5 -1 }else if(choice == 10){ //SLRemove end element, iterator positioned on it SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[3] = {7,5,3}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); int x3 = 3; void *item = SLNextItem(iter); item = SLNextItem(iter);//iterator points to 3 if(SLRemove(s,&x3) && SLNextItem(iter) == NULL){ success(); }else{ failure(); } }else if(choice == 11){ //TODO //SLRemove element in middle, iterator positioned on it SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[3] = {7,5,3}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); void *item = SLNextItem(iter); int x1 = 5; if(SLRemove(s,&x1) && *((int*)SLNextItem(iter)) == 3 && ((int*)SLNextItem(iter)) == NULL){ success(); }else{ failure(); } }else if(choice == 12){ //SLRemove element positioned immediately after element iterator is pointing to SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[6] = {7,5,155,42,-1,6}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); void *item = SLNextItem(iter); item = SLNextItem(iter); int x1 = 6; if(SLRemove(s,&x1) && *((int*)SLGetItem(iter)) == 7 //modify by lezi && *((int*)SLNextItem(iter)) == 5 && *((int*)SLNextItem(iter)) == -1 && ((int*)SLNextItem(iter)) == NULL){ success(); }else{ failure(); } }else if(choice == 13){ //Add item between recently returned element and element about to be returned. SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[3] = {7,5,3}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); void *item = SLNextItem(iter); item = SLNextItem(iter);//point to 3 now int *x4 = malloc(sizeof(int)); *x4 = 4; SLInsert(s,x4); iterprint_all_int(s,iter); //prints 3 }else if(choice == 14){ //Add item to head and middle, after iterator has been created //modify by Lezi SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[3] = {7,5,3}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); int *toinsert = malloc(sizeof(int)); *toinsert = 8; SLInsert(s,toinsert); int *toinsert1 = malloc(sizeof(int)); *toinsert1 = 4; // add by lezi SLInsert(s,toinsert1);//add by lezi iterprint_all_int(s,iter); //prints 7 5 4 3 //modify by lezi }else if(choice == 15){ //Add item to tail after all items have been returned by iterator. SortedListPtr s = SLCreate(compareInts,destroyBasicTypeAlloc); int iarr[3] = {7,5,3}; populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0,NULL); SortedListIteratorPtr iter = SLCreateIterator(s); void *item; while((item = SLNextItem(iter)) != NULL); int *toins = malloc(sizeof(int)); *toins = -1; SLInsert(s,toins); if(SLGetItem(iter) == NULL){ //modify by lezi success(); }else{ failure(); } }else{ printf("Bad input\n"); } return 0; }
void addToList(char *fS, SortedList1Ptr SL, char *pathName) { TokenizerT* tokenizer = TKCreate(" ", fS); Node1* temp; if(tokenizer == NULL) { printf("Error: unable to create tokenizer\n"); } char* token = NULL; while((token = TKGetNextToken(tokenizer)) != NULL) { if(SL==NULL) { printf("SL CREATED\n"); SL = SLCreate(token, pathName); //printf(SL->root->token); temp = SL->root; while(temp!=NULL) { printf("%s->",temp->token); temp=temp->next; } printf("\n"); } else { #ifdef DEBUG printf("***************TOKEN ADDED: %s\n", token); printf("***************Pathname ADDED: %s\n", pathName); #endif SLInsert(SL, token, pathName); if(strcmp(pathName, "") == 0) printf("\n%spathname is blank%s\n",KRED, KNORM); else printf("\n%s%s%s\n", KRED, pathName, KNORM); printlist(SL); // printf(SL->root->token); // temp = SL->root; while(temp!=NULL) { printf("%s->",temp->token); temp=temp->next; } printf("\n"); } // free(token); ???????????? } printf("Main(): Final result, print the ROOT from Vertical SL: %s\n", SL->root->token ); printf("Main(): Final result, print the ROOT's filename from Vertical SL: %s\n", SL->root->accessToNode2->fileName ); printf("Main(): Final result, print the ROOT's frequency from Vertical SL: %d\n", SL->root->accessToNode2->frequency); // printf("Main(): 2 items in HSL : Final result, print the ROOT's frequency from Vertical SL: %s\n", SLMain->root->accessToNode2->next->fileName); // printf("Main(): 2 items in HSL : Final result, print the ROOT's frequency from Vertical SL: %d\n", SLMain->root->accessToNode2->next->frequency); printf("Main():22222 Final result, print the ROOT from Vertical SL: %s\n", SL->root->next->token ); printf("Main():22222 Final result, print the ROOT's filename from Vertical SL: %s\n", SL->root->next->accessToNode2->fileName ); printf("Main():22222 Final result, print the ROOT's frequency from Vertical SL: %d\n", SL->root->next->accessToNode2->frequency); printf("Main():33333 Final result, print the ROOT from Vertical SL: %s\n", SL->root->next->next->token ); printf("Main():33333 Final result, print the ROOT's filename from Vertical SL: %s\n", SL->root->next->next->accessToNode2->fileName ); printf("Main():33333 Final result, print the ROOT's frequency from Vertical SL: %d\n", SL->root->next->next->accessToNode2->frequency); printf("Main():55555 Final result, print the ROOT from Vertical SL: %s\n", SL->root->next->next->next->token ); TKDestroy(tokenizer); }