Last active
March 15, 2019 22:55
-
-
Save maehrm/14a406b84bfb8ad00f67544c81866109 to your computer and use it in GitHub Desktop.
平成29年度秋季試験_基本情報午後問8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#define N 30 | |
const char tbl[N + 1] = " .,?abcdefghijklmnopqrstuvwxyz"; | |
int getValue(char); | |
char getChar(int); | |
char calcCheckCharacter(char [], int); | |
int validateCheckCharacter(char [], int); | |
int getValue(char c) { | |
int i; | |
for (i = 0; i < N; i++) { | |
if (tbl[i] == c) { | |
break; | |
} | |
} | |
return i; | |
} | |
char getChar(int i) { | |
return tbl[i]; | |
} | |
char calcCheckCharacter(char input[], int len) { | |
int i, value, check_value, sum = 0; | |
int is_even = 0; | |
for (i = len - 1; i >= 0; i--) { | |
value = getValue(input[i]); | |
if (is_even) { | |
sum += value; | |
} | |
else { | |
sum += (value * 2) / N + (value * 2) % N; | |
} | |
is_even = 1 - is_even; | |
} | |
check_value = (N - sum % N) % N; | |
return getChar(check_value); | |
} | |
int validateCheckCharacter(char input[], int len) { | |
int sum = 0, i, value; | |
int is_odd = 1, ret_value = 1; | |
for (i = len - 1; i >= 0; i--) { | |
value = getValue(input[i]); | |
if (is_odd) { | |
sum += value; | |
} | |
else { | |
sum += (value * 2) / N + (value * 2) % N; | |
} | |
is_odd = 1 - is_odd; | |
} | |
if (sum % N != 0) { | |
ret_value = 0; | |
} | |
return ret_value; | |
} | |
int main(void) { | |
char str[BUFSIZ] = "ipa ", c; | |
int len; | |
len = strlen(str); | |
c = calcCheckCharacter(str, len); | |
str[len] = c; | |
str[len + 1] = '\0'; | |
printf("%s\n", str); | |
printf("ipa f: %d\n", validateCheckCharacter(str, len + 1)); | |
printf("ケース1: %d\n", validateCheckCharacter("ipb f", len + 1)); | |
printf("ケース2: %d\n", validateCheckCharacter("api f", len + 1)); | |
printf("ケース3: %d\n", validateCheckCharacter("pia f", len + 1)); | |
printf("ケース4: %d\n", validateCheckCharacter(" apif", len + 1)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
平成29年度秋季基本情報午後問8 - Mae向きなブログ https://maehrm.hatenablog.com/entry/2019/03/13/212829