Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <err.h>
- #include <stdio.h>
- #include <stdlib.h>
- struct press_info {
- char pi_button;
- int pi_count;
- struct press_info *pi_next;
- };
- int
- get_press_info(const char *string, struct press_info **press_info)
- {
- struct press_info start = {0};
- struct press_info *it = &start;
- while (*string) {
- it->pi_next = malloc(sizeof(struct press_info));
- if (!it->pi_next) return -1;
- it = it->pi_next;
- it->pi_button = *string;
- it->pi_count = 0;
- it->pi_next = NULL;
- while (*string == it->pi_button) {
- string++;
- it->pi_count++;
- }
- }
- *press_info = start.pi_next;
- return 0;
- }
- int
- press_info_to_char(const struct press_info *pi,
- const struct press_info *previous)
- {
- const char lookup_table[12][5] = {"1", "2abc", "3def", "4ghi",
- "5jkl", "6mno", "7pqrs", "8tuv",
- "9wxyz", "*^", "#.,", "0+ "};
- const int data_sizes[] = {1, 4, 4, 4, 4, 4, 5, 4, 5, 2, 2, 3};
- if (pi->pi_button == '0') {
- if (previous &&
- previous->pi_button != '1' &&
- pi->pi_count == 1 &&
- pi->pi_next &&
- pi->pi_next->pi_button == previous->pi_button)
- return 0;
- return lookup_table[11][pi->pi_count % data_sizes[11]];
- }
- for (int i = 0; i < 11; i++)
- if (lookup_table[i][0] == pi->pi_button)
- return lookup_table[i][pi->pi_count % data_sizes[i]];
- return -1;
- }
- int
- main(int argc, char **argv)
- {
- if (argc != 2) errx(1, "usage: %s [keypad sequence]", *argv);
- int button;
- struct press_info *pi = NULL, *prev = NULL;
- if (get_press_info(argv[1], &pi))
- errx(1, "unable to read input");
- while (pi) {
- if ((button = press_info_to_char(pi, prev)) == -1)
- errx(1, "unable to parse character: %c", pi->pi_button);
- else if (button)
- putchar(button);
- prev = pi;
- pi = pi->pi_next;
- }
- putchar('\n');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement