int main(int argc, char* argv[]) { DynArr* b; int n, i; double t1, t2; for(n=1000; n < 200000; n=n*2) /* outer loop */ { b = createDynArr(n); for( i = 0 ; i < n; i++) { addDynArr(b, (TYPE)i); /*Add elements*/ } t1 = getMilliseconds();/*Time before contains()*/ for(i=0; i<n; i++) { containsDynArr(b, i); } t2 = getMilliseconds();/*Time after contains()*/ printf("Time for running contains() on %d elements: %g ms\n", n, t2-t1); /* delete DynArr */ deleteDynArr(b); } return 0; }
int main(int argc, const char * argv[]) { TYPE task1; TYPE task2; TYPE task3; TYPE task4; TYPE task5; TYPE task6; TYPE task7; TYPE task8; TYPE task9; TYPE task10; DynArr *mainList; mainList = createDynArr(10); /* create tasks */ task1 = createTask(9, "task 1"); task2 = createTask(3, "task 2"); task3 = createTask(2, "task 3"); task4 = createTask(4, "task 4"); task5 = createTask(5, "task 5"); task6 = createTask(7, "task 6"); task7 = createTask(8, "task 7"); task8 = createTask(6, "task 8"); task9 = createTask(1, "task 9"); task10 = createTask(0, "task 10"); /* add tasks to the dynamic array */ addHeap(mainList, task1, compare); addHeap(mainList, task2, compare); addHeap(mainList, task3, compare); addHeap(mainList, task4, compare); addHeap(mainList, task5, compare); addHeap(mainList, task6, compare); addHeap(mainList, task7, compare); addHeap(mainList, task8, compare); addHeap(mainList, task9, compare); addHeap(mainList, task10, compare); printf("Before Sort Called \n"); printDynArr(mainList, print_type); /* sort tasks */ sortHeap(mainList, compare); printf("After Sort Called \n"); /* print sorted tasks from the dynamic array */ printDynArr(mainList, print_type); return 0; }
/* Print the list param: heap pointer to the list pre: the list is not empty post: The tasks from the list are printed out in priority order. The tasks are not removed from the list. */ void printList(DynArr *heap) { /* FIXME: Write this */ struct DynArr *toPrint = createDynArr(sizeDynArr(heap)); copyDynArr(heap, toPrint); int i, max = sizeDynArr(toPrint); sortHeap(toPrint); // call print_type() on each node for(i = 0; i < max; i++) print_type(getDynArr(toPrint, i)); deleteList(toPrint); }
/* Resizes the underlying array to be the size cap param: v pointer to the dynamic array param: cap the new desired capacity pre: v is not null post: v has capacity newCap */ struct DynArr* _dynArrSetCapacity(struct DynArr *v, int newCap) { struct DynArr *temp = createDynArr(newCap); int x; temp->capacity = newCap; temp->size = v->size; for (x = 0; x < v->size; x++) { addDynArr(temp, v->data[x]); } return temp; }
/* Read the RPN string and carry out the operations param: numInputTokens is the number of tokens entered via command line param: inputString is the string of tokens pre: inputString is a valid string of Reverse polish Notation - supported operators +, -, x, / pre: numInputTokens is > 0 post: none ret: the size of the dynamic array */ double calculate(int numInputTokens, char **inputString) { double result = 0.0; char *s; struct DynArr *stack; /*set up the stack */ stack = createDynArr(20); int i; /* start at 1 to skip the name of the calculator calc */ for(i=1; i < numInputTokens; i++) { s = inputString[i]; /* General algorithm: 1) Check if the string 's' is in the list of operators 1 a) If 's' is an operator, then call the corresponding function 1 b) If 's' is not an operator, check if it is a number 2 a) If 's' is not a number, produce an error 2 b) If 's' is a number, push it onto the stack */ if(strcmp(s, "+") == 0){ add(stack); } else if(strcmp(s,"-") == 0){ subtract(stack); } else if(strcmp(s, "/") == 0){ /* FIXME: replace printf with your own function */ divide(stack); } else if(strcmp(s, "x") == 0){ /* FIXME: replace printf with your own function */ multiplie(stack); } else if(strcmp(s, "^") == 0){ /* FIXME: replace printf with your own function */ exponent(stack); } else { /* FIXME: You need to develop the code here (when s is not an operator )*/ printf("you did not give a math character\n"); } } //end for /* FIXME: You will write this part of the function If the stack looks OK, then store the final value in result Print the result */ return result; }
/* Print the list param: heap pointer to the list pre: the list is not empty post: The tasks from the list are printed out in priority order. The tasks are not removed from the list. */ void printList(DynArr *heap) { /* FIXME: Write this */ // create a new copy of the heap to prevent removal DynArr *tmpHeap = createDynArr(sizeDynArr(heap)); copyDynArr(heap, tmpHeap); while (sizeDynArr(tmpHeap) > 0) { // get first value of min priority TYPE min = getMinHeap(tmpHeap); print_type(min); removeMinHeap(tmpHeap); // remove min, to get next } freeDynArr(tmpHeap); }
int main(int argc, char* argv[]) { DynArr* b; int n, i; double t1, t2; #ifdef MEMORY_TEST_INCLUDED /* variables to hold memory used before and after creating DynArr */ long m1, m2; /* memory used BEFORE creating DynArr */ m1 = getMemoryUsage(); #endif if( argc != 2 ) return 0; b = createDynArr(1000); n = atoi(argv[1]); /*number of elements to add*/ for( i = 0 ; i < n; i++) { addDynArr(b, (TYPE)i); /*Add elements*/ } #ifdef MEMORY_TEST_INCLUDED /* memory used AFTER creating DynArr */ m2 = getMemoryUsage(); printf("Memory used by DynArr: %ld KB \n", m2-m1); #endif t1 = getMilliseconds();/*Time before contains()*/ for(i=0; i<n; i++) { containsDynArr(b, i); } t2 = getMilliseconds();/*Time after contains()*/ printf("Time for running contains() on %d elements: %g ms\n", n, t2-t1); /* delete DynArr */ deleteDynArr(b); return 0; }
/* Resizes the underlying array to be the size cap param: v pointer to the dynamic array param: cap the new desired capacity pre: v is not null post: v has capacity newCap */ void _dynArrSetCapacity(DynArr *v, int newCap) { /* FIXME: You will write this function */ assert(v!= 0); struct DynArr *newArr = createDynArr(newCap); int newSize = sizeDynArr(v); //same as v so all the data can transfer int i; for (i = 0; i<newSize; i++) { newArr->data[i] = v->data[i]; //transfer data from v to newArr } freeDynArr(v); v->capacity = newCap; //new capacity set for v v->size = newSize; v->data = malloc(sizeof(DynArr)*newCap); //v created with a new "size" aka capacity for (i = 0; i<newSize; i++) { v->data[i] = newArr->data[i]; //transfer data back into v with new capacity } deleteDynArr(newArr); //no longer needed }
/* Print the list param: heap pointer to the list pre: the list is not empty post: The tasks from the list are printed out in priority order. The tasks are not removed from the list. */ void printList(DynArr *heap) { DynArr *temp; TaskP task; assert(sizeDynArr(heap) > 0); temp = createDynArr(sizeDynArr(heap)); /* copy the main list to a temp list * so that tasks can be printed out and removed. */ copyDynArr(heap, temp); while(sizeDynArr(temp) > 0) { /* get the task */ task = getMinHeap(temp); /* print the task */ printf("%d: %s\n\n", task->priority, task->description); /* remove the task */ removeMinHeap(temp); } /* free the temp list */ deleteDynArr(temp); }
/* Print the list in priority order. This requires that either we sort it...or make a copy and pull off the smallest element one at a time. That's what we've done here. param: heap pointer to the list pre: the list is not empty post: The tasks from the list are printed out in priority order. The tasks are not removed from the list. */ void printList(DynArr *heap) { DynArr *temp; TaskP task; assert(sizeDynArr(heap) > 0); temp = createDynArr(sizeDynArr(heap)); /* copy the main list to a temp list * so that tasks can be printed out and removed. */ copyDynArr(heap, temp); while(sizeDynArr(temp) > 0) { /* get the task */ task = getMinHeap(temp); /* print the task */ printf("%d: %s\n\n", task->priority, task->description); /* remove the task , but let's not free up the memory it's pointing to since old Arr is using it!*/ removeMinHeap(temp, compare); } /* free the temp list */ deleteDynArr(temp); }
//Brute force/Divide and Conquer //To make change for A cents: //If there is a K-cent coin, then that one coin is the minimum //Otherwise, for each value i < K, //Find the minimum number of coins needed to make i cents //Find the minimum number of coins needed to make K - i cents //Choose the i that minimizes this sum DynArr * changeslow(DynArr *V, int A) { // Locals DynArr *MyCoins; // Return array of coin counts DynArr *countsAr; // Array of counts for each i DynArr *lower; // Return from lower half DynArr *upper; // Return from upper half DynArr *compiledAr[A]; // Array of pointers to each of the i solutions int i = 0; int j = 0; int iMin = 0; // Initialize the dynamic arrays that are // the size of V MyCoins = createDynArr(sizeDynArr(V)); lower = createDynArr(sizeDynArr(V)); upper = createDynArr(sizeDynArr(V)); for(i = 0; i < sizeDynArr(V); i++) { addDynArr(MyCoins, 0); addDynArr(lower, 0); addDynArr(upper, 0); } // Initialize the array that is used to hold all the i counts // Adding 1 to be able to loop from 1 in the main recursion loop countsAr = createDynArr(A + 1); for(i = 0; i < A + 1; i++) { addDynArr(countsAr, 0); } // Base case check if the A value has a coin // exactly equal to its value for(i = 0; i < sizeDynArr(V); i++) { if(getDynArr(V, i) == A) { putDynArr(MyCoins, i, getDynArr(MyCoins, i) + 1); putDynArr(countsAr, i, 1); return MyCoins; } } // Loop through all i from 1 to A and recurse on // A - i and A for(i = 1; i < A + 1; i++) { // Loop to pairwise sum the two for(j = 0; j < sizeDynArr(V); j++) { putDynArr(MyCoins, j, getDynArr(lower, j) + getDynArr(upper, j)); } // Loop to get the sum of the coins in MyCoins just created for(j = 0; j < sizeDynArr(MyCoins); j++) { putDynArr(countsAr, i, getDynArr(countsAr, i) + getDynArr(MyCoins, j)); } // Put the combined solution into the array of pointers compiledAr[i] = MyCoins; } // Find the minimum in the countsAr array for(i = 0; i < A + 1; i++) { if(iMin > getDynArr(countsAr, i)) iMin = i; } // Since we are using the i after the for we need to dec 1 return compiledAr[i -1]; }
int main(int argc, const char * argv[]) { Task *task1, *task2, *task3, *task4, *task5, *task6, *task7, *task8, *task9, *task10; Task *task11, *task12, *task13, *task14, *task15, *task16, *task17, *task18, *task19, *task20; DynArr *mainList; int i; mainList = createDynArr(10); /* create tasks */ task1 = createTask(9, "task 1"); task2 = createTask(3, "task 2"); task3 = createTask(2, "task 3"); task4 = createTask(4, "task 4"); task5 = createTask(5, "task 5"); task6 = createTask(7, "task 6"); task7 = createTask(8, "task 7"); task8 = createTask(6, "task 8"); task9 = createTask(1, "task 9"); task10 = createTask(10, "task 10"); task11 = createTask(19, "task 11"); task12 = createTask(13, "task 12"); task13 = createTask(12, "task 13"); task14 = createTask(14, "task 14"); task15 = createTask(15, "task 15"); task16 = createTask(17, "task 16"); task17 = createTask(18, "task 17"); task18 = createTask(16, "task 18"); task19 = createTask(3, "task 19"); task20 = createTask(110, "task 20"); /* add tasks to the dynamic array */ addHeap(mainList, task1); addHeap(mainList, task2); addHeap(mainList, task3); addHeap(mainList, task4); addHeap(mainList, task5); addHeap(mainList, task6); addHeap(mainList, task7); addHeap(mainList, task8); addHeap(mainList, task9); addHeap(mainList, task10); addHeap(mainList, task11); addHeap(mainList, task12); addHeap(mainList, task13); addHeap(mainList, task14); addHeap(mainList, task15); addHeap(mainList, task16); addHeap(mainList, task17); addHeap(mainList, task18); addHeap(mainList, task19); addHeap(mainList, task20); #ifdef TESTHEAP printf("Print heap\n"); for(i = 0; i < sizeDynArr(mainList);i++) print_type(getDynArr(mainList,i)); while(!isEmptyDynArr(mainList)) { TYPE v; v = getMinHeap(mainList); printf("Removing: "); print_type(v); removeMinHeap(mainList); for(i = 0; i < sizeDynArr(mainList);i++) print_type(getDynArr(mainList,i)); } #endif #ifdef TESTSORT printf("Before Sort Called \n"); for(i = 0; i < sizeDynArr(mainList);i++) printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority); /* sort tasks */ sortHeap(mainList); printf("After Sort Called \n"); /* print sorted tasks from the dynamic array */ for(i = 0; i < sizeDynArr(mainList);i++) printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority); return 0; #endif }
int main(int argc, char* argv[]){ DynArr *dyn; dyn = createDynArr(2); double a,b,c,d,e,f,g,h; a = 3; b = 4; c = 10; d = 6; e = 5; f = 20; printf("\n\nTesting addDynArr...\n"); addDynArr(dyn, a); addDynArr(dyn, b); addDynArr(dyn, c); addDynArr(dyn, d); addDynArr(dyn, e); printf("The array's content: [3,4,10,6,5]\n"); assertTrue(EQ(getDynArr(dyn, 0), a), "Test 1st element == 3"); assertTrue(EQ(getDynArr(dyn, 1), b), "Test 2nd element == 4"); assertTrue(EQ(getDynArr(dyn, 2), c), "Test 3rd element == 10"); assertTrue(EQ(getDynArr(dyn, 3), d), "Test 4th element == 5"); assertTrue(EQ(getDynArr(dyn, 4), e), "Test 5th element == 6"); assertTrue(sizeDynArr(dyn) == 5, "Test size = 5"); printf("\n\nTesting add...\nCalling addDynArr(dyn)\n"); add(dyn); printf("The array's content: [3,4,7,6,5]\n"); assertTrue(EQ(getDynArr(dyn, 3), (double)11), "Test 3rd element == 11"); assertTrue(sizeDynArr(dyn) == 4, "Test size = 4"); //removing result of add test and restoring array removeDynArr(dyn, 3); addDynArr(dyn, d); addDynArr(dyn, e); printf("\n\nTesting sub..."); subtract(dyn); printf("The array's content: [3,4,7,6,5]\n"); assertTrue(EQ(getDynArr(dyn, 3), (double)1), "Test 3rd element == 1"); assertTrue(sizeDynArr(dyn) == 4, "Test size = 4"); //printf("%d \n", sizeDynArr(dyn)); printf("Top: %f \n", topDynArr(dyn)); //removing result of add test and restoring array popDynArr(dyn); printf("Top: %f \n", topDynArr(dyn)); pushDynArr(dyn, f); pushDynArr(dyn, e); printf("Top: %f \n", topDynArr(dyn)); printf("\n\nTesting divide..."); divide(dyn); //printf("The array's content: [3,4,10,20,5]\n"); //assertTrue(EQ(getDynArr(dyn, 3),(double)4), "Test 3rd element == 4"); //assertTrue(sizeDynArr(dyn) == 4, "Test size = 4"); /* printf("At 4: %f \n", topDynArr(dyn)); removeDynArr(dyn,4); printf("At 3: %f \n", topDynArr(dyn)); removeDynArr(dyn,3); printf("At 2: %f \n", topDynArr(dyn)); removeDynArr(dyn,2); printf("At 1: %f \n", topDynArr(dyn)); printf("%d \n",sizeDynArr(dyn)); */ //removing result of add test and restoring array printf("\nTop: %f \n", topDynArr(dyn)); popDynArr(dyn); printf("Top: %f \n", topDynArr(dyn)); pushDynArr(dyn, f); pushDynArr(dyn, e); printf("Top: %f \n", topDynArr(dyn)); printf("\n\nTesting multiply...\nCalling addDynArr(dyn)\n"); multiply(dyn); //printf("The array's content: [3,4,10,6,5]\n"); //assertTrue(EQ(getDynArr(dyn, 3),(float)30), "Test 3rd element == 30"); //assertTrue(sizeDynArr(dyn) == (float)4, "Test size = 4"); printf("Before pop Top: %f \n", topDynArr(dyn)); //removing result of add test and restoring array popDynArr(dyn); printf("After pop Top: %f \n", topDynArr(dyn)); pushDynArr(dyn,(double) 2); pushDynArr(dyn,(double) 1); printf("After 2 push Top: %f \n", topDynArr(dyn)); printf("\n\nTesting power of...n"); powerOf(dyn); //printf("The array's content: [3,4,10,6,5]\n"); //assertTrue(EQ(getDynArr(dyn, 3),(float)2), "Test 3rd element == 2"); //assertTrue(sizeDynArr(dyn) == (float)4, "Test size = 4"); }
int main (int argc, const char * argv []) { TYPE newTask, firstTask; char desc [ TASK_DESC_SIZE ], filename [ 50 ], *nlptr; int priority; char cmd = ' '; FILE *filePointer; DynArr * mainList = createDynArr(10); printf("\n\n** TO-DO LIST APPLICATION **\n\n"); do { printf("Press:\n" "'l' to load to-do list from a file\n" "'s' to save to-do list to a file\n" "'a' to add a new task\n" "'g' to get the first task\n" "'r' to remove the first task\n" "'p' to print the list\n" "'e' to exit the program\n" ); /* get input command (from the keyboard) */ cmd = getchar(); /* clear the trailing newline character */ while( getchar() != '\n' ) ; switch( cmd ) { case 'a': /* add new task */ printf("Please enter the task description: "); /* get task description from user input (from keyboard) */ if( fgets(desc, sizeof( desc ), stdin) != NULL ) { /* remove trailing newline character */ nlptr = strchr(desc, '\n'); if( nlptr ) *nlptr = '\0'; } /* get task priority from user input (from keyboard) */ do { printf("Please enter the task priority (0-999): "); scanf("%d", &priority); } while( !( priority >= 0 && priority <= 999 ) ); /* clear the trailing newline character */ while( getchar() != '\n' ) ; /* create task and add the task to the heap */ newTask = createTask(priority, desc); addHeap(mainList, newTask); printf("The task '%s' has been added to your to-do list.\n\n", desc); break; case 'g': /* get the first task */ if( sizeDynArr(mainList) > 0 ) { firstTask = getMinHeap(mainList); printf("Your first task is: %s\n\n", firstTask.description); } else printf("Your to-do list is empty!\n\n"); break; case 'r': /* remove the first task */ if( sizeDynArr(mainList) > 0 ) { firstTask = getMinHeap(mainList); removeMinHeap(mainList); printf("Your first task '%s' has been removed from the list.\n\n", firstTask.description); } else printf("Your to-do list is empty!\n\n"); break; case 'p': /* print the list */ if( sizeDynArr(mainList) > 0 ) { printList(mainList); } else printf("Your to-do list is empty!\n\n"); break; case 's': /* save the list to file */ if( sizeDynArr(mainList) > 0 ) { /* get filename from user input (from keyboard) */ printf("Please enter the filename: "); if( fgets(filename, sizeof( filename ), stdin) != NULL ) { /* remove trailing newline character */ nlptr = strchr(filename, '\n'); if( nlptr ) *nlptr = '\0'; } /* open the file */ filePointer = fopen(filename, "w"); if( filePointer == NULL ) { fprintf(stderr, "Cannot open %s\n", filename); break; } /* save the list to the file */ saveList(mainList, filePointer); /* close the file */ fclose(filePointer); printf("The list has been saved into the file successfully.\n\n"); } else printf("Your to-do list is empty!\n\n"); break; case 'l': /* load the list from the file */ printf("Please enter the filename: "); /* get filename from user input (from keyboard) */ if( fgets(filename, sizeof( filename ), stdin) != NULL ) { /* remove trailing newline character */ nlptr = strchr(filename, '\n'); if( nlptr ) *nlptr = '\0'; } /* open the file */ filePointer = fopen(filename, "r"); if( filePointer == NULL ) { fprintf(stderr, "Cannot open %s\n", filename); break; } /* load the list from the file */ loadList(mainList, filePointer); /* close the file */ fclose(filePointer); printf("The list has been loaded from file successfully.\n\n"); break; case 'e': /* exit the program */ printf("Bye!\n\n"); break; default: printf("What is your command anyway?\n\n" ); break; } } while( cmd != 'e' ); /* delete the list */ deleteDynArr(mainList); return 0; }
double calculate(int numInputTokens, char **inputString) { int i; double result = 0.0; char *s; struct DynArr *stack; //for keeping track of # of operands and operators int numOfOperands = 0; int numOfOperators = 0; int check = 0; //set up the stack stack = createDynArr(20); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; if(strcmp(s, "+") == 0) { numOfOperators++; //increase for binary operators add(stack); } else if(strcmp(s,"-") == 0) { numOfOperators++; subtract(stack); } else if(strcmp(s, "/") == 0) { numOfOperators++; divide(stack); } else if(strcmp(s, "x") == 0) { numOfOperators++; multiply(stack); } else if(strcmp(s, "^") == 0) { numOfOperators = numOfOperators; //for unary operators don't increase power(stack); } else if(strcmp(s, "^2") == 0) { numOfOperators = numOfOperators; square(stack); } else if(strcmp(s, "^3") == 0) { numOfOperators = numOfOperators; cube(stack); } else if(strcmp(s, "abs") == 0) { numOfOperators = numOfOperators; absoluteValue(stack); } else if(strcmp(s, "sqrt") == 0) { numOfOperators = numOfOperators; squareRoot(stack); } else if(strcmp(s, "exp") == 0) { numOfOperators = numOfOperators; exponential(stack); } else if(strcmp(s, "ln") == 0) { numOfOperators = numOfOperators; naturalLog(stack); } else if(strcmp(s, "log") == 0) { numOfOperators = numOfOperators; logTen(stack); } else { //check if its a number (or pi or e) if(isNumber(s, &result)) { numOfOperands++; //increase count of operands pushDynArr(stack, result); //if it is push onto stack } else { printf("You entered bad characters, exiting!\n"); //else print error message exit(0); } } } //end for //check for correct balance of operands and operators //must be one more operand than operators in sequence check = numOfOperands - numOfOperators; //this must be equal to 1 for valid input if (check > 1) { printf("Illegal Input, too many operands or too few operators, exiting\n"); exit(0); } else if (check < 1) { printf("Illegal Input, too few operands or too many operators, exiting\n"); exit(0); } //if passed check store final result and return result = topDynArr(stack); return result; }
/*Bag Wrapper Interface*/ struct bag *createBag() { struct bag *myBag = malloc(sizeof(struct bag)); myBag->dynArr = createDynArr(20); return myBag; }
double calculate(int numInputTokens, char **inputString) { int i; double result = 0.0; char *s; struct DynArr *stack; //set up the stack stack = createDynArr(20); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; // Hint: General algorithm: // (1) Check if the string s is in the list of operators. // (1a) If it is, perform corresponding operations. // (1b) Otherwise, check if s is a number. // (1b - I) If s is not a number, produce an error. // (1b - II) If s is a number, push it onto the stack if(strcmp(s, "+") == 0) add(stack); else if(strcmp(s,"-") == 0) subtract(stack); else if(strcmp(s, "/") == 0) divide(stack); else if(strcmp(s, "x") == 0) /* FIXME: replace printf with your own function */ printf("Multiplying\n"); else if(strcmp(s, "^") == 0) /* FIXME: replace printf with your own function */ printf("Power\n"); else if(strcmp(s, "^2") == 0) /* FIXME: replace printf with your own function */ printf("Squaring\n"); else if(strcmp(s, "^3") == 0) /* FIXME: replace printf with your own function */ printf("Cubing\n"); else if(strcmp(s, "abs") == 0) /* FIXME: replace printf with your own function */ printf("Absolute value\n"); else if(strcmp(s, "sqrt") == 0) /* FIXME: replace printf with your own function */ printf("Square root\n"); else if(strcmp(s, "exp") == 0) /* FIXME: replace printf with your own function */ printf("Exponential\n"); else if(strcmp(s, "ln") == 0) /* FIXME: replace printf with your own function */ printf("Natural Log\n"); else if(strcmp(s, "log") == 0) /* FIXME: replace printf with your own function */ printf("Log\n"); else { // FIXME: You need to develop the code here (when s is not an operator) // Remember to deal with special values ("pi" and "e") } } //end for /* FIXME: You will write this part of the function (2 steps below) * (1) Check if everything looks OK and produce an error if needed. * (2) Store the final value in result and print it out. */ return result; }
int main(int argc, char **argv){ char *temps; char c; char *arName = ""; int verbose = 0; int nextArg = 0; int fd; int fileLen =0; char buffer[60]; int i =0; long j =0; int k =0; double tempSum; int fdDestination; char *fileBuffer = NULL; int num_read; int found[argc]; struct tm *time; struct ar_hdr header; struct dirent **namelist; struct arFiles arF; while ((c = getopt(argc, argv, "q:x:v:d:A:wt:")) != -1){ switch (c) { case 'q'://appends new file to end of archive arName = optarg; nextArg = optind; if(nextArg>=argc){ fprintf(stderr, "Too few arguments\nUsage: %s ar {qxvdAwt} archive-file file...\n", argv[0]); exit(EXIT_FAILURE); } openArchiveWrite(&fd, arName); lseek(fd,0, SEEK_END); while (nextArg<argc){ temps = argv[nextArg]; appendFile(fd, temps); nextArg++; } close(fd); break; case 'x'://extracts a file arName = optarg; nextArg = optind; openArchiveRead(&fd, arName); for(i = 0; i<argc;i++) found[i]=0; while (nextArg<argc){ while (getHeadder(fd, &header)){ temps = NULL; temps = strtok(header.ar_name, "/"); fileLen = atoi(header.ar_size); if(fileLen%2 != 0) fileLen++; if(strcmp(temps, argv[nextArg])==0){ tempSum=0; for(i=5;i>2;i--){//base conversion for modes buffer[0] = header.ar_mode[i]; buffer[1]= 0; tempSum += atoi(buffer)*pow(8.0,5-i); } //read archived file into memory fileLen = atoi(header.ar_size); fileBuffer = (char *)malloc(fileLen); num_read = read(fd, fileBuffer, fileLen); if (num_read < 0) { close(fd); perror("Error while reading the file to add to extract.\n"); exit(EXIT_FAILURE); } //create the archived file i = tempSum; fdDestination = open(temps, O_RDWR|O_CREAT, i); if(fdDestination<0){ free(fileBuffer); close(fd); perror("Error while creating the extracted file."); exit(EXIT_FAILURE); } //write the archived file to disk num_read = write(fdDestination, fileBuffer, fileLen); if (num_read < 0) { close(fd); perror("Error while writing the extracted file.\n"); exit(EXIT_FAILURE); } free(fileBuffer); close(fdDestination); break; } lseek(fd, fileLen, SEEK_CUR); } lseek(fd, 8, SEEK_SET); nextArg++; } close(fd); break; case 'v'://set verbose to 1 and cascade to -t verbose=1; case 't': arName = optarg; openArchiveRead(&fd, arName); while (getHeadder(fd, &header)){ if(verbose){//accounts for -v tempSum=0; for(i=5;i>2;i--){//convert mode base buffer[0] = header.ar_mode[i]; buffer[1]= 0; tempSum += atoi(buffer)*pow(8.0,5-i); } //write permissions filePerms(tempSum); //write GID/UID printf("%d/", atoi(header.ar_gid)); printf("%d ", atoi(header.ar_uid)); //store the size string k = atoi(header.ar_size); snprintf(buffer, 10, "%d", k); k= strlen(buffer); //ar displays 6 places for size unless larger than 6 places if(k<6){ j = 6; } else{ j = k;//if larger than 6 display up to 10 places (limit of .ar_size) } //print size right justified for(i=0;i<j;i++){ buffer[i] = (i+k<j)?' ': header.ar_size[(i+k-j)]; } buffer[j]= 0; printf("%s ", buffer); //convert time to tm struct and write custom formated time j = atoi(header.ar_date); time = localtime(&j); strftime(buffer, 60, "%b %e %H:%M %Y", time); printf("%s ",buffer); } //the first token indicated by / is the file name temps = strtok(header.ar_name, "/"); printf("%s\n",temps); //move the file pointer to where the next header should exist fileLen = atoi(header.ar_size); if(fileLen%2 != 0) fileLen++; lseek(fd, fileLen, SEEK_CUR); } close(fd); break; case 'd'://removes a file from the archive arName = optarg; nextArg = optind; openArchiveRead(&fd, arName); //find all locations to delete while (nextArg<argc){ while (getHeadder(fd, &header)){ temps = NULL; temps = strtok(header.ar_name, "/"); fileLen = atoi(header.ar_size); if(fileLen%2 != 0) fileLen++; if(strcmp(temps, argv[nextArg])==0){ found[nextArg] = 1; break; } lseek(fd, fileLen, SEEK_CUR); } lseek(fd, 8, SEEK_SET); nextArg++; } //check to see if at least one file was found k=0; for(i=0;i<argc;i++) k = (k|found[i]); if(k){//get each file info char *fileData; struct DynArr *fileArray; fileArray = createDynArr(10); while (getHeadder(fd, &header)){ fileLen = atoi(header.ar_size); if(fileLen%2 != 0) fileLen++; fileData = (char *)malloc(fileLen+60); lseek(fd, -60, SEEK_CUR); num_read = read(fd, fileData, fileLen+60); if (num_read < 0) { close(fd); perror("Error while reading the archive prior to delete.\n"); exit(EXIT_FAILURE); } //add filedata to array arF.fileName = (char *)malloc(15); char *temp = strtok(header.ar_name, "/"); strncpy(arF.fileName, temp, 15); arF.fileSize = fileLen+60; arF.file = fileData; addDynArr(fileArray, arF); } //close the current file and re-open it deleting it's contents close(fd); openArchiveDelete(&fd, arName); //iterate through each file saved in fileArray int numFiles = sizeDynArr(fileArray); for(i=0;i<numFiles;i++){ arF = getDynArr(fileArray, i); for(k=0;k<argc;k++){ if(found[k] && (strcmp(arF.fileName, argv[k])==0)){ found[k] = 0;//turn off the found flag to stop searching after the first file is found k=argc+1;// break out of the loop } } //if k==argc then the file was not on the list to be deleted so write it if(k==argc){ num_read = write(fd, arF.file, arF.fileSize); if (num_read < 0) { close(fd); perror("Error while writing the updated archive file.\n"); exit(EXIT_FAILURE); } } } deleteDynArr(fileArray); close(fd); } else{ close(fd); } break; case 'A'://most of the code for getting the file listing comes from the scandir man page arName = optarg; k = scandir(".", &namelist, NULL, alphasort); if(k<0){ perror("Failed to get directory listing."); exit(EXIT_FAILURE); } openArchiveWrite(&fd, arName); lseek(fd,0, SEEK_END); for(i =0;i<k;i++){ if((strcmp(namelist[i]->d_name, arName)!=0)&&namelist[i]->d_type== DT_REG){ appendFile(fd, namelist[i]->d_name); } } close(fd); free(namelist); break; case 'w': break; default: fprintf(stderr, "Usage: %s ar {qxvdAwt} archive-file file...\n", argv[0]); exit(EXIT_FAILURE); } } return 0; }
int main(int argc, const char * argv[]) { Task *task1, *task2, *task3, *task4, *task5, *task6, *task7, *task8, *task9, *task10; DynArr *mainList; int i; mainList = createDynArr(10); /* create tasks */ task1 = createTask(9, "task 1"); task2 = createTask(3, "task 2"); task3 = createTask(2, "task 3"); task4 = createTask(4, "task 4"); task5 = createTask(5, "task 5"); task6 = createTask(7, "task 6"); task7 = createTask(8, "task 7"); task8 = createTask(6, "task 8"); task9 = createTask(1, "task 9"); task10 = createTask(0, "task 10"); /* add tasks to the dynamic array */ addHeap(mainList, task1); addHeap(mainList, task2); addHeap(mainList, task3); addHeap(mainList, task4); addHeap(mainList, task5); addHeap(mainList, task6); addHeap(mainList, task7); addHeap(mainList, task8); addHeap(mainList, task9); addHeap(mainList, task10); #ifdef TESTHEAP for(i = 0; i < sizeDynArr(mainList);i++) printf("DynArr[%d] = %d\n", i, getDynArr(mainList,i).priority); while(!isEmptyDynArr(mainList)) { TYPE v; v = getMinHeap(mainList); printf("Val = %s ___%d\n", v->description, v->priority); removeMinHeap(mainList); } #endif #ifdef TESTSORT printf("Before Sort Called \n"); for(i = 0; i < sizeDynArr(mainList);i++) printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority); /* sort tasks */ sortHeap(mainList); printf("After Sort Called \n"); /* print sorted tasks from the dynamic array */ for(i = 0; i < sizeDynArr(mainList);i++) printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority); return 0; #endif }
int main (int argc, const char * argv[]) { char cmd = ' '; int priority; char str [256]; DynArr* mainList = createDynArr(10); FILE *fp; printf("\n\n** TO-DO LIST APPLICATION **\n\n"); do { printf("Press:\n" "'l' to load to-do list from a file\n" "'s' to save to-do list to a file\n" "'a' to add a new task\n" "'g' to get the first task\n" "'r' to remove the first task\n" "'p' to print the list\n" "'e' to exit the program\n" ); /* get input command (from the keyboard) */ cmd = getchar(); /* clear the trailing newline character */ while (getchar() != '\n'); switch(cmd){ case 'l': //load fp = fopen("todo.txt", "r"); if(fp == NULL){ printf("error opening file\n"); } loadList(mainList, fp); fclose(fp); printf("List is loaded!\n"); break; case 's': //save fp = fopen("todo.txt", "w"); if(fp == NULL){ printf("Error opening file!\n"); } saveList(mainList, fp); fclose(fp); printf("List is saved!\n"); break; case 'a': printf("Enter a description: "); fgets(str, 256, stdin); if ((strlen(str)>0) && (str[strlen (str) - 1] == '\n')) str[strlen (str) - 1] = '\0'; printf("Enter the priority: "); scanf("%d", &priority); TYPE taskTemp = createTask(priority, str); addHeap(mainList, taskTemp, compare); printf("Item added! \n\n"); while (getchar() != '\n'); break; case 'g': if(sizeDynArr(mainList) > 0){ print_type(getMinHeap(mainList)); }else{ printf("List is empty!\n"); } break; case 'r': if(sizeDynArr(mainList) > 0){ removeMinHeap(mainList, compare); }else{ printf("No items in list!\n"); } break; case 'p': if(sizeDynArr(mainList) > 0){ printList(mainList); }else{ printf("List has no items!\n"); } break; case 'e': break; default: printf("Please enter a proper value!\n"); break; } } while(cmd != 'e'); /* delete the list */ deleteDynArr(mainList); return 0; }
/* param: integer size of input and char pre: argc is not equal to 1 post: the final number is calculated without errors. */ double calculate(int numInputTokens, char **inputString) { int i; double result = 0.0; char *s; struct DynArr *stack; //set up the stack stack = createDynArr(20); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; if (strcmp(s, "+") == 0) // add { if (sizeDynArr(stack) >= 2) // make sure stack has two numbers to add together { add(stack); } else { printf("Not enough numbers. %s is causing an error. Exiting.\n", s); exit(0); } } else if (strcmp(s, "-") == 0) // subtract { if (sizeDynArr(stack) >= 2) // make sure stack has two numbers to subtract together { subtract(stack); } else { printf("Not enough numbers. %s is causing an error. Exiting.\n", s); exit(0); } } else if (strcmp(s, "/") == 0) // divide { if (sizeDynArr(stack) >= 2) // make sure stack has two numbers to divide together { divide(stack); } else { printf("Not enough numbers. %s is causing an error. Exiting.\n", s); exit(0); } } else if (strcmp(s, "x") == 0) // multiply { if (sizeDynArr(stack) >= 2) // make sure stack has two numbers to multiply together { multiply(stack); } else { printf("Not enough numbers. %s is causing an error. Exiting.\n", s); exit(0); } } else if (strcmp(s, "^") == 0) // calculate power { if (sizeDynArr(stack) >= 2) // make sure stack has two numbers to use for power { power(stack); } else { printf("Not enough numbers. %s is causing an error. Exiting.\n", s); exit(0); } } else if (strcmp(s, "^2") == 0) // calculate square { square(stack); } else if (strcmp(s, "^3") == 0) // calculate cube { cube(stack); } else if (strcmp(s, "abs") == 0) // calculate absolute { absolute(stack); } else if (strcmp(s, "sqrt") == 0) // calculate square root { squareRoot(stack); } else if (strcmp(s, "exp") == 0) // calculate exponetial { exponential(stack); } else if (strcmp(s, "ln") == 0) // calculate natural log { naturalLog(stack); } else if (strcmp(s, "log") == 0) // get log { baseTenLog(stack); } else { if (strcmp(s, "pi") == 0) // convert pi to a number { s = "3.14159265"; } else if (strcmp(s, "e") == 0) // convert e to a number { s = "2.7182818"; } if (isNumber(s, &result) != 0) // if a number see if you can push on stack { pushDynArr(stack, result); } else // exit if not a number { printf("Error. Following input causing an error: %s \n", s); exit (0); } } } assert(!isEmptyDynArr(stack)); // check to make sure stack isn't empty if (sizeDynArr(stack) > 1) { printf("Not enough operators. Too many numbers. "); for (int i = 1; i < numInputTokens; i++) { printf("%s ", inputString[i]); } printf(" \n"); exit(0); } result = topDynArr(stack); // get final number and make it it result return result; }
double calculate(int numInputTokens, char **inputString) { int i; double result = 0.0; char *s; struct DynArr *stack; //set up the stack stack = createDynArr(20); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; // Hint: General algorithm: // (1) Check if the string s is in the list of operators. // (1a) If it is, perform corresponding operations. // (1b) Otherwise, check if s is a number. // (1b - I) If s is not a number, produce an error. // (1b - II) If s is a number, push it onto the stack if(strcmp(s, "+") == 0) add(stack); else if(strcmp(s,"-") == 0) subtract(stack); else if(strcmp(s, "/") == 0) divide(stack); else if(strcmp(s, "x") == 0) time(stack); else if(strcmp(s, "^") == 0) power(stack); else if(strcmp(s, "^2") == 0) /* FIXME: replace printf with your own function */ squaring(stack); else if(strcmp(s, "^3") == 0) /* FIXME: replace printf with your own function */ cubing(stack); else if(strcmp(s, "abs") == 0) /* FIXME: replace printf with your own function */ myAbs(stack); else if(strcmp(s, "sqrt") == 0) /* FIXME: replace printf with your own function */ squareRoot(stack); else if(strcmp(s, "exp") == 0) /* FIXME: replace printf with your own function */ exponential(stack); else if(strcmp(s, "ln") == 0) /* FIXME: replace printf with your own function */ naturalLog(stack); else if(strcmp(s, "log") == 0) /* FIXME: replace printf with your own function */ baseLog(stack); else { // FIXME: You need to develop the code here (when s is not an operator) // Remember to deal with special values ("pi" and "e") double *tmp = (double *)malloc(sizeof(double)); if (isNumber(s, tmp)) pushDynArr(stack, *tmp); else if(strcmp(s, "pi") == 0) pushDynArr(stack, 3.14159265); else if(strcmp(s, "e") == 0) pushDynArr(stack, 2.7182818); else flag = 0; } } //end for /* FIXME: You will write this part of the function (2 steps below) * (1) Check if everything looks OK and produce an error if needed. * (2) Store the final value in result and print it out. */ if (sizeDynArr(stack) != 1) printf("There is an error in your input !\n"); else { if (flag) { result = topDynArr(stack); popDynArr(stack); printf("The result is : %f\n", result); } else printf("There is an error in your input !\n"); } return result; }
// this main function contains some int main(int argc, char* argv[]){ DynArr *dyn; dyn = createDynArr(2); printf("\n\nTesting addDynArr...\n"); addDynArr(dyn, 3); addDynArr(dyn, 4); addDynArr(dyn, 10); addDynArr(dyn, 5); addDynArr(dyn, 6); printf("The array's content: [3,4,10,5,6]\n"); assertTrue(EQ(getDynArr(dyn, 0), 3), "Test 1st element == 3"); assertTrue(EQ(getDynArr(dyn, 1), 4), "Test 2nd element == 4"); assertTrue(EQ(getDynArr(dyn, 2), 10), "Test 3rd element == 10"); assertTrue(EQ(getDynArr(dyn, 3), 5), "Test 4th element == 5"); assertTrue(EQ(getDynArr(dyn, 4), 6), "Test 5th element == 6"); assertTrue(sizeDynArr(dyn) == 5, "Test size = 5"); printf("\n\nTesting putDynArr...\nCalling putDynArr(dyn, 2, 7)\n"); putDynArr(dyn, 2, 7); printf("The array's content: [3,4,7,5,6]\n"); assertTrue(EQ(getDynArr(dyn, 2), 7), "Test 3rd element == 7"); assertTrue(sizeDynArr(dyn) == 5, "Test size = 5"); printf("\n\nTesting swapDynArr...\nCalling swapDynArr(dyn, 2, 4)\n"); swapDynArr(dyn, 2, 4); printf("The array's content: [3,4,6,5,7]\n"); assertTrue(EQ(getDynArr(dyn, 2), 6), "Test 3rd element == 6"); assertTrue(EQ(getDynArr(dyn, 4), 7), "Test 5th element == 7"); printf("\n\nTesting removeAtDynArr...\nCalling removeAtDynArr(dyn, 1)\n"); removeAtDynArr(dyn, 1); printf("The array's content: [3,6,5,7]\n"); assertTrue(EQ(getDynArr(dyn, 0), 3), "Test 1st element == 3"); assertTrue(EQ(getDynArr(dyn, 3), 7), "Test 4th element == 7"); assertTrue(sizeDynArr(dyn) == 4, "Test size = 4"); printf("\n\nTesting stack interface...\n"); printf("The stack's content: [3,6,5,7] <- top\n"); assertTrue(!isEmptyDynArr(dyn), "Testing isEmptyDynArr"); assertTrue(EQ(topDynArr(dyn), 7), "Test topDynArr == 7"); popDynArr(dyn); printf("Poping...\nThe stack's content: [3,6,5] <- top\n"); assertTrue(EQ(topDynArr(dyn), 5), "Test topDynArr == 5"); pushDynArr(dyn, 9); printf("Pushing 9...\nThe stack's content: [3,6,5,9] <- top\n"); assertTrue(EQ(topDynArr(dyn), 9), "Test topDynArr == 9"); printf("\n\nTesting bag interface...\n"); printf("The bag's content: [3,6,5,9]\n"); assertTrue(containsDynArr(dyn, 3), "Test containing 3"); assertTrue(containsDynArr(dyn, 6), "Test containing 6"); assertTrue(containsDynArr(dyn, 5), "Test containing 5"); assertTrue(containsDynArr(dyn, 9), "Test containing 9"); assertTrue(!containsDynArr(dyn, 7), "Test not containing 7"); removeDynArr(dyn, 3); printf("Removing 3...\nThe stack's content: [6,5,9]\n"); assertTrue(!containsDynArr(dyn, 3), "Test not containing 3"); printf("Executing test functions...\n"); printf("\nTesting addDynArr()\n"); addDynArr_TEST(dyn); //Testing the add functionality under 3 conditions printf("\nTesting popDynArr()\n"); popDynArr_TEST(dyn); //Testing the pop function under 2 conditions printf("\nTesting topDynArr()\n"); topDynArr_TEST(dyn); //Testing the top function under 2 conditions printf("\nTesting pushDynArr()\n"); pushDynArr_TEST(dyn); //Testing the push function under 3 conditions printf("\nTesting containsDynArr()\n"); containsDynArr_TEST(dyn); //Testing the contains function under 2 conditions printf("\nTesting removeDynArr()\n"); removeDynArr_TEST(dyn); //Testing the remove function under 2 conditions return 0; }
double calculate(int numInputTokens, char **inputString) { int i, limit=0; double result = 0.0; char *s; struct DynArr *stack; //set up the stack stack = createDynArr(20); printf("testing info! numInputTOkesn: %d\n", numInputTokens); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; // Hint: General algorithm: // (1) Check if the string s is in the list of operators. // (1a) If it is, perform corresponding operations. // (1b) Otherwise, check if s is a number. // (1b - I) If s is not a number, produce an error. // (1b - II) If s is a number, push it onto the stack if(strcmp(s, "+") == 0){ add(stack); limit = 0; } else if(strcmp(s,"-") == 0){ subtract(stack); limit = 0; } else if(strcmp(s, "/") == 0){ divide(stack); limit = 0; } else if(strcmp(s, "x") == 0){ multiply(stack); limit = 0; } else if(strcmp(s, "^") == 0){ power(stack); limit = 0; } else if(strcmp(s, "^2") == 0){ square(stack); limit = 0; } else if(strcmp(s, "^3") == 0 ){ cube(stack); limit = 0; } else if(strcmp(s, "abs") == 0){ abso(stack); limit = 0; } else if(strcmp(s, "sqrt") == 0){ sqf(stack); limit = 0; } else if(strcmp(s, "exp") == 0){ expo(stack); limit = 0; } else if(strcmp(s, "ln") == 0){ logg(stack); limit = 0; } else if(strcmp(s, "log") == 0){ logg10(stack); limit = 0; } else { if(limit >=2){ printf("\nLimit has been reached! You did something wrong!\n"); break; } //printf("%c is not an operator! converting to a a number!\n",*s); int isNum; double num = 0; isNum = isNumber(s, &num); if(isNum == 1){ //Is infact a number, push to stack pushDynArr(stack, num); limit++; //printf("value %f is now pushed to the statck\n", num); printf("\n%f", num); }else{ if(strcmp(s, "pi") == 0){ pushDynArr(stack, 3.144159265); printf("\n3.144159265"); limit++; }else if(strcmp(s, "e") == 0){ pushDynArr(stack, 2.7182818); limit++; printf("\n2.7182818"); }else{ //ignore because it is not a number printf("\nPosition %d is not a number, ignoring...\n", i+1); } } //limit is more than 2, this should not happen! // Remember to deal with special values ("pi" and "e") } } //end for /* FIXME: You will write this part of the function (2 steps below) * (1) Check if everything looks OK and produce an error if needed. * (2) Store the final value in result and print it out. */ if( stack->size > 1){ //something went wrong printf("\nError computing value, check your entry!\n"); }else{ result = topDynArr(stack); } return result; }
double calculate(int numInputTokens, char **inputString){ int i; double result = 0.0; char *s; struct DynArr *stack; double num; //set up the stack stack = createDynArr(20); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; // Hint: General algorithm: // (1) Check if the string s is in the list of operators. // (1a) If it is, perform corresponding operations. // (1b) Otherwise, check if s is a number. // (1b - I) If s is not a number, produce an error. // (1b - II) If s is a number, push it onto the stack if(strcmp(s, "+") == 0){ add(stack); printf("Adding\n"); } else if(strcmp(s,"-") == 0){ subtract(stack); printf("Subtracting\n"); } else if(strcmp(s, "/") == 0){ divide(stack); printf("Dividing\n"); } else if(strcmp(s, "x") == 0){ multiply(stack); printf("Multiplying\n"); } else if(strcmp(s,"^") == 0){ power(stack); printf("Power\n"); } else if(strcmp(s, "^2") == 0){ squared(stack); printf("Squaring\n"); } else if(strcmp(s, "^3") == 0){ cubed(stack); printf("Cubing\n"); } else if(strcmp(s, "abs") == 0){ absoluteValue(stack); printf("Absolute value\n"); } else if(strcmp(s, "sqrt") == 0){ squareRoot(stack); printf("Square root\n"); } else if(strcmp(s, "exp") == 0){ exponential(stack); printf("Exponential\n"); } else if(strcmp(s, "ln") == 0){ naturalLog(stack); printf("Natural Log\n"); } else if(strcmp(s, "log") == 0){ logBase10(stack); printf("Log\n"); } else{ // FIXME: You need to develop the code here (when s is not an operator) // Remember to deal with special values ("pi" and "e") //check if not a number if (isNumber(s, &num) == 0){ if (strcmp(s, "pi") == 0){ num = 3.14159265; } else if (strcmp(s, "e") == 0){ num = 2.7182818; } else{ //wrong printf("%s is not valid (number or operator) \n", s); break; } } pushDynArr(stack, num); } } //end for /* FIXME: You will write this part of the function (2 steps below) * (1) Check if everything looks OK and produce an error if needed. * (2) Store the final value in result and print it out. */ if (sizeDynArr(stack) != 1) { printf("Incorrect count of numbers is detected! Calculations CANNOT be preformed. "); return 0; } else { result = topDynArr(stack); } return result; }
int main(int argc, const char * argv[]) { char cmd = ' '; DynArr* mainList = createDynArr(10); char filename[100]; //filename buffer FILE* file = NULL; //input/output file printf("\n\n** TO-DO LIST APPLICATION **\n\n"); do { printf("Press:\n" "'l' to load to-do list from a file\n" "'s' to save to-do list to a file\n" "'a' to add a new task\n" "'g' to get the first task\n" "'r' to remove the first task\n" "'p' to print the list\n" "'e' to exit the program\n" ); /* get input command (from the keyboard) */ cmd = getchar(); /* clear the trailing newline character */ while (getchar() != '\n'); switch (cmd) { case 'l': { //get filename printf("Enter filename: "); scanf("%s", filename); getchar(); //if a file is already open, then close it if (file != NULL) { fclose(file); } file = fopen(filename, "r"); //open the file for reading if (file != NULL) //if the file was opened sucessfully... { //empty the main list if (!isEmptyDynArr(mainList)) { int size = sizeDynArr(mainList); for (int i = 0; i < size; i++) { removeMinHeap(mainList, compare); } } //load the file and print a confirmation loadList(mainList, file); printf("List has been loaded.\n\n"); } else //otherwise print and error message { printf("Could not open file.\n\n"); } break; } case 's': { //get filename printf("Enter filename: "); scanf("%s", filename); getchar(); file = fopen(filename, "w"); //open the file for writing if (file != NULL) //if the file was opened sucessfully { //save the list and print a confirmation saveList(mainList, file); printf("List has been saved.\n\n"); } else //otherwise print an error message { printf("Could not create file.\n\n"); } break; } case 'a': { int priority; //stores the task priority char desc[100]; //sotres the task description //get the task description printf("Enter a brief description: "); fgets(desc, 100, stdin); desc[strcspn(desc, "\n")] = 0; //removes trailing newline character //get the task priority printf("Enter a task priority (0-999): "); scanf("%d", &priority); getchar(); TYPE newTask = createTask(priority, desc); //create a new task addHeap(mainList, newTask, compare); //add that taks to the heap printf("The task '%s' has been added to your list.\n\n", desc); //print a confirmation break; } case 'g': { if (!isEmptyDynArr(mainList)) //make sure the list is not empty { struct Task* task = (struct Task*)getMinHeap(mainList); //get the value at the heap's root node printf("Your first task is: %s\n\n", task->description); //print the description of that value } else { printf("Your to-do list is empty!\n\n"); } break; } case 'r': { if (!isEmptyDynArr(mainList)) //make sure the heap is not empty { struct Task* task = (struct Task*)getMinHeap(mainList); //get the value at the heap's root node printf("Your first task '%s' has been removed from the list.\n\n", task->description); //print the description of that value removeMinHeap(mainList, compare); //remove that value from the heap free(task); task = NULL; } else { printf("The list is empty.\n\n"); } break; } case 'p': { if (!isEmptyDynArr(mainList)) //make sure the heap is not empty { printList(mainList); //then print the contents of the heap from highest to lowest priority } else { printf("The list is empty.\n\n"); } break; } case 'e': { //if a file has been opened, then close that file if (file != NULL) { fclose(file); } break; } default: break; } /* Note: We have provided functions called printList(), saveList() and loadList() for you to use. They can be found in toDoList.c */ } while (cmd != 'e'); /* delete the list */ deleteDynArr(mainList); return 0; }
int main (int argc, const char * argv[]) { char cmd[1] = " "; char filename[128]; FILE *a_file; int priority; char task[128]; struct Task * tempTask; DynArr* mainList = createDynArr(10); printf("\n\n** TO-DO LIST APPLICATION **\n\n"); do { printf("Press:\n" "'l' to load to-do list from a file\n" "'s' to save to-do list to a file\n" "'a' to add a new task\n" "'g' to get the first task\n" "'r' to remove the first task\n" "'p' to print the list\n" "'e' to exit the program\n" ); /* get input command (from the keyboard) */ scanf("%s", cmd); /* clear the trailing newline character */ while (getchar() != '\n'); /* Fixme: Your logic goes here! */ if(cmd[0] == 'l'){ printf("Please enter a file name to load:"); scanf("%s", filename); a_file = fopen(filename, "r"); loadList(mainList, a_file); printf("File loaded\n"); } else if(cmd[0] == 's'){ printf("Please enter the file name:"); scanf("%s", filename); a_file = fopen(filename, "w"); saveList(mainList, a_file); printf("File saved.\n"); } else if(cmd[0] == 'a'){ printf("Please enter the task name: "); scanf("%s", task); printf("Please enter the task priority: "); scanf("%d", &priority); tempTask = createTask(priority, task); addHeap(mainList, tempTask, compare); } else if(cmd[0] == 'g'){ if (sizeDynArr(mainList) > 0){ tempTask = getMinHeap(mainList); printf("The first task on the list is: %s\n", tempTask->description); } else printf("Your to-do list is empty.\n"); } else if(cmd[0] == 'r'){ if (sizeDynArr(mainList) > 0){ tempTask = getMinHeap(mainList); removeMinHeap(mainList, compare); printf("The first task (%s) has been removed from the list.\n", tempTask->description); free(tempTask); } else printf("Your to-do list is empty, so nothing was removed.\n"); } else if(cmd[0] == 'p'){ if (sizeDynArr(mainList) > 0){ printDynArr(mainList, print_type); } else printf("Your to-do list is empty.\n"); } } while(cmd[0] != 'e'); /* Note: We have provided functions called printList(), saveList() and loadList() for you to use. They can be found in toDoList.c */ /* delete the list */ deleteDynArr(mainList); return 0; }