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

c++ Count the occurrence of each pair of element in txt file

本文关键字:元素 txt 计算 文件 c++      更新时间:2023-10-16

我有文本文件为:

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 memoryn";
    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";
}

货币对映射到计数器要简单得多。下面是它的样子:

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';
}

这是一个现场演示。

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

您的要求缺乏如何从数据行生成对。
示例 1,使用 4 1 2 3 4
这对是<1,2> <3,4>吗?
还是<1,2> <2,3> <3,4>?
或所有渗透:
<1, 1> <1, 2> <1, 3> <1, 4>,
<2, 1> <2, 2> <2, 3> <2, 4>,
<3, 1> <3, 2> <3, 3> <3, 4>,
<4, 1> <4, 2> <4, 3> <4, 4>?

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