Beispiel #1
0
void p1(void)
{
    int i,n;
    struct Data d[MaxHeapSize-1];
    struct Data tempD;
    int A[]={5,2,8,6,1,9,21,42,0};
    struct Queue * pQ;
    struct Heap * mH=initMinHeap();
    initQueue(&pQ);

    for (i=0; i<MaxHeapSize-1; i++) {
        d[i].data=A[i];
    }
    for (i=0; i<MaxHeapSize-1; i++) {
        insertMinHeap(mH,d[i]);
    }
    for (i=0; i<MaxHeapSize-1; i++) {
        tempD=removeMinHeap(mH);
        enqueue(pQ, tempD);
    }
    printf("Elements in the priority queue are:");
    while (isEmpty(pQ)!=1) {
        dequeue(pQ, &tempD);
        printf(" %d ", tempD.data);
    }
    printf("\n");
    freeQueue(pQ);
    freeMinHeap(mH);
}
Beispiel #2
0
void ptest(void)
{
    int i,n;
    struct Data d[MaxHeapSize-1];
    struct Data tempD;
    int A[]={5,2,8,6,1,9,21,42,0};
    struct Heap * mH=initMinHeap();
    for (i=0; i<MaxHeapSize-1; i++) {
        d[i].data=A[i];
    }
    for (i=0; i<MaxHeapSize-1; i++) {
        insertMinHeap(mH,d[i]);
    }
    printf("count: %d \n", mH->count);
    for (i=0; i<MaxHeapSize-1; i++){
        printf("popped data: %d ", (removeMinHeap(mH)).data);
        printf("\n");
        for(n=0; n<MaxHeapSize; n++){
            printf("%d \n", mH->heapArray[n].data.data);
        }
        printf("------------------------------");
        printf("\n");
    }
    free(mH);
}
/*  Delete the list

    param:  heap    pointer to the list
    post:   The tasks from the list are removed and their occupied memories are freed

*/
void deleteList(DynArr *heap)
{

	Task* task;
	while(sizeDynArr(heap) > 0)
	{
	  	/* get the task */
		task = getMinHeap(heap);
		/* remove the task */
		removeMinHeap(heap);
		/* free the task */
		free(task);
	}
	/* free the heap */
	deleteDynArr(heap);
}
Beispiel #4
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 */

  // 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);
}
Beispiel #5
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)
{
    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);
}
Beispiel #6
0
/*  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);
}
Beispiel #7
0
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;
}
Beispiel #8
0
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
}
Beispiel #9
0
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;
}
Beispiel #10
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
}
Beispiel #11
0
Datei: main.c Projekt: dot1q/Misc
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;
}
Beispiel #12
0
int main() {
    struct task task1, task2, task3, task4, task5, task6, task7, task8, task9, task10;
	struct DynArr taskList;
	initDynArr(&taskList, 10);

    /* create tasks */
	task1 = createTask(10, "Clean house");
	task2 = createTask(6, "Eat dinner");
	task3 = createTask(2, "Do laundry");
	task4 = createTask(4, "Do dishes");
	task5 = createTask(5, "Grocery shopping");
	task6 = createTask(7, "Change oil");
	task7 = createTask(13, "Do taxes");
	task8 = createTask(8, "Sleep");
	task9 = createTask(1, "Do other homework");
	task10 = createTask(0, "Finish heap homework");

	/* add tasks to the dynamic array */
	addHeap(&taskList, task1);
	addHeap(&taskList, task2);
	addHeap(&taskList, task3);
	addHeap(&taskList, task4);
	addHeap(&taskList, task5);
	addHeap(&taskList, task6);
	addHeap(&taskList, task7);
	addHeap(&taskList, task8);
	addHeap(&taskList, task9);
	addHeap(&taskList, task10);

	printf("Beginning testing... \n");

  /* Should print: heap size: 10 */
  printf("heap size: %d \n", sizeDynArr(&taskList));

  /* Should print - Priority: 0 - Description: Finish heap homework */
  printTask(getMinHeap(&taskList));

  /* Remove top node from head */
	removeMinHeap(&taskList);

  /* Should print - Priority: 1 - Do other homework */
	printTask(getMinHeap(&taskList));

	int i;
	printf("printing heap... \n");
	/* Should print - 1 2 6 4 5 7 13 10 8 9 */
	for(i = 0; i <sizeDynArr(&taskList);i++) {
        printf("%d ", getDynArr(&taskList, i).priority);
	}
	printf("\n");

    /* Sort heap */
	sortHeap(&taskList);

    printf("printing sorted heap... \n");
    /* Should print (without descriptions) : 1, 2, 4, 5, 6, 7, 8, 10, 13 */
		/*Not sure how to both print "Priority: 1 - Do Other homework" like you asked
			above and in this order ascending, using the same function.
			Doesn't really make sense.*/
	for (i = 0; i < taskList.size; i++)	{
	  	printTask(getDynArr(&taskList, i));
	}
    printf("\n");

	return 0;
}
Beispiel #13
0
int main (int argc, const char * argv[])
{
	const long size = atoi(argv[1]);
  	TYPE *task = (TYPE*)malloc(sizeof(TYPE)*size*2);
	int *flip = (int*)malloc(sizeof(int)*size*2);
	DynArr mainList;
	long i;
	struct skipList skippy;
	printf("Enter\n");
	initDynArr(&mainList, 10000000);	/*Avoid effects of resizing*/
	initSkipList(&skippy);
	/* create tasks */
	for(i=0;i<size*2; i++)
	{
		task[i] = createTask(rand(), "r");
		flip[i] = rand()%2;
	}
	
		
	/* add tasks to the dynamic array */
	
	for(i=0;i<size; i++)
	{
		addHeap(&mainList, task[i]);
		addSkipList(&skippy, task[i]);
	}
	
	
	
	long start = clock();
	long finish = clock();
	
	long add = 0;
	long remove = 0;
	long cnt_add = 0;
	long cnt_remove = 0;
	long sadd = 0;
	long sremove = 0;
	long scnt_add = 0;
	long scnt_remove = 0;
	for(i=0;i<size*2; i++)
	{
		if(flip[i])
		{
			start = clock();
			addHeap(&mainList, task[i]);
			finish = clock();
			add += (finish-start);
			cnt_add++;
			start = clock();
			addSkipList(&skippy, task[i]);
			finish = clock();
			sadd += (finish-start);
			scnt_add++;
		}
		else
		{
			start = clock();
			removeMinHeap(&mainList);
			finish = clock();
			remove += (finish-start);
			cnt_remove++;
			start = clock();
			removeMinSkipList(&skippy);
			finish = clock();
			sremove += (finish-start);
			scnt_remove++;
		}
	}
	
	printf("Below are the average runtimes for a given number of operations.\n");
	printf("----HEAP----\n");
	printf("Adding %ld tasks took %lf clocks.\n", cnt_add, (double)(add) / (double)(cnt_add));
	printf("Removing %ld minimums took %lf clocks.\n", cnt_remove, (double)(remove) / (double)cnt_remove);
	printf("----SKIP LIST----\n");
	printf("Adding %ld tasks took %lf clocks.\n", scnt_add, (double)(sadd) / (double)(scnt_add));
	printf("Removing %ld minimums took %lf clocks.\n", scnt_remove, (double)(sremove) / (double)scnt_remove);

	

	return 0;
}
Beispiel #14
0
BOOLEAN mergeRuns(FILE ** sorted, int pagesize, int availableBuffers, FileList currentFiles, int * passes, int * runs, int totalRecordCount){
	RecordHeap rHeap;
	Buffer * bufferNodes;
	int bufferIndex;

/*Determine max files that can be merged in a run*/
/*That is available buffers -1 for the output buffer*/
/*This is also the output buffer indes*/
	int outputBuffIndex = availableBuffers -1;

/*Buffer array (of buffer nodes) where size of which is the number
of buffers available to store in memory*/
	bufferNodes = calloc(availableBuffers, sizeof(Buffer));
	if(!bufferNodes){
		fprintf(stderr, "Error: Failed to allocate buffer array\n");
		return FALSE;
	}

/*Allocate memory for record arrays for each buffer*/
	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		initBuffer(&bufferNodes[bufferIndex], pagesize);
	}

/*Initialise priority queue
It's size is the amount of files that can be merged in a run*/
/*outputBuffIndex is the last index in the buffer array*/
	if(initHeap(&rHeap, outputBuffIndex * pagesize) == FALSE){
		return FALSE;
	}

/*while more merging required, (more than 1 temporary file)*/
/*go through a pass*/
	while(currentFiles.fileCount > 1){
		int runCount = 0;
		/*Define first file to be the start of the file linked list*/
		FileNode * firstFileForRun = currentFiles.fileHeadNode;

		/*Run file list, is the files to be merged in the next pass*/
		FileList runFileList;/*= calloc(1, sizeof(FileList));*/

		float runsInPassFloat = ((float)currentFiles.fileCount/(float)(availableBuffers-1));
		int runsInPass = ceil(runsInPassFloat);

		initFileList(&runFileList);


/*while still merging required for pass*/
/*go through a run*/
		while(runCount < runsInPass){
			int buffersInUse = 0;
			int bufferIndex = 0;
			int init = 0;
			FileNode * currentRunFile = firstFileForRun;
			FILE * outputFile;
			
/*create new temp file for merge run, written to when output buffer is full*/
			if((outputFile = tmpfile()) == NULL){
				fprintf(stderr, "Error: Failed to create output temporary file for run\n");
				return FALSE;
			}

/*add file pointer to the file list for the next pass*/
			addFile(&runFileList,outputFile);

/*Read in pages from current files to buffers*/
			for(bufferIndex = 0; bufferIndex < outputBuffIndex; bufferIndex++){
				int recordPageIndex;
/*fill buffer with records from file*/
				if(currentRunFile->fp != NULL){
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						/*read in record*/
						Record record;
						if(fread(&record, sizeof(Record), 1, currentRunFile->fp) == 1){
							/*add record to page (records array)*/
							init++;
							if(addRecord(&bufferNodes[bufferIndex], record, pagesize, recordPageIndex) == FALSE)
								return FALSE;
		/*add record index to heap*/
							if(addToHeap(&rHeap, &bufferNodes[bufferIndex], recordPageIndex) == FALSE)
								return FALSE;
						}
		/*else reached file end*/
						else{
							/*temp file will be automatically deleted by the system*/
							fclose(currentRunFile->fp);
							currentRunFile->fp = NULL;
							/*removeFile(currentFiles, currentRunFile);*/
							/*add blank records*/
							/*int blankRecordCount;
							for(blankRecordCount = recordCount; blankRecordCount < pagesize; blankRecordCount++){
								int recordPageIndex = addBlankRecord(&bufferNodes[bufferIndex], pagesize);
								
								if(recordPageIndex < 0)
									return FALSE;
							}*/
							break;
						}
					}
					bufferNodes[bufferIndex].fileNode = currentRunFile;
					buffersInUse++;
					currentRunFile = currentRunFile->nextFileNode;
					if (currentRunFile == NULL)
						break;
				}
				else
					break;
			}
/*set firstFileForRun for next run*/
			firstFileForRun = currentRunFile;

/*while all buffers are not empty (there is still records in pages in
some buffer not including the output buffer)*/
			while(buffersInUse > 0 && rHeap.count > 0){
/*keep getting min record and writing to output buffer*/
/*get smallest record*/
				RecordIndex minIndex = removeMinHeap(&rHeap);
				if(minIndex.guildID == 0)
					return FALSE;
/*move smallest record from main buffer memory to output buffer*/
/*add record to output buffer*/
				addRecord(&bufferNodes[outputBuffIndex],
					minIndex.buff->pageRecords[minIndex.pgIndex], pagesize, bufferNodes[outputBuffIndex].recordCount);
/*remove the same record from original buffer*/
				removeRecord(minIndex.buff, minIndex.pgIndex);
/*if output buffer is full, write page to file*/
				if(bufferNodes[outputBuffIndex].recordCount == pagesize){
/*write page to file*/
					int written;
					written = fwrite(bufferNodes[outputBuffIndex].pageRecords, sizeof(Record),
						pagesize, outputFile);
					if(written !=pagesize){
						fprintf(stderr, "Error: Failed to write to output file, wrote %i records\n",written);
						return FALSE;
					}

					/*clear page in output buffer*/
					clearPage(&bufferNodes[outputBuffIndex], pagesize);
				}

/*if original buffer is empty, read in another page*/
				if(minIndex.buff->recordCount == 0){
					int recordPageIndex;
/*fill buffer with records from file*/
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						Record record;
						if(minIndex.buff->fileNode->fp != NULL){
							if(fread(&record, sizeof(Record), 1, minIndex.buff->fileNode->fp) == 1){
		/*add record to page (records array)*/
								if(addRecord(minIndex.buff, record, pagesize, recordPageIndex) == FALSE)
									return FALSE;
		/*add record index to heap*/
								if(addToHeap(&rHeap, minIndex.buff, recordPageIndex) == FALSE)
									return FALSE;
							}
		/*else reached file end*/
							else{
								/*temp file will be automatically deleted by the system*/
								fclose(minIndex.buff->fileNode->fp);
								minIndex.buff->fileNode->fp = NULL;
								/*removeFile(currentFiles, minIndex.buff->fileNode);*/
								break;
							}
						}
					}
				}
/*if buffer is still empty, then 0 records were read in,
therefore file is empty and the buffer is now free*/
				if(minIndex.buff->recordCount == 0)
					/*decrement buffers in use counter*/
					buffersInUse--;
			}

/*All files for run have been fully read*/
/*Write out records still in output buffer*/
			if(bufferNodes[outputBuffIndex].recordCount > 0){
/*Output buffer page was not full*/
				int i = 0;
				for(i = 0; i < pagesize; i++){
					if(bufferNodes[outputBuffIndex].pageRecords[i].GuildID != 0){
						fwrite(&bufferNodes[outputBuffIndex].pageRecords[i],
							sizeof(Record), 1, outputFile);
						removeRecord(&bufferNodes[outputBuffIndex], i);
					}
				}
			}
			/*Rewind outfile for future merge*/
			rewind(outputFile);
			runCount++;
		}
		/*set runFileListas new current file list*/
		freeFileNode(&currentFiles);
		currentFiles = runFileList;
		*passes = *passes+1;
		*runs = *runs + runCount;
		printf("Pass %i resulted in %i runs\n",*passes,runCount);
	}


/*FileList will contain link to only 1 temporary binary file*/
	if(currentFiles.fileCount != 1){
		fprintf(stderr, "Error: Number of files:%i is invalid\n",currentFiles.fileCount);
		return FALSE;
	}
	*sorted = currentFiles.fileHeadNode->fp;

	/*free allocated memory*/

	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		freeBuffer(&bufferNodes[bufferIndex]);
	}
	free(bufferNodes);

	freeHeap(&rHeap);

	freeFileNode(&currentFiles);

	/*free(currentFiles);*/

	return TRUE;
}
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;
}