-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat_challenge.c
More file actions
110 lines (94 loc) · 2.52 KB
/
format_challenge.c
File metadata and controls
110 lines (94 loc) · 2.52 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//This ended up grosser than I would like, but the general case is kind of annoying
//TODO come back with a more elegant solution
//have to link math library -lm
//"numbers.txt"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool is_prime(int x);
bool is_even(int x);
int parse_numbers(char *str, int **out);
void reset_string(char *str, int len);
int main (void) {
FILE *fp = fopen("numbers.txt", "r");
if (!fp) {
puts("Cannot open file!");
exit(1);
}
char buff[255];
while (fgets(buff, 255, fp)) {
int *int_buff = malloc(sizeof(int)),
len = parse_numbers(buff, &int_buff);
for (int i = 0; i < len; ++i) {
if (is_prime(int_buff[i])) {
printf("Found prime: %d\n", int_buff[i]);
}
else if (is_even(int_buff[i])) {
printf("Found even: %d\n", int_buff[i]);
}
else {
printf("Found odd: %d\n", int_buff[i]);
}
}
}
}
bool is_prime (int x) {
if (x <= 0)
return false;
for (int i = 2; i <= (int) sqrt((double) x); ++i) {
if (x % i == 0)
return false;
}
return true;
}
bool is_even (int x) {
return x % 2 == 0;
}
int parse_numbers (char *str, int **out) {
int index = 0,
temp = 0,
count = 0;
char buff[255],
c;
reset_string(buff, 255);
while ((c = *(str++)) != '\0') {
if (c >= '0' && c <= '9' || c == '-') {
buff[index++] = c;
} else {
/* gets the number out of buff,
* resizes the array that was passed in,
* purges buff
*/
if (index > 0) {
sscanf(buff, "%d", &temp);
++count;
if (!realloc(*out, sizeof(int) * count)) {
puts("Error realloc'ing memory");
exit(1);
}
(*out)[count - 1] = temp;
reset_string(buff, 255);
index = 0;
}
}
}
// get the last number out
if (index > 0) {
sscanf(buff, "%d", &temp);
++count;
if (!realloc(*out, sizeof(int) * count)) {
puts("Error realloc'ing memory");
exit(1);
}
(*out)[count - 1] = temp;
reset_string(buff, 255);
index = 0;
}
return count;
}
void reset_string (char *str, int len) {
for (int i = 0; i < len; ++i) {
str[i] = '\0';
}
}