用C语言在omp中并行运行组合(字典顺序)?

问题描述 投票:0回答:0

我需要帮助。我无法让这个组合生成算法(按字典顺序)并行工作。算法取自Rosettacode网站,链接为:https://rosettacode.org/wiki/Combinations#Lexicographic_ordered_generation

使用 omp parallel 获得了奇怪的结果。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <omp.h>
#include <string.h>

void comb(int m, int n, unsigned char *c)
{
    int i;
    for (i = 0; i < n; i++) c[i] = n - i;

    while (1) {
        #pragma omp critical
        {
        for (i = n; i--;)
            printf("%d%c", c[i], i ? ' ': '\n');
        }
        /* this check is not strictly necessary, but if m is not close to n,
           it makes the whole thing quite a bit faster */
        i = 0;
        if (c[i]++ < m) continue;

        for (; c[i] >= m - i;) if (++i >= n) return;
        for (c[i]++; i; i--) c[i-1] = c[i] + 1;
        
    }
}

int main()
{
    unsigned char buf[100];
    #pragma omp parallel
    {
        comb(5, 3, buf);
    }
    return 0;
}

我还尝试嵌入一个过滤器,例如,如果我选择跳过总共 3 个彼此相邻的数字,使用 comb(7, 5, buf) 来跳过,即。不会生成指定的行。

1 2 3 4 5 - 不生成 1 2 3 4 6 - 不生成 1 2 3 4 7 - 不生成 1 2 3 5 6 - 不生成 1 2 3 5 7 - 不生成 1 2 3 6 7 - 不生成 1 2 4 5 6 - 不生成 1 2 4 5 7 1 2 4 6 7 1 2 5 6 7 - 不生成 1 3 4 5 6 - 不生成 1 3 4 5 7 - 不生成 1 3 4 6 7 1 3 5 6 7 - 不生成 1 4 5 6 7 - 不生成 2 3 4 5 6 - 不生成 2 3 4 5 7 - 不生成 2 3 4 6 7 - 不生成 2 3 5 6 7 - 不生成 2 4 5 6 7 - 不生成 3 4 5 6 7 - 不生成

我不知道这是否有意义,但是 comb(70, 45, buf) 并跳过 4 个相邻数字将节省数百万个毫无意义且浪费时间的组合。

我多次尝试修复代码,一无所获并放弃了。请帮我修复代码。

c openmp combinations
© www.soinside.com 2019 - 2024. All rights reserved.