Line data Source code
1 : #include <stdbool.h>
2 : #include <stdio.h>
3 : #include <stdlib.h>
4 : #include <string.h>
5 :
6 : #define MAX_WORD_LEN 100
7 : #define MAX_WORDS 10000
8 :
9 : typedef struct {
10 : char text[MAX_WORD_LEN];
11 : int count;
12 : bool deleted;
13 : } word_t;
14 :
15 : typedef struct {
16 : word_t *words;
17 : int size;
18 : } dict_t;
19 :
20 :
21 59640 : bool is_prime(int n) {
22 59640 : if (n <= 1)
23 1 : return false;
24 59639 : if (n <= 3)
25 2 : return true;
26 59637 : if (n % 2 == 0 || n % 3 == 0)
27 39758 : return false;
28 :
29 224568 : for (int i = 5; i * i <= n; i += 6) {
30 218542 : if (n % i == 0 || n % (i + 2) == 0)
31 13853 : return false;
32 : }
33 6026 : return true;
34 : }
35 :
36 : // Find word in array
37 59640 : int find_word(dict_t *dict, char *word) {
38 175970438 : for (int i = 0; i < dict->size; i++) {
39 175964274 : if (!dict->words[i].deleted && strcmp(dict->words[i].text, word) == 0) {
40 53476 : return i;
41 : }
42 : }
43 6164 : return -1;
44 : }
45 :
46 1 : int main(void) {
47 :
48 : // Initialize dictionary
49 : dict_t dict;
50 1 : dict.words = malloc(MAX_WORDS * sizeof(word_t));
51 1 : dict.size = 0;
52 :
53 : char word[MAX_WORD_LEN];
54 1 : int line = 1;
55 :
56 : // if prime just try to delete!
57 :
58 59641 : while (fgets(word, MAX_WORD_LEN, stdin)) {
59 :
60 59640 : char *nl = word;
61 285398 : while (*nl != '\n' && *nl != '\0') nl++;
62 59640 : *nl = '\0';
63 59640 : int idx = find_word(&dict, word);
64 :
65 59640 : if (is_prime(line)) {
66 : // printf("%d linenmbr \n", line);
67 6028 : if (idx != -1) {
68 5565 : dict.words[idx].deleted = true;
69 5565 : printf("trying to delete %s: deleted\n", word);
70 : } else {
71 463 : printf("trying to delete %s: not found\n", word);
72 : }
73 : } else {
74 53612 : if (idx != -1) {
75 47911 : dict.words[idx].count++;
76 47911 : printf("counted %s\n", word);
77 : } else {
78 : // printf("%s: not found ", word);
79 5701 : strcpy(dict.words[dict.size].text, word);
80 5701 : dict.words[dict.size].count = 1;
81 5701 : dict.words[dict.size].deleted = false;
82 5701 : dict.size++;
83 5701 : printf("added %s\n", word);
84 : }
85 : }
86 59640 : line++;
87 : }
88 :
89 : // Find most frequent word
90 1 : char *max_word = NULL;
91 1 : int max_count = 0;
92 :
93 5702 : for (int i = 0; i < dict.size; i++) {
94 5701 : if (!dict.words[i].deleted &&
95 136 : (dict.words[i].count > max_count ||
96 129 : (dict.words[i].count == max_count && max_word &&
97 1 : strcmp(dict.words[i].text, max_word) < 0))) {
98 8 : max_count = dict.words[i].count;
99 8 : max_word = dict.words[i].text;
100 : }
101 : }
102 :
103 1 : if (max_word != NULL && max_count > 0) {
104 1 : printf("result: %s %d\n", max_word, max_count);
105 : }
106 :
107 1 : free(dict.words);
108 1 : fclose(stdin);
109 1 : return 0;
110 : }
|