c - How do I get every possible array with 4 given digits? -



c - How do I get every possible array with 4 given digits? -

i have 4 digits in array in c, , i'd find algorithm can create every possible array (24 possibilities) without writing 24 lines of code if possible. if have array {1, 2, 3, 4} i'd next arrays: {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, 1, 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} idea? in advance!

i'm unaware of function standard c library implements functionality, can steal c++. i'm using implementation of std::next_permutation here. since iterators don't exist in c, can simple typedef.

// bool typedefs #include <stdbool.h> #define int* // swaps contents pointed 2 iterators void iter_swap(it a, b) { int tmp = *a; *a = *b; *b = tmp; } // reverses range void reverse(it first, last) { while ((first != last) && (first != --last)) { iter_swap(first++, last); } } int next_permutation(it begin, end) { if (begin == end) homecoming false; = begin; ++i; if (i == end) homecoming false; = end; --i; while (true) { j = i; --i; if (*i < *j) { k = end; while (!(*i < *--k)) /* pass */; iter_swap(i, k); reverse(j, end); homecoming true; } if (i == begin) { reverse(begin, end); homecoming false; } } } int main() { int arr[] = { 1, 2, 3, 4 }; { (unsigned = 0; < 4; ++i) printf("%d ", arr[i]); printf("\n"); } while(next_permutation(arr, arr + 4)); homecoming (0); }

c arrays

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -