-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem0022.c
76 lines (50 loc) · 1.49 KB
/
problem0022.c
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//Project Euler Problem 22
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define FILE_SIZE 64000 /* max size in bytes */
#define MAX_NAMES 5163 /* total names in the file */
int compare(const void *x, const void *y) {
return strcmp(*(char * const *)x, *(char * const *)y);
}
int main(int argc, char *argv[]) {
FILE* names_file;
names_file = fopen(argv[1], "r");
char input_buffer[FILE_SIZE] = { '\0' }; /* buffer for file contents */
if (names_file == NULL) {
printf("Couldn't open the file, bye! \n");
return EXIT_FAILURE;
}
fread(input_buffer, 1, FILE_SIZE, names_file);
fclose(names_file);
char *names[MAX_NAMES];
// Parse the input_buffer:
int count = 0;
char *name;
name = strtok(input_buffer, ",");
do {
int name_len = strlen(name);
names[count] = (char *) malloc((name_len + 1) * sizeof(char));
if (names[count] == NULL) {
printf("Malloc failed, bye!");
return EXIT_FAILURE;
}
// Copy the name into the names array:
strcpy(names[count++], name);
} while (name = strtok(NULL, ","));
// Sort the names using quicksort
qsort(names, count, sizeof(char *), compare);
int total_score = 0;
for (int i = 0; i < count; i++) {
int name_score = 0;
for (int j = 0; j < strlen(names[i]); j++) {
name_score += (names[i][j] - 'A' + 1);
}
total_score += name_score * (i + 1);
}
printf("%d\n", total_score);
for (int i = 0; i < count; i++) {
free(names[i]);
}
return EXIT_SUCCESS;
}