comparison src/utils.c @ 30:f945bcc3571f

refactor
author Dennis C. M. <dennis@denniscm.com>
date Thu, 29 Jun 2023 17:48:36 +0100
parents dae463bbf5ca
children 61104b22a25d
comparison
equal deleted inserted replaced
29:dae463bbf5ca 30:f945bcc3571f
28 swap_elements(i, j, arr); 28 swap_elements(i, j, arr);
29 } 29 }
30 } 30 }
31 31
32 32
33 bool array_sorted(struct Element *arr, int arr_size) { 33 void algorithm_selector(struct Algo *algos, int size, int direction, int *selected_algo) {
34 for (int i = 0; i < arr_size - 1; i++) { 34 int selection = *selected_algo + direction;
35 if (arr[i].value > arr[i + 1].value) {
36 return false;
37 }
38 }
39 35
40 return true; 36 if (selection >= 0 && selection <= size - 1) {
41 } 37 *selected_algo = selection;
42
43
44 void algorithm_selector(struct Algo *algos, int direction, int *selected_algorithm) {
45 int selection = *selected_algorithm + direction;
46 int lower = 0;
47 int upper = (int)((sizeof(algos) / sizeof(algos[0])) - 1);
48
49 if (selection >= lower && selection <= upper) {
50 *selected_algorithm = selection;
51 } 38 }
52 } 39 }
53 40
54 41
55 void delay_flow(useconds_t *delay, bool *pause) { 42 void change_speed(struct AlgoArgs *algo_args, int change) {
43 int new_delay = algo_args->delay + change;
44
45 if (new_delay) {
46 algo_args->delay = new_delay;
47 }
48 }
49
50
51 void control_flow(useconds_t delay, bool sequentially, bool *pause) {
52 if (sequentially) {
53 *pause = true;
54 }
55
56 while (*pause) { 56 while (*pause) {
57 // Wait to resume 57 // Wait to resume
58 } 58 }
59 59
60 usleep(*delay); 60 usleep(delay);
61 } 61 }
62
63
64 void reset_state(struct AlgoArgs *algo_args, struct ThreadState *thread_state) {
65 if (thread_state->running) {
66 pthread_cancel(thread_state->thread);
67 }
68
69 randomize_array(algo_args->arr, algo_args->arr_size);
70
71 algo_args->comparisons = 0;
72 algo_args->pause = false;
73 algo_args->sequentially = false;
74
75 for (int i = 0; i < algo_args->arr_size - 1; i++) {
76 algo_args->arr[i].current = false;
77 }
78 }
79
80
81 void run(struct AlgoArgs *algo_args, struct Algo *algos, int selected_algo,
82 struct ThreadState *thread_state) {
83
84 if (algo_args->pause) {
85 algo_args->pause = false;
86 } else {
87 thread_state->running = true;
88 pthread_create(&(thread_state->thread), NULL, algos[selected_algo].function,
89 (void *)algo_args);
90 }
91 }
92