如何获得4个给定数字的每个可能数组?

时间:2014-10-12 17:21:46

标签: c arrays

我在C中的数组中有4个数字,我想找到一个可以创建每个可能的数组(24种可能性)的算法,如果可能的话,不用编写24行代码。所以,如果我有数组{1,2,3,4},我想得到以下数组:
{1,2,3,4} {1,2,4,3} {1,3,2,4} {1,3,4,2} {1,4,2,3} {1,4,3,2} {2,1,3,4} {2,1,4,3} {2,3,4,4} {2,3,4,1} {2,4,1,3} {2,4,3,1} {3,1,2,4} {3,1,4,2} {3,2,1,4}
{3,2,4,1} {3,4,1,2} {3,4,2,1} {4,1,2,3} {4,1,3,2} {4,2,1,3} {4,2,3,1} {4,3,1,2} {4,3,2,1}
任何的想法?提前谢谢!

2 个答案:

答案 0 :(得分:1)

我不知道实现此功能的标准C库的任何功能,但您可以从C ++中窃取它。我正在使用std::next_permutation from here的实现。由于C中不存在迭代器,因此可以执行简单的typedef。

// For bool typedefs
#include <stdbool.h>

#define It int*

// Swaps the contents pointed by two iterators
void iter_swap(It a, It b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

// Reverses a range
void reverse(It first, It last)
{
    while ((first != last) && (first != --last)) {
        iter_swap(first++, last);
    }
}

int next_permutation(It begin, It end) {
    if (begin == end)
        return false;

    It i = begin;
    ++i;
    if (i == end)
        return false;

    i = end;
    --i;

    while (true) {
        It j = i;
        --i;

        if (*i < *j) {
            It k = end;

            while (!(*i < *--k))
                /* pass */;

            iter_swap(i, k);
            reverse(j, end);
            return true;
        }

        if (i == begin) {
            reverse(begin, end);
            return false;
        }
    }
}

int main() 
{
    int arr[] = { 1, 2, 3, 4 };

    do {
        for (unsigned i = 0; i < 4; ++i)
            printf("%d ", arr[i]);
        printf("\n");
    } while(next_permutation(arr, arr + 4));

    return (0);
}

答案 1 :(得分:0)

c ++中的简单答案:

#include <stdio.h>
#include <algorithm>
void main()
{
    int tab[] = { 1, 2, 3, 4 };
    do
    {
        for (auto v : tab)
            printf("%d ", v);
        puts("");
    } while (std::next_permutation(tab, tab + 4));
}

阅读一些关于生成下一个排列的文章(算法并不难)并在c中编写nex_permutation函数,例如:std::next_permutation Implementation Explanation