c ++计算txt文件中每对元素的出现次数

时间:2014-01-14 01:15:41

标签: c++

我的文本文件为:

4 1 2 3 4

3 3 1 2

3 4 2 1

2 4 3

其中每行中的第一个元素表示每行中元素的总数

我想计算每对元素的出现次数并打印结果,这样:

(1,2)= 3次

所以我不需要计算和打印(2,1)

最终结果必须是:

1 2 = 3

1 3 = 3

1 4 = 2

2 3 = 2

2 4 = 2

3 4 = 2

到目前为止这是代码:

//global values:
    int count2[10][10]; // to store the count of  occurrence of each pair           
    int pair2[10][10];// to store the pair of element
    int Totalnum; // total number of elements in txt file=4 
    int TotLines; //    total number of lines in txt file=4

    // main fun
    int RowSize;
    int item1, item2;
    int maxSize = 0;
    FILE *fp;
    int i, j, k;


// Initialize
count2[10][10] = (int )malloc(sizeof(int)* Totalnum);
pair2[10][10] = (int )malloc(sizeof(int)*  Totalnum);
if ((count2 == NULL) || (pair2 == NULL)) {
    cout << "out of memory\n";
    exit(1);
}

for (i = 0; i <  Totalnum; i++)
for (j = 0; j <  Totalnum; j++){
    count2[i][j] = 0;
    pair2[i][j] =0; 
}

/* scan DB to count the frequency of each pair item */

if ((fp = fopen(dataFile, "r")) == NULL) // Database file
{
    cout << "Can't open data file " << dataFile << "\n";
    exit(1);
}

/* Scan each line of the DB */
for (i = 0; i < TotLines; i++) 
{
    /* Read the row size */
    fscanf(fp, "%d", &RowSize);


    /* Read the items in the row*/
    for (j = 0; j < RowSize; j++)
    {
        fscanf(fp, "%d", &item1);
        for (k = j + 1; k < RowSize; k++)
        {
            fscanf(fp, "%d", &item2);
            if (pair2[item1][item2] == pair2[item2][item1])
            {
                count2[item1][item2] ++;
                count2[item2][item1] = count2[item1][item2];
            }
            else
                count2[item1][item2]++;
       }
    }

}
fclose(fp);

for (j = 0; j <= Totalnum; j++){
    for (k = j + 1; k <= Totalnum; k++)
        printf("%d  [%d] ", pair2[j][k], count2[j][k]);
            cout <<  "\n";
}

2 个答案:

答案 0 :(得分:2)

将对映射到计数器要简单得多。这是它的样子:

std::map<std::pair<int, int>, int> pairToCount;

while (in >> a >> b)
{
    auto it = pairToCount.find(std::make_pair(b, a));

    ++pairToCount[
        (it != pairToCount.end()) ? std::make_pair(b, a)
                                  : std::make_pair(a, b) ];
}

for (const auto& p : pairToCount)
{
    std::cout << "(" << p.first.first << " " << p.first.second << ") = "
                                             << p.second << '\n';
}

Here is a Live Demo.

答案 1 :(得分:0)

在开始计算对之前,您必须识别它们。

您对数据行中如何生成对的要求不足 实施例1,使用4 1 2 3 4
  是否对&lt; 1,2&gt; &LT; 3,4 GT ;?
  或者&lt; 1,2&gt; &lt; 2,3&gt; &lt; 3,4&gt;?   或所有permations:
     &lt; 1,1&gt; &lt; 1,2&gt; &lt; 1,3&gt; &lt; 1,4&gt;,
     &lt; 2,1&gt; &lt; 2,2&gt; &lt; 2,3&gt; &lt; 2,4&gt;,
     &lt; 3,1&gt; &lt; 3,2&gt; &lt; 3,3&gt; &lt; 3,4&gt;,
     &lt; 4,1&gt; &lt; 4,2&gt; &lt; 4,3&gt; &lt; 4,4&gt;?

一旦您决定如何生成对,使用std::map将更容易计算。