Skip to content

Instantly share code, notes, and snippets.

@zlargon
Last active May 2, 2016 09:05
Show Gist options
  • Save zlargon/57c02aa875d34bf3f912f1d2d1efdde8 to your computer and use it in GitHub Desktop.
Save zlargon/57c02aa875d34bf3f912f1d2d1efdde8 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define S_LEN 2048
#define DIGIT_LEN 10
struct {
char c;
char * word;
size_t digit;
} Rule[10] = {
// ROUND ONE
{ 'Z', "ZERO", 0 },
{ 'W', "TWO", 2 },
{ 'U', "FOUR", 4 },
{ 'X', "SIX", 6 },
{ 'G', "EIGHT", 8 },
// ROUND TWO
{ 'H', "THREE", 3 },
{ 'F', "FIVE", 5 },
{ 'S', "SEVEN", 7 },
// ROUND TREE
{ 'O', "ONE", 1 },
{ 'I', "NINE", 9 }
};
void solution (const char * input, const size_t inputLen, int digitCounter[DIGIT_LEN]);
int main (int argc, char const * argv[]) {
struct {
FILE * in;
FILE * out;
} stream = {
// .in = stdin,
// .out = stdout,
.in = fopen("A-large-practice.in", "r"),
.out = fopen("A-large-practice.out", "w"),
};
int T;
fscanf(stream.in, "%d", &T);
for (int caseIndex = 1; caseIndex <= T; caseIndex++) {
// get S
char S[S_LEN] = {};
fscanf(stream.in, "%s", S);
// get result
int counter[DIGIT_LEN] = {};
solution(S, strlen(S), counter);
// show result
fprintf(stream.out, "Case #%d: ", caseIndex + 1);
for (int digit = 0; digit < DIGIT_LEN; digit++) {
for (int i = 1; i <= counter[digit]; i++) {
fprintf(stream.out, "%d", digit);
}
}
fprintf(stream.out, "\n");
}
return 0;
}
// O(n)
void solution (const char * input, size_t inputLen, int digitCounter[DIGIT_LEN]) {
// reset (0-9)
memset(digitCounter, 0, DIGIT_LEN);
// the number of each character (A-Z)
int characterCounter[26] = {};
for (size_t i = 0; i < inputLen; i++) {
size_t index = input[i] - 65;
characterCounter[index]++;
}
for (size_t i = 0; inputLen > 0 && i < DIGIT_LEN; i++) {
const char c = Rule[i].c;
const int num = characterCounter[c - 65]; // number of word
if (num == 0) {
continue;
}
// result
digitCounter[Rule[i].digit] = num;
// reduce number of character
const char * word = Rule[i].word;
const size_t len = strlen(word);
for (int j = 0; j < len; j++) {
characterCounter[word[j] - 65] -= num;
}
// reduce len
inputLen -= num * len;
}
// check: length should be zero
if (inputLen != 0) {
puts("\n\n");
puts("Error!!!");
printf("%s\n", input);
printf("len = %zu\n", inputLen);
for (int i = 0; i < DIGIT_LEN; i++) {
printf("%d ", digitCounter[i]);
}
puts("\n\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment