c - 在c中为趋势线分配权重

标签 c arrays permutation

我正在尝试为一组趋势线分配一组权重。 权重位于数组中,趋势线位于数组中。我想要 最终得到所有排列:即,因此数组中的每个趋势线都得到 分配每个权重。在我的代码中,我当前得到以下输出:

output: 1 combination per line:
1.00, 1.00, 1.00, 1.00 
1.50, 1.50, 1.50, 1.50 
2.00, 2.00, 2.00, 2.00, 

但是我想要得到的是所有排列,不包括重复项。那是 我想获得权重/趋势线的所有不同可能组合:

output: 1 combination per line:
1.00, 1.00, 1.00, 1.00
1.50, 1.00, 1.00, 1.00, 
2.50, 1.00, 1.00, 1.00, 
1.00, 1.50, 1.00, 1.00, 
1.50, 1.50, 1.00, 1.00, 
2.50, 1.50, 1.00, 1.00, 
....etc

编辑:
所以我的问题是:如何更改下面的代码以便我可以生成 趋势线和​​权重的所有不同组合。例如,如果我有 2 条趋势线和 3 个权重 (1,2,3),则所有组合将为:

1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3

这是代码:

#define TRENDLINE_COUNT 4
#define WEIGHT_COUNT 3
void hhour(void)
{   
    int trendLine[TRENDLINE_COUNT];
    double weight[] = { 1, 1.5, 2 };
    FILE *myFile = fopen("s:\\data\\testdump\\ww.txt", WRITE);

    fprintf(myFile, "output: 1 combination per line :\n"    );
    for (int weightIndex = 0; wei`enter code here`ghtIndex < WEIGHT_COUNT; weightIndex++)
    {
        double currentWeight = weight[weightIndex];
        double cumulativeTrendValue = 0;

        for (int trendLineIndex = 0; trendLineIndex < TRENDLINE_COUNT; trendLineIndex++)
        {
            cumulativeTrendValue += trendLine[trendLineIndex] * currentWeight;

            fprintf(myFile, "%.02lf, ", currentWeight);
        }
        fprintf(myFile, "\n");

        // do something with cumulativeTrendValue
    }

    fclose(myFile);
}

最佳答案

我想这就是你想要的。可能有更干净的解决方案,但如果可能的话,我非常喜欢暴力破解解决方案。如果你想改变趋势线......呃,也许是具有递归可变参数函数的东西......但当我面对这种程度的疯狂时,我开始充电。

#include <stdio.h>
#include <string.h>

#define TRENDLINE_COUNT 4
#define WEIGHT_COUNT 3

double weight[] = { 1, 1.5, 2 };

int addOne(int counter[TRENDLINE_COUNT])
{
  int i=0;
  while(1)
  {
    if(counter[i]+1 >= WEIGHT_COUNT)
    {
      if( i+1 >= TRENDLINE_COUNT)
      {  return 1;}
      else
      { 
        counter[i]=0;
        i++;
      }
    }
    else
    {
      counter[i]++;
      return 0;
    }
  }
  return 0;
}

void hhr()
{
  int i;
  int counter[TRENDLINE_COUNT];  

  memset(counter, 0, sizeof(int)*TRENDLINE_COUNT);
  do 
  {
    for(i=0; i<TRENDLINE_COUNT; i++)
    { 
      //printf("%d ", counter[i]);
      printf("%f ", weight[counter[i]]);
    }
    printf("\n");
  }while(!addOne(counter));
}

int main(int argc, char **argv)
{
  hhr();
}

关于c - 在c中为趋势线分配权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820192/

相关文章:

c - 使用打印功能无法打印字符串的问题

c - C语言如何在一行中获取2个输入?

arrays - 使用递归查找数组中的最大元素

java - 不接受数组中相同的输入

c++ - 枚举完整图的哈密顿循环的算法(循环、反转、环绕或重复不计算在内的排列)

java - 提高 ArrayList 排列的效率

c - 如何在 Linux 和 C 中将文件用作互斥体?

objective-c - 如何在 OS X 上的 Objective C/C 中获取总 CPU 空闲时间?

arrays - Visual Basic 6 运行时错误 381 "Invalid Property Array Index"

python - 停止递归生成器和排列