0

我正在设计一个半随机交织器。有时它可以工作,但有时即使是小的矢量长度也需要很多时间。谁能帮我写代码?

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

1 回答 1

1

点击演示

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

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

于 2012-07-12T16:00:53.023 回答