私はCを学ぼうとしていますが、そのための良い方法は、Pythonで行ったプログラミングの実践の問題をやり直すことだと思いました。私は現在これに取り組んでいます。
私の解決策:
def main():
nums = ["10", "9", "8", "7", "6", "5", "4", "3", "2", "1"]
ops = ["+", "-", "*", "/", ""]
recursive(nums, ops, "", 0)
def recursive(nums, ops, current_str, num_ind):
if num_ind == len(nums)-1:
# print current_str + nums[num_ind]
if eval(current_str + nums[num_ind]) == 2013:
print current_str + nums[num_ind]
return 0
else:
current_str = current_str + nums[num_ind]
num_ind += 1
for i in range(len(ops)):
recursive(nums, ops, current_str+ops[i], num_ind)
Pythonは、関数呼び出しごとに新しい文字列を作成する再帰関数呼び出しを実行するときに、いくつかの魔法を実行します。つまり、「」は「10」になり、「10 +」、「10-」、「10 *」、「10 /」、「すべての順列に対して10"など。そのprintステートメントのコメントを外した場合の例:
10+9+8+7+6+5+4+3+2+1
10+9+8+7+6+5+4+3+2-1
10+9+8+7+6+5+4+3+2*1
10+9+8+7+6+5+4+3+2/1
10+9+8+7+6+5+4+3+21
Cでのメモリ割り当てと文字列を実際に使用する必要があることを見て、PythonがCで示すような「フォーク」動作を実行することさえ可能ですか?
アップデート:
理解した、
int recursive(char** nums, char** ops, char* current_str, int num_ind){
int i, ret;
char new_str[100];
num_ind++;
if(num_ind == 9){
//printf("%s\n", strcat(current_str,nums[num_ind]));
ret = eval(strcat(current_str, nums[num_ind]));
if(ret == 2013){
printf("%s\n", current_str);
}
return 0;
}
for(i=0; i<5; i++){
strcpy(new_str, current_str);
strcat(new_str, nums[num_ind]);
recursive(nums, ops, strcat(new_str, ops[i]), num_ind);
}
}