Skip to content

Instantly share code, notes, and snippets.

@walkingmask
Created May 14, 2015 23:04
Show Gist options
  • Select an option

  • Save walkingmask/78642c83790762fbe76e to your computer and use it in GitHub Desktop.

Select an option

Save walkingmask/78642c83790762fbe76e to your computer and use it in GitHub Desktop.
/*
*-- puzzle10.c --
* 2015/05/15(fri)
* walkingmask
* 任意の4つの数字(かぶり無し)と3つの演算子(かぶり有り)で10を作れるか(10パズル)
* 組み合わせの数は 4! * 4^3 = 24 * 64 1536通り
*-- 問題点 --
* 1 1 5 8 のような 8/(1-1/5)=10 括弧を使った計算を考慮してない
* 解決策としては,部分和同士の演算も書くことが挙げられる
* n1*n2*n3*n4 , (n1*n2)*n3*n4 , (n1*n2)*n3)*n4 , (n1*n2)*(n3*n4)
* n1*(n2*n3*n4) , n1*n2*n3*n4 ...
*-- 実行例 --
%./puzzle10
input 1st number => 1
input 2st number => 2
input 3st number => 2
input 4st number => 4
1 : 1.000000 + 2.000000 + 2.000000 + 4.000000 = 9.000000
2 : 1.000000 - 2.000000 + 2.000000 + 4.000000 = 5.000000
3 : 1.000000 * 2.000000 + 2.000000 + 4.000000 = 8.000000
4 : 1.000000 / 2.000000 + 2.000000 + 4.000000 = 6.500000
5 : 1.000000 + 2.000000 - 2.000000 + 4.000000 = 5.000000
6 : 1.000000 - 2.000000 - 2.000000 + 4.000000 = 1.000000
7 : 1.000000 * 2.000000 - 2.000000 + 4.000000 = 4.000000
8 : 1.000000 / 2.000000 - 2.000000 + 4.000000 = 2.500000
9 : 1.000000 + 2.000000 * 2.000000 + 4.000000 = 10.000000
true
*/
#include <stdio.h>
void f(int *array);
int main(){
int e_nums[6][4] = {{0,1,2,3},{0,1,3,2},{0,2,1,3},{0,2,3,1},{0,3,1,2},{0,3,2,1}};
int ope[3] = {0,0,0};
int i,j,k,p=1;
float sum;
float in_nums[4];
for(i=0;i<4;i++){
printf("input %dst number => ", i+1);scanf("%f", &in_nums[i]);
}
for(i=0;i<6;i++){
for(j=0;j<4;j++){
while(ope[2] < 4){
sum = in_nums[e_nums[i][0]];
printf("%d : %f ", p, sum); // debug
for(k=0;k<3;k++){
switch(ope[k]){
case 0:
sum += in_nums[e_nums[i][k+1]];
printf("+ "); // debug
break;
case 1:
sum -= in_nums[e_nums[i][k+1]];
printf("- "); // debug
break;
case 2:
sum *= in_nums[e_nums[i][k+1]];
printf("* "); // debug
break;
case 3:
if(in_nums[e_nums[i][k+1]] != 0){
sum /= in_nums[e_nums[i][k+1]];
printf("/ "); // debug
}else{
sum += 0;
printf("+ "); // debug
}
break;
}
printf("%f ", in_nums[e_nums[i][k+1]]); // debug
}
printf("= %f\n", sum); // debug
if(sum == 10){
printf("true\n");
return 0;
}
ope[0] += 1;
if(ope[0] == 4){
ope[0] = 0;
ope[1] += 1;
}
if(ope[1] == 4){
ope[1] = 0;
ope[2] += 1;
}
p++;
}
for(k=0;k<3;k++)ope[k]=0;
f(e_nums[i]);
}
}
printf("false\n");
return 0;
}
void f(int *array){
int temp = array[0];
array[0] = array[1];
array[1] = array[2];
array[2] = array[3];
array[3] = temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment