forked from joaomsa/StringSearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
124 lines (110 loc) · 3.02 KB
/
main.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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/* Joao Paulo Mendes de Sa */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#ifndef STRSTR_H
#define STRSTR_H
#include "strstr.h"
#endif
/* Check whether memory allocation fails. */
#define CHKMLC(x) \
if ((x) == NULL){ \
fprintf(stderr, "Malloc Failed\n"); \
abort();}
/* Read notes from input. */
void music_read(FILE *input, int notesLen, char *notes)
{
int i, c;
for (i = 0; isgraph(c = getc(input)) || i < notesLen; ){
switch (c){
case 'A':
notes[i] = 0;
break;
case 'B':
notes[i] = 2;
break;
case 'C':
notes[i] = 3;
break;
case 'D':
notes[i] = 5;
break;
case 'E':
notes[i] = 7;
break;
case 'F':
notes[i] = 8;
break;
case 'G':
notes[i] = 10;
break;
case '#':
notes[i - 1]++;
break;
case 'b':
notes[i - 1]--;
if (notes[i - 1] == -1)
notes[i - 1] = 11;
break;
}
if (c >= 'A' && c <= 'G')
i++;
}
}
/* Calculate pairwise pitch difference. */
void music_pitch_diff(int *notesLen, char *notes)
{
int i;
for (i = 0; i < *notesLen - 1; i++){
notes[i] = notes[i + 1] - notes[i];
if (notes[i] < 0)
notes[i] += 12;
notes[i] += '0';
}
(*notesLen)--;
notes[*notesLen] = '\0';
}
int main(int argc, char *argv[])
{
int needleLen, haystackLen;
char *needle, *haystack, *ptr;
FILE *input;
if (argc < 3){
fprintf(stderr, "Missing paramerter\n");
abort();
}
input = fopen(argv[1], "r");
while (1){
if (fscanf(input, "%i %i", &haystackLen, &needleLen) != 2){
fprintf(stderr, "Missing number of notes\n");
abort();
}
if (needleLen == 0 || haystackLen == 0)
break;
CHKMLC(needle = malloc(sizeof(char) * needleLen));
CHKMLC(haystack = malloc(sizeof(char) * haystackLen));
music_read(input, haystackLen, haystack);
music_read(input, needleLen, needle);
music_pitch_diff(&haystackLen, haystack);
music_pitch_diff(&needleLen, needle);
switch(argv[2][0] - '0'){
case 1: ptr = strstr_bf(haystack, needle);
break;
case 2: ptr = strstr_kmp(haystack, needle);
break;
case 3: ptr = strstr_bmh(haystack, needle);
break;
case 4: ptr = strstr_bitap(haystack, needle);
break;
default: ptr = strstr(haystack, needle);
}
if (ptr != NULL)
printf("S %li\n", ptr - haystack);
else
printf("N\n");
free(needle);
free(haystack);
}
return EXIT_SUCCESS;
}