Last active
August 29, 2015 14:21
-
-
Save plus7/49cd09379bbdae0bbcb9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* http://qiita.com/tag1216/items/25ff0f957340c54ae73c */ | |
/* | |
usage: ./a.out|sed -e "s/ //g" | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <math.h> | |
char *template="1 2 3 4 5 6 7 8 9"; | |
int gen_pattern(char *buf){ | |
static int state; | |
if(state == pow(3,8)){ | |
return 0; | |
} | |
memcpy(buf, template, strlen(template)+1); | |
int i, tmp; | |
tmp = state; | |
for(i = 0; i < 8; i++){ | |
switch(tmp % 3){ | |
case 0: | |
buf[i*2 + 1] = ' '; | |
break; | |
case 1: | |
buf[i*2 + 1] = '+'; | |
break; | |
case 2: | |
buf[i*2 + 1] = '-'; | |
break; | |
} | |
tmp = tmp / 3; | |
} | |
state++; | |
return 1; | |
} | |
int sum(int *array, int count){ | |
int tmp = 0; | |
int i; | |
for(i = 0; i < count; i++){ | |
tmp += array[i]; | |
} | |
return tmp; | |
} | |
#define PLUS 0 | |
#define MINUS 1 | |
int parse_pattern(char *pattern){ | |
int i; | |
int nums[9]; | |
int sign = PLUS; | |
int curidx = 0; | |
for(i = 0; i < 9; i++){ | |
nums[i] = 0; | |
} | |
for(i=0; i < strlen(template)+1; i++){ | |
switch(pattern[i]){ | |
case '+': | |
if(sign == MINUS) nums[curidx] *= -1; | |
sign = PLUS; | |
curidx++; | |
break; | |
case '-': | |
if(sign == MINUS) nums[curidx] *= -1; | |
sign = MINUS; | |
curidx++; | |
break; | |
case '\0': | |
if(sign == MINUS) nums[curidx] *= -1; | |
curidx++; | |
break; | |
case ' ': | |
nums[curidx] *= 10; | |
break; | |
default: | |
nums[curidx] += (pattern[i] - '0'); | |
} | |
} | |
return sum(nums, 9); | |
} | |
int main(void){ | |
char *buf = malloc(strlen(template)+1); | |
int i, rv; | |
while(gen_pattern(buf)){ | |
rv = parse_pattern(buf); | |
if(rv==100){ | |
printf("%s = %d\n", buf, rv); | |
} | |
} | |
free(buf); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment