Sucessfully does english to morse, but fails with morse to english (probaly the best I'll get):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char e[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
' '
};
const char *m[] = {
".- ", "-.. ", "-.- ", "-.. ", ". ", "..-. ", "--. ", "....",
"..", ".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ",
"--.- ", ".-. ", "... ", "- ", "..- ", "...- ", "...- ",
".-- ", "-..- ", "-.-- ", "--.. ",
".---- ", "..--- ", "...-- ", "....- ", "..... ", "-.... ",
"--... ", "---.. ", "----. ", "----- ",
" "
};
void morse(char []);
void unmorse(char []);
void help(char []);
main(int argc, char *argv[]) {
if (argc < 3 || strstr(argv[1], "-h") != NULL) {
help(argv[0]);
exit(1);
}
if (strstr(argv[1], "-e") != NULL) {
morse(argv[2]);
} else if (strstr(argv[1], "-m") != NULL) {
unmorse(argv[2]);
} else {
fprintf(stderr, "unkown option: %s\n\n", argv[1]);
help(argv[0]);
exit(1);
}
}
void morse(char s[]) {
int i = 0, j;
while (s != '\0') {
j = 0;
while (s != e[j] && s != (e[j] + 'a' - 'A')) {
j++;
}
printf("%s", m[j]);
i++;
}
printf("\n");
}
void unmorse(char s[]) {
int i = 0, j;
while (s != '\0') {
j = 0;
while (strstr(&s, m[j]) != NULL &&
strstr(m[j], &s) != NULL) {
j++;
}
printf("%s", e[j]);
i++;
}
}
void help(char prog[]) {
fprintf(stderr, "usage: %s [options] [string]\n"
"options:\n\t-e\tenglish to morse\n"
"\t-m\tmorse to english\n\t-h\tprint this\n",
prog);
}
I got another challenge (yes, it's conversion):
Challenge: Sucessfully implement rot13: english to rot13.
Difficulty: (really) Easy
Helpful Information: http://en.wikipedia.org/wiki/ROT13
Rot was really easy (though I wasn't anal about error checking):
#include <stdio.h>
char rot(char [], int, int);
char lower(char [], int);
main(int argc, char *argv[]) {
int i = 0;
if (argc == 1) {
fprintf(stderr, "usage: %s [rot] [string]\n", argv[0]);
}
while (argv[2] != '\0') {
argv[2] = lower(argv[2], i);
argv[2] = rot(argv[2], i, atoi(argv[1]));
i++;
}
printf("%s\n", argv[2]);
}
char lower(char s[], int i) {
if (s <= 90 && s >= 65)
s += 32;
return s;
}
char rot(char s[], int i, int rotnum) {
return (s > 109) ? (s -= rotnum) : (s += rotnum);
}