半随机交织器的设计

时间:2012-07-12 15:35:36

标签: c

我正在设计一个半随机交织器。有时它可以工作,但有时甚至对于小矢量长度也需要很多时间。任何人都可以帮我处理代码吗?

int i, j, s1 = 2, s2 = 5;
for (int i = 0; i < vecLen; i++) {
    IM[i] = rand() % vecLen;
    for (j = 0; j < i; j++) {
        if (IM[i] == IM[j]) {
            IM[i] = rand() % vecLen;
            j = -1;
        }
        if ((i - j) <= s1) {
            if (sqrt((IM[i] - IM[j]) * (IM[i] - IM[j])) <= s2) {
                IM[i] = rand() % vecLen;
                j = -1;
            }
        }
    }
}

for (i = 0; i < vecLen; i++) {
    DM[IM[i]] = i;
}

1 个答案:

答案 0 :(得分:1)

Click for Demo

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

#define BOOL int
#define TRUE (-1)
#define FALSE (0)

int *Generate(int n, int s1, int s2);
BOOL GenerateNext(int i, int *xs, int n, int s1, int s2);
void Shuffle(int *arr, int n);

int main(void)
{
    int n = 20, s1 = 2, s2 = 5;
    int i;
    int *xs = Generate(n, s1, s2);
    if (xs == NULL)
    {
        printf("No valid permutations.\n");
    }
    else
    {
        printf("Permutation: [ ");
        for (i = 0; i < n; i++)
        {
            if (i > 0) printf(", ");
            printf("%d", xs[i]);
        }
        printf(" ]\n");

        free(xs);
    }
}

int *Generate(int n, int s1, int s2)
{
    int *xs = (int *) malloc(sizeof(int) * n);
    if (GenerateNext(0, xs, n, s1, s2))
    {
        return xs;
    }
    free(xs);
    return NULL;
}

BOOL GenerateNext(int i, int *xs, int n, int s1, int s2)
{
    int candidates[n];
    int nCandidates = 0, candidate, j, delta;
    BOOL ok;

    if (i == n) return TRUE;

    for (candidate = 0; candidate < n; candidate++)
    {
        ok = TRUE;
        for (j = 0; j < i && ok; j++)
        {
            if (xs[j] == candidate) ok = FALSE;
            else if ((i - j) <= s1)
            {
                int delta = xs[j] - candidate;
                if (delta < 0) delta = -delta;
                if (delta <= s2) ok = FALSE;
            }
        }
        if (ok)
        {
            candidates[nCandidates++] = candidate;
        }
    }

    if (nCandidates == 0) return FALSE;

    Shuffle(candidates, nCandidates);

    for (j = 0; j < nCandidates; j++)
    {
        xs[i] = candidates[j];
        if (GenerateNext(i + 1, xs, n, s1, s2))
        {
            return TRUE;
        }
    }

    return FALSE;
}

void Shuffle(int *arr, int n)
{
    int i, j, tmp;
    for (i = 0; i < n; i++)
    {
        j = i + rand() % (n - i);
        if (j != i)
        {
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }
}

编辑:重写了答案,以确定是否有任何有效的排列。