Пример #1
0
int
main(int argc, char * argv[])
{
  if (argc < 2) die("USAGE: ex18 13 11 9");

  int count = argc - 1;
  char ** inputs = argv + 1;

  int *numbers = malloc(count * sizeof(int));
  if(! numbers) die("Memory error");

  for(int i=0; i < count; i++){
    numbers[i] = atoi(inputs[i]);
  }

  print_numbers(numbers, count);

  int * sorted = bubble_sort(numbers, count, sorted_order);

  print_numbers(sorted, count);

  free(sorted);

  free(numbers);
}
Пример #2
0
int main(int argc, char** argv) {

	int fd = open("/dev/random", O_RDWR);
	print_numbers(fd, 5);
	close(fd);

	fd = open("/dev/urandom", O_RDWR);
	print_numbers(fd, 5);
	close(fd);

}
Пример #3
0
int main(int argc, char *argv[]) {

	void *memory = allocate_fabric_attached_memory();
	struct DataHeader *header = get_header_address(memory);
	struct DataBuffer *buffer = get_buffer_address(memory);

	int i;

	check_if_something_to_show(header);
	i = header->current_sort_number;

	while (1) {


		if (header->current_sort_number >= i) {
			print_numbers(header, buffer, i);
			i++;
		} else {
			printf("Nothing new to show...\n");
			check_if_something_to_show(header);
			i = header->current_sort_number + 1;
		}
		printf("Going to sleep and continue later...\n\n");
		sleep(SLEEPING_TIME);

		printf("Continue...\n");
	}

	return 0;
}
Пример #4
0
int main()
{
	init_numbers(N, nums);
	read_numbers(nums);
	print_numbers(N, nums);
	find_max(N, nums);
	return 0;
}
Пример #5
0
int main8(void)
{
    printf("gimee a numbe bro:\n");
    int number;
    scanf("%d", &number);
    print_numbers(number);
    return 0;
}
Пример #6
0
int quicksort_driver(int a[], int l, int r, int max_y, int max_x, data *qcsort, WINDOW *win) {
	int j;
	if(l < r) {
		j = partition(a, l, r, max_y, max_x, qcsort, win);
		if(j == INT_MIN) /* exit */
			return INT_MIN;
		quicksort_driver(a, l, j - 1, max_y, max_x, qcsort, win);
		quicksort_driver(a, j + 1, r, max_y, max_x, qcsort, win);
	}
	attron(A_BOLD);
	print_numbers(qcsort, max_y, max_x);
	attroff(A_BOLD);
	return 0;
}
Пример #7
0
/* main program */
int main () {
        int     num_times;	/* number of times to print */

	/* prompt the user */

        print_prompt ();

	/* read in an integer */

        num_times = 12341;

	/* print the numbers */

        print_numbers (num_times);
	return 0;
}
/**
 * main function!
 */
int main(int argc, const char * argv[])
{
	double *numbers;
	Stat *stats;
	int length = 0;
	numbers = read_numbers_from_file("real1.txt", &length);
	if (numbers != NULL)
	{
		stats = process_numbers(numbers, length);
		if (stats != NULL)
		{
			print_numbers(stats);
			free(stats);
		}
		free(numbers);
	}
	return 0;
}
int main(void){
  struct timeval tv;
  fd_set readfds;

  tv.tv_sec = 1;
  tv.tv_usec = 500000;

  FD_ZERO(&readfds);
  FD_SET(STDIN, &readfds);

  select(STDIN+1, &readfds, NULL, NULL, NULL);

  if(FD_ISSET(STDIN, &readfds))
    printf("A key was pressed!\n");
  else
    printf("Timed out\n");

  int numbers [] = {1, 54, 23};
  print_numbers(numbers);
  return 0;
}
Пример #10
0
int main(){

    char c;
    int choice;
    int m, n;

    do {
	printf("MENU OPTIONS\n");
	printf("1 -- Using threads for synchronisation\n");
	printf("2 -- Thread printing even and odd numbers\n");
	printf("3 -- Printing m numbers(1 to m) alternatively using n threads\n");

	printf("\n");
	printf("Enter your choice\n");
	scanf("%d",&choice);
	switch(choice){
	    case 1:
		sync_threads();
		break;

	    case 2:
		even_odd_print();
		break;

	    case 3:
		printf("Enter m\n");
		scanf("%d", &m);
		printf("Enter no of threads\n");
		scanf("%d", &n);
		print_numbers(m, n);
		break;

	    default:
		break;
	}
	printf("\n\n");
    } while((c=getchar())!='q'); 
    return 0;
}
Пример #11
0
/* Fill an array of int values, prompting the user from stdin;
 * echo the list of numbers entered, then find the max and print it
 */ 
int main()
{ // Prompt the user for the size of the array
  // Store the size in the static integer SIZE
  get_size();
  if(SIZE<=0){
    fprintf(stderr, "Error! The size must be greater than 0!\n");
    exit(-1);
  }
  // Create a new array of numbers, of size "SIZE".
  int numbersArray[SIZE];
  // Pass the pointer to the array into these functions
  // Initialize all elements in the array to -1
  init_numbers(SIZE, numbersArray);
  // Read the user input
  read_numbers(numbersArray);
  // Print all values in the array
  print_numbers(SIZE, numbersArray);
  // Print the max values, evaluated by our functions
  printf("Max number: %d\n", find_max(SIZE, numbersArray));
  printf("Max number out of first half: %d\n", 
      find_max(SIZE/2, numbersArray));
}
Пример #12
0
int selectionsort(void) {
	WINDOW *win1, *win2, *win3;
	FILE *fp1;
	int startx_of_box, starty_of_box, width_of_box, height_of_box, max_x, max_y, start_y, start_x;  
	int choice, i, j, iter_no = 1, inner_iter, random = 1;
	int min, min_index, x_box1, x_box2;
	char c;
	data ssort;

	init_sort_info(&ssort); /* initialise number of swaps and comparisons to 0 */
	win3 = NULL; /* win3 will be used for displaying the final box after each iteration */
	cbreak();
	
	fp1 = fopen("files/selectionsort.txt", "r");
	if(fp1 == NULL) { /* display error */
		fprintf(stdout, "\vfopen: files/selectionsort.txt :: %s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \v", strerror(errno));
                endwin();
                exit(0);
	}	
	
	getmaxyx(stdscr, max_y, max_x); /* get max coordinates of the screen */
	print_in_middle(stdscr, 3, 0, max_x, "SELECTION SORT", COLOR_PAIR(3));
	
	start_y = max_y / 5;
	start_x = max_x / 4 + 4;
	print_intro(fp1, start_y, start_x); /* print the introduction page of Selection Sort */
	
	instruction(max_y - 2, 0, "Press <ENTER> to CONTINUE or 'p' to return to the previous menu.");
	c = getch();
	if(c == 'p') { /* exit */
		clear();
		fclose(fp1);
		curs_set(TRUE);
		return 0;
	}	
	else {
		get_num_elem(&ssort); /* get the number of elements to perform sorting on */
		clear();
		
		while(random != 0) { /* this loop is required because sometimes random function generates already sorted elements */
			random = num_generator(&ssort); /* randomly generate 'elements' numbers and store in ssort.numbers[elements] */
			message(max_y); /* print "generating random numbers..." */
		}
		clear();
		
		print_in_middle(stdscr, 3, 0, max_x, "SELECTION SORT", COLOR_PAIR(3));
		
		inner_iter = ssort.elements;
		height_of_box = 3; /* height of box */
		width_of_box = 4; /* width of box */
		starty_of_box = (max_y - height_of_box) / 4 + 5;  /* starting y coordinate of the box */
		startx_of_box = max_x / 4 + 2;  /* starting x coordinate of the box */
		
		instruction(max_y - 3, 0, "Press <ENTER> to START.");
		instruction(max_y - 2, 0, "Press 'p' to go to the Main Menu.\n");
		
		curs_set(FALSE); /* curs_set(TRUE) shows a dirty cursor at top-left of the box */
		win1 = create_newwin(height_of_box, width_of_box, starty_of_box, startx_of_box); /* create windows */
		startx_of_box += 8;
		win2 = create_newwin(height_of_box, width_of_box, starty_of_box, startx_of_box);
		
		attron(A_BOLD);	
		print_numbers(&ssort, max_y, max_x);
		attroff(A_BOLD);
		
		choice = getch();
		if(choice == 'p') { /* exit */
			clear();
			curs_set(TRUE);
			fclose(fp1);
			free(ssort.numbers);
			destroy_win(win1);
			destroy_win(win2);
			return 0;
		}	
		if(choice == ENTER) { /* start the animation */
			move(max_y - 3, 0);
			clrtoeol();
			
			attron(A_BOLD);
			mvprintw(max_y - 12, 0, "GREEN: Smallest element in the current list.");
			mvprintw(max_y - 10, 0, "YELLOW: Final position of element.");
			attroff(A_BOLD);
			
			instruction(max_y - 3, 0, "Press <RIGHT ARROW KEY> to proceed to the next step.");
			sleep(3);
			attron(A_BOLD);
			refresh();
			destroy_win(win1);
			x_box1 = startx_of_box;
			for(j = 0; j < ssort.elements - 1; j++) {
				sleep(1);
				mvprintw(max_y / 4, (max_x - 19) / 2,"Iteration number: %d", iter_no);
				
				destroy_win(win2);
				print_numbers(&ssort, max_y, max_x);
				x_box2 = x_box1 + 5;
				win1 = create_newwin(height_of_box, width_of_box, starty_of_box, x_box1);
				win2 = create_newwin(height_of_box, width_of_box, starty_of_box, x_box1 + 5);
				
				print_numbers(&ssort, max_y, max_x);
				
				min = ssort.numbers[j];
				min_index = j;
				
				move(max_y - 19, 0);
				clrtoeol();
				mvprintw(max_y - 19, max_x / 4 + 18, "Minimum element is %d.", ssort.numbers[j]);
				refresh();
				for(i = j + 1; i < inner_iter; i++) {
					sleep(1);
					print_numbers(&ssort, max_y, max_x);
					destroy_win(win2);
					win2 = create_newwin(height_of_box, width_of_box, starty_of_box, x_box2);
					if(ssort.numbers[i] < min) {
						print_numbers(&ssort, max_y, max_x);
						sleep(1);
						min = ssort.numbers[i];
						min_index = i;
						move(max_y - 19, 0);
						clrtoeol();
						mvprintw(max_y - 19, max_x / 4 + 18, "New minimum element is %d.", ssort.numbers[i]);
						refresh();
					}
					else {
						move(max_y - 19, 0);
						clrtoeol();
						mvprintw(max_y - 19, max_x / 4 + 18, "Minimum element remains %d.", ssort.numbers[min_index]);
						refresh();
					}	
					ssort.comparisons++; /* increment the number of comparisons in ssort */
					print_numbers(&ssort, max_y, max_x);
					choice = getch();
					if(choice == 'p') { /* exit */
						clear();
						curs_set(TRUE);
						fclose(fp1);
						free(ssort.numbers);
						destroy_win(win1);
						destroy_win(win2);
						return 0;
					}
					x_box2 += 5;
				}
				iter_no++;
				/* place a box over the smallest number */
				box_over_num(min_index, win3, max_y, max_x, height_of_box, width_of_box, 3);
				print_numbers(&ssort, max_y, max_x);
				sleep(1);
				
				move(max_y - 19, 0);
				clrtoeol();
				mvprintw(max_y - 19, max_x / 4 + 18, "Now %d and %d get swapped.", ssort.numbers[min_index], ssort.numbers[j]);
				refresh();
				sleep(2);
				
				destroy_win(win3);
				print_numbers(&ssort, max_y, max_x);
				win3 = NULL;
				
				ssort.numbers[min_index] = ssort.numbers[j];
				ssort.numbers[j] = min;
				ssort.swaps++;
				/* place a box over the number, now in its final position */
				box_over_num(j, win3, max_y, max_x, height_of_box, width_of_box, 4);
				
				x_box1 += 5;
				print_numbers(&ssort, max_y, max_x);
			}
			destroy_win(win1);
			destroy_win(win2);
			print_numbers(&ssort, max_y, max_x);
			sleep(1);
			
			clear_boxes(starty_of_box); /* clear the boxes from the screen */
			
			move(max_y - 19, 0);
			clrtobot();
			mvprintw(max_y - 17, max_x / 4 + 15, "Yeah! The numbers are sorted!!");
			mvprintw(max_y - 13, max_x / 4 + 15, "Info:");
			mvprintw(max_y - 11, max_x / 4 + 15, "Number of swaps = %d", ssort.swaps);
			mvprintw(max_y - 9, max_x / 4 + 15, "Number of comparisons = %d", ssort.comparisons);
			attroff(A_BOLD);
		}
		move(max_y - 4, 0);
		clrtobot();
		curs_set(TRUE);
		instruction(max_y - 2, 0, "Press any key to continue.\n");
		getch();
	}
	fclose(fp1);
	free(ssort.numbers);
	return 0;
}
Пример #13
0
/*
 * Modifica valoarea valorilor in urma comenzii date de utilizator.
 */
void modify_variable(int way)
{
    switch (idx)
    {
    case 1:
        if ((transX < 200) && (way == 1))
            transX++;
        if ((transX > -200) && (way == 0))
            transX--;
        break;
    case 2:
        if ((transY < 200) && (way == 1))
            transY++;
        if ((transY > -200) && (way == 0))
            transY--;
        break;
    case 3:
        if ((scaleX < 4.96) && (way == 1))
            scaleX += 0.05;
        if ((scaleX > 0.05) && (way == 0))
            scaleX -= 0.05;
        break;
    case 4:
        if ((scaleY < 4.96) && (way == 1))
            scaleY += 0.05;
        if ((scaleY > 0.05) && (way == 0))
            scaleY -= 0.05;
        break;
    case 5:
        if ((rotA < 2*M_PI) && (way == 1))
            rotA += 0.1;
        if ((rotA > 0) && (way == 0))
            rotA -= 0.1;
        break;
    case 6:
        draw_line();
        if ((simX < getmaxx()-7) && (way == 1))
            simX += 5;
        if ((simX > 0) && (way == 0))
            simX -= 5;
        draw_line();
        break;
    case 7:
        draw_line();
        if ((simY < getmaxy()-57) && (way == 1))
            simY += 5;
        if ((simY > 0) && (way == 0))
            simY -= 5;
        draw_line();
        break;
    case 8:
        draw_line();
        if ((simA < 3.09) && (way == 1))
            simA += 0.1;
        if ((simA > 0) && (way == 0))
            simA -= 0.1;
        draw_line();
        break;
    }
    print_numbers();
}
Пример #14
0
/*
 * Initializeaza toate spatiile de editare.
 */
void initialize_variable_spaces()
{
    set(1);
    setcolor(RED);
    outtextxy(0, 0, "Transl. cu:");
    idx = 1;
    outtextxy(10, 15, "x = ");
    variable_space(1);
    print_numbers();
    idx = 2;
    setcolor(RED);
    outtextxy(10, 30, "y = ");
    variable_space(1);
    print_numbers();

    set(2);
    setcolor(RED);
    outtextxy(0, 0, "Scalare cu:");
    idx = 3;
    outtextxy(10, 15, "x = ");
    variable_space(1);
    print_numbers();
    idx = 4;
    setcolor(RED);
    outtextxy(10, 30, "y = ");
    variable_space(1);
    print_numbers();

    set(3);
    setcolor(RED);
    outtextxy(0, 0, "Rotire cu:");
    idx = 5;
    outtextxy(10, 15, "р = ");
    variable_space(1);
    print_numbers();

    set(4);
    setcolor(RED);
    outtextxy(0, 0, "Coord. dr. aleatoare:");
    idx = 6;
    outtextxy(10, 15, "x = ");
    variable_space(1);
    print_numbers();
    idx = 7;
    setcolor(RED);
    outtextxy(10, 30, "y = ");
    variable_space(1);
    print_numbers();
    idx = 8;
    setcolor(RED);
    outtextxy(90, 15, "р = ");
    variable_space(1);
    print_numbers();

    idx = 1;
    variable_space(1);

    set(5);
    setcolor(RED);
    outtextxy(1, 5, "Comenzi:");
    outtextxy(1, 15, "+, -, t, s, r, c");
    outtextxy(1, 25, "x, y, o, d");
    outtextxy(1, 37, "ESC, sageti, TAB");

    setviewport(0, 0, getmaxx(), getmaxy(), 1);
    setcolor(RED);
    line(5, 3, 5, 47);
    line(105, 3, 105, 47);
    line(205, 3, 205, 47);
    line(305, 3, 305, 47);
    line(485, 3, 485, 47);
    line(635, 3, 635, 47);
    line(5, 2, 635, 2);
    line(5, 48, 635, 48);
}
Пример #15
0
int main(int argc, char **argv){
    print_numbers();

    return 0;
}
Пример #16
0
int main(int argc, char const *argv[]) {
  print_numbers ();
  print_numbers ();
  print_numbers ();
  return 0;
}
Пример #17
0
/**
 * Função principal do programa, responsável por executar funções 
 * que definem o comportamento do algoritmo.
 * 
 * \param argc Quantidade de argumentos passados ao programa.
 * \param argv Vetor que contem os argumentos passados para o programa.
 * \return Retorna zero caso tenha sucesso na execução.
 * \see create_empty_bin_list 
 * \see sort_numbers_array
 * \see print_numbers
 * \see fill_bins
 * \see print_list_bins
 * \see free_bins
 * \see NUMBERS_QUANTITY
 * \see NUMBERS_MINIMUM
 * \see NUMBERS_MAXIMUM
 * \see BIN_SIZE
 */ 
int main(int argc, char **argv)
{
   unsigned short int i;
   unsigned short int *values; /** Usa-se ponteiro para armazenar a lista de números. */
   bin_list *bins; /** Usa-se ponteiro contem a lsita de BINs gerados dinamicamente. */

   /**
    * Verifica-se os argumentos passados, ou seja, se foi passado a quantidade necessária. 
    * Se não, informa o que é preciso para execução e encerra o programa.
    */
   if (argc < 5)
   {
      printf("Passar os argumentos do programa.\n");
      printf("1 - Quantidade de números para empacotar \n");
      printf("2 - Tamanhos dos BINs \n");
      printf("3 - Valor mínimo dos números \n");
      printf("4 - Valor máximo dos números \n");
      printf("5 - Valores a serem empacotados (Opcional) \n");
      exit(1);
   }

   /** 
    * Atribui os argumentos as variavéis globais do programa, para
    * que seja utilizado no restante do rpograma.
    */
   NUMBERS_QUANTITY = atoi(argv[1]);
   BIN_SIZE = atoi(argv[2]);
   NUMBERS_MINIMUM = atoi(argv[3]);
   NUMBERS_MAXIMUM = atoi(argv[4]);

   /**
    * Caso tenha sido passado mais de cinco argumentos para o programa,
    * significa que a lista de números foi informada pelo usuário e,
    * portanto, não será gerada aleatoriamente.
    */
   if (argc > 5)
   {
      values = malloc(sizeof(int)*argc-5);
      NUMBERS_QUANTITY = argc -5;

      for (i = 0; i < argc-5; i++)
         values[i] = atoi( argv[i+5]);
   }
   else
   {
      values = malloc(sizeof(int)*NUMBERS_QUANTITY);
      create_numbers_array (values);
   }

   /**
    * \attention
    * Caso não tenha sido possível alocar memória para os números gerados ou
    * informados o programa é encerrado devido a indisponibilidade de memória.
    */
   if (values == NULL)
      exit(1);

   /** Inicialisa a lista de BINs.*/
   bins = create_empty_bin_list();
   /** Ordena de forma descrescente os números para empacotar. */
   sort_numbers_array (values);
   /** Imprime os números gerados e devidamente ordenados. */
   print_numbers(values);
   /** Preenche os BINS, ou seja, ler a lista de números e gera os BINs necessários. */ 
   fill_bins (values, bins);
   /** Imprime os BINs que foram gerados. */
   print_list_bins (bins);
   /** Por fim, libera todos os recursos que foram utilizados. */
   free_bins (bins);

   free (values);
   return 0;
}
Пример #18
0
int partition(int a[], int l, int r, int max_y, int max_x, data *qcsort, WINDOW *win) {
	int pivot, i, j, temp, choice, posx_i, posx_j, y_i, y_j;
	
	pivot = a[l]; /* pivot is the first element of the list */
	/* place a red box over the pivot */
	box_over_num(l, win, max_y, max_x, 3, 4, 2); /* height of box = 3, width of box = 4 */
	
	attron(A_BOLD);
	
	y_i = (max_y - 3) / 4 + 3; /* y coordinate of the row in which 'i' moves */
	y_j = (max_y - 3) / 4 + 4; /* y coordinate of the row in which 'j' moves */
	i = l;
	j = r + 1;
	posx_j = max_x / 4 + 11 + 5 * (j - 1);
	
	mvprintw(y_j, posx_j, "j");
	refresh();
	print_numbers(qcsort, max_y, max_x);
	while(1) {
		do {
			move(y_i, 0);
			clrtoeol();
			
			++i;
			
			move(max_y - 19, max_x / 4 + 18);
			clrtoeol();
			if(a[i] <= pivot)
				mvprintw(max_y - 19, max_x / 4 + 18, "As i: %d <= pivot: %d, increment i.", a[i], pivot);
			else	
				mvprintw(max_y - 19, max_x / 4 + 18, "As i: %d > pivot: %d, stop.", a[i], pivot);
			posx_i = max_x / 4 + 11 + 5 * i;
			mvprintw(y_i, posx_i, "i");
			refresh();
			
			(qcsort->comparisons)++; /* increment the number of comparisons in qcsort */
			choice = getch();
			if(choice == 'p') /* exit */
				return INT_MIN;
		} while(a[i] <= pivot && i < r);
		do {
			move(y_j, 0);
			clrtoeol();

			--j;

			move(max_y - 19, max_x / 4 + 18);
			clrtoeol();
			if(a[j] > pivot)
				mvprintw(max_y - 19, max_x / 4 + 18, "As j: %d > pivot: %d, decrement j.", a[j], pivot);
			else	
				mvprintw(max_y - 19, max_x / 4 + 18, "As j: %d <= pivot: %d, stop.", a[j], pivot);
			posx_j = max_x / 4 + 11 + 5 * j;
			mvprintw(y_j, posx_j, "j");
			refresh();

			(qcsort->comparisons)++;
			choice = getch();
			if(choice == 'p') /* exit */
				return INT_MIN;
		} while(a[j] > pivot);
		if(i >= j) /*  i and j have crossed over */
			break;

		move(max_y - 19, max_x / 4 + 18);
		clrtoeol();
		mvprintw(max_y - 19, max_x / 4 + 18, "Now i: %d and j: %d get swapped.", a[i], a[j]);
		refresh();

		temp = a[i]; /* swap i and j */
		a[i] = a[j];
		a[j] = temp;

		(qcsort->swaps)++; /* increment swaps */
		choice = getch();
		print_numbers(qcsort, max_y, max_x);
	}
	move(max_y - 19, max_x / 4 + 18);
	clrtoeol();
	mvprintw(max_y - 19, max_x / 4 + 18, "As i and j have crossed, pivot: %d and j: %d get swapped.", a[l], a[j]);
	refresh();

	temp = a[l]; /* swap pivot and j */
	a[l] = a[j];
	a[j] = temp;
	(qcsort->swaps)++; /* increment swaps */
	
	choice = getch();
	if(choice == 'p') /* exit */
		return INT_MIN;
	
	print_numbers(qcsort, max_y, max_x);
	/* place a box over the element j */ 
	box_over_num(j, win, max_y, max_x, 3, 4, 3); /* height of box = 3, width of box = 4, color_pair = 3 */
	
	mvprintw(y_j, max_x / 4 + 11 + 5 * j, " "); /* copy a whitespace over the green box */
	attroff(A_BOLD);
	return j;
}
Пример #19
0
int quicksort(void) {
	WINDOW *win1;
	FILE *fp1;
	int max_x, max_y, start_y, start_x, starty_of_box, height_of_box = 3;
	int choice, random = 1, ret_val;
	char c;
	data qcsort;

	init_sort_info(&qcsort); /* initialise number of swaps and comparisons to 0 */
	cbreak();
	init_pair(2, COLOR_RED, COLOR_BLACK);
	
	fp1 = fopen("files/quicksort.txt", "r");
	if(fp1 == NULL) { /* display error */
		fprintf(stdout, "\vfopen: files/quicksort.txt :: %s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \v", strerror(errno));
                endwin();
                exit(0);
	}	
	
	getmaxyx(stdscr, max_y, max_x); /* get the max dimensions of the screen */
	print_in_middle(stdscr, 3, 0, max_x, "QUICKSORT", COLOR_PAIR(3));
	
	start_y = max_y / 5;
	start_x = max_x / 4 + 4;
	print_intro(fp1, start_y, start_x); /* print the introduction page of Quicksort */
	
	instruction(max_y - 2, 0, "Press <ENTER> to CONTINUE or 'p' to return to the previous menu.");
	c = getch();
	if(c == 'p') {
		clear();
		curs_set(TRUE);
		fclose(fp1);
		return 0;
	}	
	else {
		(qcsort.comparisons)++; /* this is incremented as the partition function has a do...while */
		get_num_elem(&qcsort); /* get the number of elements to perform sorting on */
		clear();
		
		while(random != 0) { /* this loop is required because sometimes random function generates already sorted elements */
			random = num_generator(&qcsort); /* randomly generate 'elements' numbers and store in qcsort.numbers[elements] */
			message(max_y); /* print "generating random numbers..." */
		}
		clear();
		
		print_in_middle(stdscr, 3, 0, max_x, "QUICKSORT", COLOR_PAIR(3));
		
		instruction(max_y - 3, 0, "Press <ENTER> to START.");
		instruction(max_y - 2, 0, "Press 'p' to go to the Main Menu.");
		curs_set(FALSE); /* curs_set(TRUE) shows a dirty cursor at top-left of the box */
		
		attron(A_BOLD);
		print_numbers(&qcsort, max_y, max_x);
		attroff(A_BOLD);
		win1 = NULL; /* win1 will be used for displaying the final box after each iteration */
		choice = getch();
		if(choice == 'p') {
			clear();
			curs_set(TRUE);
			fclose(fp1);
			free(qcsort.numbers);
			return 0;
		}	
		else if(choice == ENTER) { /* start the animation */
			move(max_y - 3, 0);
			clrtoeol();
			attron(A_BOLD);
			mvprintw(max_y - 12, 0, "RED: Current position of pivot.");
			mvprintw(max_y - 10, 0, "GREEN: Final position of element.");
			attroff(A_BOLD);
			instruction(max_y - 3, 0, "Press <RIGHT ARROW KEY> to proceed to the next step.");
			sleep(3);
			attron(A_BOLD);
			
			ret_val = quicksort_driver(qcsort.numbers, 0, qcsort.elements - 1, max_y, max_x, &qcsort, win1);
			if(ret_val == INT_MIN) { /* exit */
				clear();
				curs_set(TRUE);
				fclose(fp1);
				free(qcsort.numbers);
				return 0;
			}	
			
			sleep(1);
			starty_of_box = (max_y - height_of_box) / 4 + 5;
			move(starty_of_box - 2, 0); /* to delete the letter 'i' which remains after the animation */
			clrtoeol();
			move(starty_of_box - 1, 0); /* to delete the letter 'j' which remains after the animation */
			clrtoeol();
			clear_boxes(starty_of_box); /* clear the boxes off the screen */
			move(max_y - 19, 0);
			clrtobot();
			attron(A_BOLD);
			mvprintw(max_y - 17, max_x / 4 + 15, "Yeah! The numbers are sorted!!");
			mvprintw(max_y - 13, max_x / 4 + 15, "Info:");
			mvprintw(max_y - 11, max_x / 4 + 15, "Number of swaps = %d", qcsort.swaps);
			mvprintw(max_y - 9, max_x / 4 + 15, "Number of comparisons = %d", qcsort.comparisons);
		}
		curs_set(TRUE);
		move(max_y - 5, 0);
		clrtobot();
		instruction(max_y - 2, 0, "Press any key to continue.\n");
		getch();
	}
	attroff(A_BOLD);
	fclose(fp1);
	free(qcsort.numbers);
	return 0;
}
Пример #20
0
/**
 * \param threads - number of threads to run in
 * \param chunk - size of chunk to generate
 * \param stop_after - seconds of generating the chunk. \
 *          Zero to generate only once, negative to infinite (until ESC is pressed)
 * \param stream - stream to write data
 * \param type - which function should be used? GET_UINT8_ARRAY, ...
 * \return throughput in MB/s
 */
double test_throughput( int threads, const size_t chunk, int stop_after, FILE *stream, const int type)
{
	size_t written, total,buf_size;
	uint64_t buf[threads*chunk];
    //char* buf_ptr;
    //uint64_t* buf;
    //size_t size;
	omp_set_num_threads(threads);
	struct timespec t[2];
	double run_time, throughput;
	int key,i;
	unsigned int retry;

	//buf_ptr = malloc(threads*chunk*sizeof(uint64_t)+10);
    //buf = (uint64_t*)&(buf_ptr[3]);
	run_time = 0;
	total = 0;
	clock_gettime(CLOCK_REALTIME, &t[0]);
	if(verbose_flag)
		fprintf(stderr, "Press [Esc] to stop the loop");

	key = 0;
	// SIZE threads*chunk;
	buf_size = SIZEOF(buf);
	do
	{
		written = 0;
#if 0
#pragma omp parallel for reduction(+:written)
		for ( i=0; i<threads; ++i)
		{
			/****************************************************************
			*                      TESTED METHODS INSERT HERE              *
			****************************************************************/
			switch(type)
			{
			case GET_BYTES:
				written += rdrand_get_bytes_retry((uint8_t*)&buf[i*chunk], chunk*8,1)/8;
				break;
			case GET_UINT8_ARRAY:
				written += rdrand_get_uint8_array_retry((uint8_t*)&buf[i*chunk], chunk*8, 1)/8;
				break;
			case GET_UINT16_ARRAY:
				written += rdrand_get_uint16_array_retry((uint16_t*)&buf[i*chunk], chunk*4, 1)/4;
				break;
			case GET_UINT32_ARRAY:
				written += rdrand_get_uint32_array_retry((uint32_t*)&buf[i*chunk], chunk*2, 1)/2;
				break;
			case GET_UINT64_ARRAY:
				written += rdrand_get_uint64_array_retry(&buf[i*chunk], chunk, 1);
				break;


			case GET_RDRAND16_STEP:
				written += fill_uint16_step((uint16_t *)&buf[i*chunk], chunk*4, 1)/4;
				break;
			case GET_RDRAND32_STEP:
				written += fill_uint32_step((uint32_t *)&buf[i*chunk], chunk*2, 1)/2;
				break;
			case GET_RDRAND64_STEP:
				written += fill_uint64_step(&buf[i*chunk], chunk, 1);
				break;

			case GET_RDRAND16_RETRY:
				written += fill_uint16_retry((uint16_t *)&buf[i*chunk], chunk*4, 1)/4;
				break;
			case GET_RDRAND32_RETRY:
				written += fill_uint32_retry((uint32_t *)&buf[i*chunk], chunk*2, 1)/2;
				break;
			case GET_RDRAND64_RETRY:
				written += fill_uint64_retry(&buf[i*chunk], chunk, 1);
				break;

			case GET_RESEED64_DELAY:
				written += rdrand_get_uint64_array_reseed_delay(&buf[i*chunk], chunk, 1);
				break;
			case GET_RESEED64_SKIP:
				written += rdrand_get_uint64_array_reseed_skip(&buf[i*chunk], chunk, 1);
				break;
			}
		}
		/* test generated amount */
		if ( written != SIZEOF(buf) )
		{
			fprintf(stderr, "ERROR: bytes generated %zu, bytes expected %zu\n", written, SIZEOF(buf));
			break;
		}

		if(!no_print_flag)
		{
			/* Test written amount */
			if(print_numbers_flag == 1)
			{
				written = print_numbers(stream, (char *)buf,sizeof(buf))/8;
				// written = fwrite(, sizeof(buf[0]), SIZEOF(buf), stream);
			}
			else
			{
				written = fwrite(buf, sizeof(buf[0]), SIZEOF(buf), stream);
			}
			total += written;
			if ( written !=  SIZEOF(buf) )
			{
				perror("fwrite");
				fprintf(stderr, "ERROR: fwrite - bytes written %zu, bytes to write %zu\n", sizeof(buf[0]) * written, sizeof(buf));
				break;
			}
		}
		else
		{
			total += written;
		}
#else
		#pragma omp parallel for reduction(+:written)
		for ( i=0; i<threads; ++i)
		{
			written += generate_with_metod(type,&buf[i*chunk], chunk, RETRY_LIMIT);


		}

		if ( written != buf_size )
		{
			/* if we can't lower threads count anymore */
			if ( threads == 1 )
			{
				fprintf(stderr, "Warning: %zu bytes generated, but %zu bytes expected. Trying to get randomness with slower speed.\n", written, buf_size);
				retry = 0;
				while(written != buf_size && retry++ < SLOW_RETRY_LIMIT_CYCLES)
				{
					usleep(retry*SLOW_RETRY_DELAY);
					// try to generate the rest
					written +=generate_with_metod(type,buf+written, chunk-written, SLOW_RETRY_LIMIT);
				}
				if( written != buf_size )
				{
					fprintf(stderr, "Error:  %zu bytes generated, but %zu bytes expected. Probably there is a hardware problem with your CPU.\n", written, buf_size);
					break;
				}
			}
			else
			{
				/* try to lower threads count to avoid underflow */
				threads--;
				fprintf(stderr, "Warning: %zu bytes generated, but %zu bytes expected. Probably slow internal generator - decreaseing threads count by one to %d to avoid problems.\n", written, buf_size, threads);
				buf_size -= chunk;

				continue;
			}
		}
		if(!no_print_flag)
		{

			/* Test written amount */
			if(print_numbers_flag == 1)
			{
				written = print_numbers(stream, (char *)buf,sizeof(buf))/8;
				// written = fwrite(, sizeof(buf[0]), SIZEOF(buf), stream);
			}
			else
			{
				written = fwrite(buf, sizeof(buf[0]), SIZEOF(buf), stream);
			}
			total += written;
			if ( written !=  SIZEOF(buf) )
			{
				perror("fwrite");
				fprintf(stderr, "ERROR: fwrite - bytes written %zu, bytes to write %zu\n", sizeof(buf[0]) * written, sizeof(buf));
				break;
			}
		}
		else
		{
			total += written;
		}




#endif // 0

		/* Stopping */
		key = getkey();

		if (stop_after >= 0)
		{
			clock_gettime(CLOCK_REALTIME, &t[1]);
			run_time = (double)(t[1].tv_sec) - (double)(t[0].tv_sec) +
				   ( (double)(t[1].tv_nsec) - (double)(t[0].tv_nsec) ) / 1.0E9;
			if(run_time > stop_after)
				key = 0x1B;
		}
	}
	while (key != 0x1B);

	if(stop_after < 0) // compute only if it wasn't already computed
	{
		clock_gettime(CLOCK_REALTIME, &t[1]);
		run_time = (double)(t[1].tv_sec) - (double)(t[0].tv_sec) +
			   ( (double)(t[1].tv_nsec) - (double)(t[0].tv_nsec) ) / 1.0E9;
	}
	throughput = (double) (total) * sizeof(buf[0]) / run_time/1024.0/1024.0;
	if(verbose_flag)
	{

		if(print_numbers_flag == 1)
			fprintf(stderr,"\n");
		fprintf(stderr, "\r  Runtime %.2f sec, throughput %.3f MiB/s\n", run_time, throughput);
	}

	return throughput;
}
Пример #21
0
int print_numbers(void){
    static int i = 0;
    i++;
    printf("%d\n", i);
    return (i - top) && print_numbers();
}