如何用C语言解决这个数组问题



我有两个数组:int element[3] = {0, 1, 2};int quantity[3] = {2, 3, 4};现在我想要一个结果数组,它将有两个零,三个一和四个二。int result[2+3+4] = {0, 0, 1, 1, 1, 2, 2, 2, 2};如何使用循环完成此操作?

您需要计算结果数组中的元素数量,并使用计算值声明可变长度数组,或者动态分配这样的数组。

例如

int quantity[3] = {2, 3, 4};
size_t n = 0;
for ( size_t i = 0; i < 3; i++ )
{
n += quantity[i];
}
int result[n];
// or
// int *result = malloc( n * sizeof( int ) );

然后在嵌套循环中,您需要填充结果数组。

例如

for ( size_t i = 0, j = 0; i < 3; i++ )
{
for ( size_t k = 0; k < quantity[i]; k++ )
{
result[j++] = element[i];
}
}

首先我们需要计算结果数组的大小。然后开始一次填充每个元素的结果数组。当我们填充结果数组时,我们需要增加索引。

int elementSize = sizeof(element)/sizeof(element[0]);
int resultSize = 0;
//pre calculating the size of result array
for(int i=0;i<elementSize;i++ ) {
resultSize += quantity[i];
}
int result[resultSize], currIndex = 0;
//picking each element
for(int i = 0;i< elementSize; i++ ) {
int currElement = element[i];
int currQuantity = quantity[i];
//filling the current element required no of times in the result array
while(currQuantity--) {
result[currIndex] = currElement;
currIndex++;
}
}
//just a for loop to check the elements inside result array
for(int i=0;i<resultSize;i++)
printf("%dn",result[i]);

最新更新