gpt4 book ai didi

c - C三个堆栈并尝试所有选项

转载 作者:行者123 更新时间:2023-11-30 21:37:21 25 4
gpt4 key购买 nike

我有三个筹码和数字,我需要的是尝试分配的所有选项。我将计算每个选项并检查其是否符合我的要求。

示例:3个数字:1 2 3
123 ||
12 | 3 |
12 || 3
1 | 23 |
1 || 23 ...

编辑:添加代码:

int array[] = { 1,2,3 };
int stackA[10];
int stackB[10];
int stackC[10];
...
printf("stackA contains 123, stackB contains, stackC contains");
printf("stackA contains 12, stackB contains 3, stackC contains");
printf("stackA contains 12, stackB contains, stackC contains 3");

最佳答案

编辑:这是用于计算所有可能性的有效C代码:

#include <stdio.h>
#include <stdlib.h>

/* exponentiation: base b, exponent n */
int power(int b, unsigned int n)
{
int result = 1;

while (n != 0)
{
if ((n & 1) == 1)
{
result *= b;
}

n = n >> 1;
b *= b;
}

return result;
}

void print_instance_of_solution_set(int* a, char** stack, int number_of_stacks, unsigned int number_of_elements)
{
int k, j;

for (k = 0; k < number_of_stacks; k++)
{
printf("Stack %i = { ", k);
for (j = 0; j < number_of_elements; j++)
{
if (stack[k][j] == 1)
{
printf("%i ", a[j]);
}
}
printf("}; ");
}
printf("\n");
}

int main()
{
/* configuration parameters */
const int number_of_stacks = 3;
const unsigned int number_of_elements = 5;
int a[] = { 0, 2, 4, 6, 8 }; /* has to contain number_of_elements elements */

/* other variables */
int i, j, k;
int total_count;
char** stack;

/* allocate memory for stacks */
stack = (char**)malloc(number_of_stacks*sizeof(char*) + number_of_stacks*number_of_elements*sizeof(char));
if (stack == 0)
{
fprintf(stderr, "Memory allocation error!\n");
return -1;
}
for (i = 0; i < number_of_stacks; i++)
{
stack[i] = (char*)stack + number_of_stacks*sizeof(char*) + i*number_of_elements*sizeof(char);
}

/* calculate cardinality of solution set */
/* the cardinality of solution set is number_of_stacks raised to the power number_of_elements */
total_count = power(number_of_stacks, number_of_elements);

/* iterate over all instances */
for (i = 0; i < total_count; i++)
{
int tmp = i;
for (j = 0; j < number_of_elements; j++)
{
for (k = 0; k < number_of_stacks; k++)
{
stack[k][j] = (k == tmp % number_of_stacks) ? 1 : 0;
}
tmp /= number_of_stacks;
}

/* output of stack elements */
print_instance_of_solution_set(a, stack, number_of_stacks, number_of_elements);
}

return 0;
}

关于c - C三个堆栈并尝试所有选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34483364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com