【问题标题】:generation of all the possible binary inputs for a lookup table为查找表生成所有可能的二进制输入
【发布时间】:2015-04-25 22:54:52
【问题描述】:

我必须为 C 代码中的查找表生成所有可能的输入。我确信它必须以递归方式完成,但我找不到任何方法。你有什么建议吗?谢谢

int main()
{
    int i,j,k;
    int M,N;
    int comb;
    FILE *fp;

    printf("Insert M and N values \n");
    scanf("%d", &M);
    scanf("%d", &N);
    comb = (int) pow(2.0,M);

    int A[comb][M];
    int B[comb][N];

    time_t t;
    srand((unsigned) time(&t));
    fp = fopen("lut.txt","w"); 
    fprintf(fp, "INPUTPINS - %d\n", M);
    fprintf(fp, "OUTPUTPINS - %d\n", N);
    for (i=0; i< comb; i++)
    {
        for(j= 0; j<M; j++)
        {
            fprintf(fp,"%d", A[i][j]);
        }
        fprintf(fp, " - ");
        for (k=0; k<N; k++)
        {
            B[i][k] = rand()%2;
            fprintf(fp, "%d", B[i][k]);
        }
        fprintf(fp,"\n");
    }
    fclose(fp);
    return 0;
}

我需要为我的矩阵 A 生成值,它将包含所有可能的 2^n 输入,而输出将是随机的。

【问题讨论】:

  • 只有在您与我们分享您的一些代码时,才能提出建议。

标签: c binary


【解决方案1】:

我不明白您为什么需要数组或递归来查找权限。 perms 是 0 到 2^M - 1 范围内的每个数字。您所需要的只是一个以二进制输出的函数。对scanf()fopen() 进行一些错误检查会更好。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void pbinary(FILE *fp, int val, int bits)
{
    int mask = 1 << (bits-1);
    while (bits-- > 0) {
        fprintf (fp, "%d", (val & mask) != 0);
        mask >>= 1;
    }
}

int main()
{
    int i, M, N, comb;
    FILE *fp;
    printf("Insert M and N values \n");
    scanf("%d", &M);
    scanf("%d", &N);
    comb = 1 << M;

    srand((unsigned)time(NULL));
    fp = fopen("lut.txt","w"); 
    fprintf(fp, "INPUTPINS - %d\n", M);
    fprintf(fp, "OUTPUTPINS - %d\n", N);
    for (i=0; i< comb; i++)
    {
        pbinary (fp, i, M);
        fprintf(fp, " - ");
        pbinary (fp, rand(), N);
        fprintf(fp,"\n");
    }
    fclose(fp);
    return 0;
}

程序输入

Insert M and N values
3
4

文件输出

INPUTPINS - 3
OUTPUTPINS - 4
000 - 1001
001 - 0101
010 - 0110
011 - 0100
100 - 1001
101 - 0011
110 - 0111
111 - 1111

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多