cpair.c 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/**
 * @file cpair.c
 * @author Ivaylo Ivanov 11777707
 * @date 08.12.2018
 *
 * @brief Main program module.
 *
 * A program that searches for the closest pair of points in a set of 2D-points
 *
 *    SYNOPSIS
 *    cpair
 *
 *    EXAMPLE
 *    $ cat 1.txt
 *    4.0 4.0
 *    -1.0 1.0
 *    1.0 -1.0
 *    -4.0 -4.0
 *    $ ./cpair < 1.txt
 *    -1.000000 1.000000
 *    1.000000 -1.000000
 *
 *
 * The program accepts an array of 2D-points as an input from stdin. The input ends at EOF.
 *
 * The program does the following:
 *  - No output if the array has one point
 *  - The points if the array has 2 points
29 30 31
 *  - Otherwise, the array is split in 2 parts based on the mean of X and sent to 2 different paralell child processes.
 *    The parent watches for the return code of the children and terminates with an error if any of the children exit
 *    with anything other than success.
32 33 34 35 36 37 38 39 40 41 42
 *
 * Algorithm description when there are more than 2 points:
 *  - P1 and P2 are the closest pairs for the first and the second part respectively.
 *  - Go through all of the pairs between the points from the first half with the second half and save the shortest one in P3.
 *  - Compare P1, P2 and P3 and return the shortest one to stdout.
 *
 **/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
43 44 45
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
46

47 48
/// Node struct for linked list
typedef struct node {
49 50 51 52 53
    /**
     * points[0] - contains the X coordinate of the point
     * points[1] - contains the Y coordinate of the point
     *
     **/
54 55 56
    float points[2];
    struct node * next;
} node_t;
57

58 59
float get_x_mean(node_t * head);
float get_distance(float x1, float x2, float y1, float y2);
60 61
node_t * find_shortest_distance(node_t * list);
int wait_for_termination(pid_t child);
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
int main(int argc, char *argv[]) {
    if (argc > 1) {
        puts("The command takes no additional arguments.");
        puts("Usage: cpair");
        exit(EXIT_FAILURE);
    }

    /**
     *  Create the pipe file descriptors and inititalize the pipes
     *
     * fd[0] - input side of pipe
     * fd[1] - output side of pipe
     *
     **/
    int in_pipe_a[2], out_pipe_a[2], in_pipe_b[2], out_pipe_b[2];

    if(pipe(in_pipe_a) < 0 || pipe(in_pipe_b) < 0 || pipe(out_pipe_a) < 0 || pipe(out_pipe_b) < 0) {
        fprintf(stderr, "ERROR: Failed creating the pipes\n");
        exit(EXIT_FAILURE);
    }

84 85
    char input[__UINT8_MAX__] = ""; ///< An array to save the input to
    int point_num = 0; ///< Save the number of points
86 87 88 89 90
    node_t * head = NULL;

    head = malloc(sizeof(node_t));

    node_t * current = head;
91 92

    while(fgets(input, __INT8_MAX__, stdin) != NULL) { ///< Read line by line
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
93 94 95
        /// Split the input by whitespace as delimiter
        char *x = strtok(input, " ");
        char *y = strtok(NULL, " ");
96

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
97
        if(x != NULL && y != NULL) {
98
            /// Convert to float and save to the list
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
99 100
            current -> points[0] = strtof(x, NULL);
            current -> points[1] = strtof(y, NULL);
101 102 103
            current -> next = malloc(sizeof(node_t));
            current = current -> next;
            point_num++; ///< Increase the list length
104
        } else {
105
            fprintf(stderr, "ERROR: Ill-formed line found\n");
106 107 108 109 110
            exit(EXIT_FAILURE);
        }
    }

    if(feof(stdin) == 0) {
111
        fprintf(stderr, "ERROR: An error interrupted the read\n");
112 113 114 115 116 117 118
        exit(EXIT_FAILURE);
    }

    if(point_num == 1)
        exit(EXIT_SUCCESS);

    if(point_num == 2) {
119 120
        printf("%f %f\n", head -> points[0], head -> points[1]);
        printf("%f %f\n", head -> next -> points[0], head -> next -> points[1]);
121 122 123
        exit(EXIT_SUCCESS);
    }

124 125
    pid_t child_a, child_b; ///< Create variables for the child processes

126
    /// Create first child
127
    switch(child_a = fork()) {
128
        case -1:
129
            fprintf(stderr ,"ERROR: Couldn't fork child\n");
130 131
            exit(EXIT_FAILURE);
        case 0:
132 133 134 135 136
            /// Child execution
            close(out_pipe_a[0]);
            close(in_pipe_a[1]);
            close(STDIN_FILENO);
            if(dup2(in_pipe_a[0], STDIN_FILENO) != STDIN_FILENO) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
137
                fprintf(stderr, "ERROR: Failed duplicating STDIN\n");
138 139
                exit(EXIT_FAILURE);
            }
140 141
            execlp(argv[0], argv[0], NULL);

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
142
            fprintf(stderr, "ERROR: Failed to load program into child\n");
143
            exit(EXIT_FAILURE);
144
        default:
145 146
            /// Parent execution
            /// Create second child
147 148 149 150 151
            switch(child_b = fork()) {
                case -1:
                    fprintf(stderr, "ERROR: Couldn't fork child\n");
                    exit(EXIT_FAILURE);
                case 0:
152 153 154 155 156
                    /// Child execution
                    close(out_pipe_b[0]);
                    close(in_pipe_b[1]);
                    close(STDIN_FILENO);
                    if(dup2(in_pipe_b[0], STDIN_FILENO) != STDIN_FILENO) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
157
                        fprintf(stderr, "ERROR: Failed duplicating STDIN\n");
158 159
                        exit(EXIT_FAILURE);
                    }
160 161
                    execlp(argv[0], argv[0], NULL);

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
162
                    fprintf(stderr, "ERROR: Failed to load program into child\n");
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
                    exit(EXIT_FAILURE);
                default:
                    /// Parent execution
                    close(in_pipe_a[0]);
                    close(in_pipe_b[0]);
                    close(STDOUT_FILENO);

                    float x_mean = get_x_mean(head);

                    node_t * first_part = malloc(sizeof(node_t));
                    int first_part_len = 1;

                    node_t * second_part = malloc(sizeof(node_t));
                    int second_part_len = 1;

                    node_t * first_part_buff = first_part;
                    node_t * second_part_buff = second_part;

                    /// Separate the lists based on the mean
                    current = head;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
183
                    while(current -> next != NULL) {
184 185
                        if(current -> points[0] <= x_mean) {
                            first_part_buff -> points[0] = current -> points[0];
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
186
                            first_part_buff -> points[1] = current -> points[1];
187 188 189 190 191
                            first_part_buff -> next = malloc(sizeof(node_t));
                            first_part_buff = first_part_buff -> next;
                            first_part_len ++;
                        } else {
                            second_part_buff -> points[0] = current -> points[0];
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
192
                            second_part_buff -> points[1] = current -> points[1];
193 194 195 196 197 198 199 200
                            second_part_buff -> next = malloc(sizeof(node_t));
                            second_part_buff = second_part_buff -> next;
                            second_part_len ++;
                        }
                        current = current -> next;
                    }

                    /**
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
201 202 203 204
                     *
                     * Send first half to first child
                     *
                     **/
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
205
                    /// Setup string for first child pipe
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
206
                    current = first_part;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
207
                    char first_part_string[first_part_len][__UINT8_MAX__];
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
208
                    int i = 0;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
209
                    while(current -> next != NULL) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
210 211 212 213 214 215
                        sprintf(first_part_string[i], "%f %f\n", current -> points[0], current -> points[1]);
                        i++;
                        current = current -> next;
                    }
                    first_part_string[first_part_len][0] = EOF;

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
216 217 218 219 220
                    if(dup2(in_pipe_a[1], STDIN_FILENO) != STDIN_FILENO) {
                        fprintf(stderr, "ERROR: Failed duplicating STDIN\n");
                        exit(EXIT_FAILURE);
                    }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
221 222
                    /// Write to pipe
                    if (write(in_pipe_a[1], first_part_string, first_part_len * __UINT8_MAX__) < 0) {
223 224 225 226
                        fprintf(stderr, "ERROR: Failed writing to child\n");
                        exit(EXIT_FAILURE);
                    }
                    close(STDOUT_FILENO);
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
227 228 229 230 231 232

                    /**
                     *
                     * Send second half to second child
                     *
                     **/
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
233
                    /// Setup string for second child pipe
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
234 235 236
                    current = second_part;
                    char second_part_string[second_part_len + 1][__UINT8_MAX__];
                    i = 0;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
237
                    while(current -> next != NULL) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
238 239 240 241 242 243
                        sprintf(second_part_string[i], "%f %f\n", current -> points[0], current -> points[1]);
                        i++;
                        current = current -> next;
                    }
                    second_part_string[second_part_len][0] = EOF;

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
244 245 246 247 248
                    if(dup2(in_pipe_b[1], STDIN_FILENO) != STDIN_FILENO) {
                        fprintf(stderr, "ERROR: Failed duplicating STDIN\n");
                        exit(EXIT_FAILURE);
                    }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
249 250
                    /// Write to pipe
                    if (write(in_pipe_b[1], second_part_string, second_part_len * __UINT8_MAX__) < 0) {
251 252 253 254 255 256 257
                        fprintf(stderr, "ERROR: Failed writing to child\n");
                        exit(EXIT_FAILURE);
                    }
                    close(STDOUT_FILENO);

                    /// Wait for the correct exit of the children
                    if(wait_for_termination(child_a) != EXIT_SUCCESS || wait_for_termination(child_b) != EXIT_SUCCESS) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
258
                        fprintf(stderr, "ERROR: Children didn't terminate successfully\n");
259 260
                        exit(EXIT_FAILURE);
                    }
261

262 263 264 265 266 267 268 269 270 271
                    /// Free the memory
                    free(head);
                    free(first_part);
                    free(first_part_buff);
                    free(second_part);
                    free(second_part_buff);
                    free(current);
                    break;
            }
    }
272 273 274 275 276

    exit(EXIT_SUCCESS);
}

/**
277 278 279
 * @brief Function to calculate the mean of the X coordinates from a points list
 * @details Loops through the points list, gets the sum of X coordinates and returns the mean
 * @param head - a pointer to a list with the points
280 281 282
 * @return mean of all X coordinates
 *
 **/
283 284
float get_x_mean(node_t * head) {
    node_t * current = head;
285
    float x_sum = 0;
286 287 288
    int i = 1;

    while(current != NULL) {
289 290 291
        x_sum += current -> points[0];
        current = current -> next;
        i++;
292
    }
293

294
    return x_sum/(i - 2); ///< TODO: Fix the bug with the 2 more iterations
295 296 297 298 299 300 301 302 303 304 305 306 307 308
}

/**
 * @brief Function to calculate the distance between 2 points
 * @details The function calculates the distance between 2 points
 *          in a Cartesian coordinate system, given their coordinates
 * @param x1, y1 - pair of coordinates for the first point
 *        x2, y2 - pair of coordinates for the second point
 * @return distance between the two points
 *
 **/
float get_distance(float x1, float x2, float y1, float y2) {
    return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2));
}
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

/**
 * @brief Function to find the shortest distance in a list
 * @details The function gets a list of points and finds the pair
 *          with the shortest distance between them.
 * @param list - the list with points
 * @return res - a list containing the coordinates of the two closest points
 *
 **/
node_t * find_shortest_distance(node_t * list) {
    node_t * current = list;
    node_t * next = list;

    /// Setup the result list
    node_t * res = malloc(sizeof(node_t));
    res -> next = malloc(sizeof(node_t));

    int current_shortest = 0;
    int new_shortest = 0;

    while(current != NULL) {
        next = current -> next;
        if(next != NULL) {
            new_shortest = get_distance(current -> points[0], next -> points[0], current -> points[1], next -> points[1]);

            if(new_shortest < current_shortest) {
                current_shortest = new_shortest;

                /// Save the pairs
                res -> points[0] = current -> points[0];
                res -> points[1] = current -> points[1];
                res -> next -> points[0] = next -> points[0];
                res -> next -> points[1] = next -> points[1];
            }

            current = next;
        } else
            break;
    }

    return res;
}

/**
 * @briefs Function that waits for a child to close
 * @details The function waits for a child to close.
 *          If it closes successfully, it returns the exit status only.
 *          Otherwise, it prints an error message and then returns the exit status.
 * @param child - the pid of the child process
 * @return the exist status of the child process
 *
 **/
int wait_for_termination(pid_t child) {
    int exit_stat = 0;

    if(waitpid(child, &exit_stat, 0) < 0) {
        fprintf(stderr, "ERROR: Child did not exit successfully\n");
    }

    return WEXITSTATUS(exit_stat);
}