Skip to content

Instantly share code, notes, and snippets.

@fsouza
Last active December 10, 2015 09:48
Show Gist options
  • Select an option

  • Save fsouza/4416288 to your computer and use it in GitHub Desktop.

Select an option

Save fsouza/4416288 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#define readline(buf) do { \
int j, c; \
for(j = 0; (c = getchar()) != '\n' && c != EOF; j++) { \
buf[j] = c; \
} \
buf[j] = '\0'; \
} while(0)
#define readinput(input, output, n, limit, olimit) do { \
char buf[8]; \
int i; \
readline(buf); \
n = atoi(buf); \
input = (char **)malloc(n * sizeof(char *)); \
output = (char **)malloc(n * sizeof(char *)); \
for(i = 0; i < n; i++) { \
input[i] = (char *)malloc(limit * sizeof(char)); \
readline(input[i]); \
output[i] = (char *)malloc(olimit * sizeof(char)); \
output[i][0] = '\0'; \
} \
} while(0)
void
free_streams(int length, int n, ...)
{
char **v;
int i, j;
va_list st;
va_start(st, n);
for(i = 0; i < n; i++) {
v = va_arg(st, char**);
for(j = 0; j < length; j++) {
free(v[j]);
}
free(v);
}
va_end(st);
}
int digits[26] = {
2, 22, 222, 3, 33, 333, 4, 44, 444, 5, 55, 555,
6, 66, 666, 7, 77, 777, 7777, 8, 88, 888, 9, 99,
999, 9999,
};
void
t9(char **input, char **output, int n)
{
int i, j, siz;
char tmp[6], *t;
for(i = 0; i < n; i++) {
siz = strlen(input[i]);
for(j = 0; j < siz; j++) {
if(input[i][j] == ' ') {
tmp[0] = ' ';
tmp[1] = '0';
tmp[2] = '\0';
} else {
sprintf(tmp, " %d", digits[input[i][j]-'a']);
}
t = tmp;
if(output[i][strlen(output[i])-1] != t[1]) {
t++;
}
strcat(output[i], t);
}
}
}
int
main(void)
{
int i, n;
char **messages, **output;
readinput(messages, output, n, 1001, 5005);
t9(messages, output, n);
for(i = 0; i < n; i++) {
printf("Case #%d: %s\n", i+1, output[i]);
}
free_streams(n, 2, messages, output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment