summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--codeword.c96
1 files changed, 93 insertions, 3 deletions
diff --git a/codeword.c b/codeword.c
index 7b215a9..7a87f51 100644
--- a/codeword.c
+++ b/codeword.c
@@ -2,6 +2,7 @@
#include <stdio.h>
#include <string.h>
#include <errno.h>
+#include <ctype.h>
typedef struct
{
@@ -10,14 +11,20 @@ typedef struct
char letter;
} Character;
-static void Chomp(char *p)
+static void PrepLine(char *p)
{
size_t l = strlen(p);
+ size_t f;
while (l && p[l-1] == '\n')
{
p[--l] = 0;
}
+
+ for(f = 0; f < l; f++)
+ {
+ p[f] = tolower((unsigned char)p[f]);
+ }
}
static void Error(const char *p)
@@ -26,6 +33,82 @@ static void Error(const char *p)
exit(EXIT_FAILURE);
}
+static int ContainsLetter(char c, const Character *chars, int no_chars)
+{
+ int f;
+
+ for(f=0; f < no_chars; f++)
+ {
+ if (chars[f].is_letter && chars[f].letter == c)
+ {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static int CheckLettersAndLength(const char *buff,
+ const Character *chars,
+ int no_chars)
+{
+ size_t l = strlen(buff);
+ int f;
+
+ if (l != no_chars)
+ {
+ return 0;
+ }
+
+ for(f=0; f < no_chars; f++)
+ {
+ if (chars[f].is_letter &&
+ (chars[f].letter != buff[f]))
+ {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+static int CheckNumbers(const char *buff, const Character *chars, int no_chars)
+{
+ int f;
+ int n;
+ char code[27] = {0};
+
+ for(f = 0; f < no_chars; f++)
+ {
+ if (!chars[f].is_letter)
+ {
+ int i = chars[f].number - 1;
+
+ if (ContainsLetter(buff[f], chars, no_chars))
+ {
+ return 0;
+ }
+
+ if (code[i] && code[i] != buff[f])
+ {
+ return 0;
+ }
+
+ for(n = 0; n < 27; n++)
+ {
+ if (n != i && code[n] == buff[f])
+ {
+ return 0;
+ }
+ }
+
+ code[i] = buff[f];
+ }
+ }
+
+ return 1;
+}
+
int main(int argc, char *argv[])
{
int no_chars;
@@ -54,10 +137,10 @@ int main(int argc, char *argv[])
i = atoi(argv[f+2]);
- if (i == 0)
+ if (i < 1 || i > 27)
{
chars[f].is_letter = 1;
- chars[f].letter = argv[f+2][0];
+ chars[f].letter = tolower((unsigned char)argv[f+2][0]);
chars[f].number = 0;
}
else
@@ -77,6 +160,13 @@ int main(int argc, char *argv[])
while(fgets(buff, sizeof buff, fp))
{
+ PrepLine(buff);
+
+ if (CheckLettersAndLength(buff, chars, no_chars) &&
+ CheckNumbers(buff, chars, no_chars))
+ {
+ printf("%s\n", buff);
+ }
}
return EXIT_SUCCESS;