Created
January 18, 2026 10:53
-
-
Save uap-universe/a1b56f6c4c9552e1824ce027947413f9 to your computer and use it in GitHub Desktop.
Enumerates all index selections for a dynamic number of arrays with different sizes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <stdbool.h> // not required in C23 anymore | |
| /** | |
| * Enumerate all index combinations. | |
| * | |
| * The @p indices array shall be initially @c NULL and | |
| * will be allocated by this function and must be passed | |
| * free(). | |
| * | |
| * @param indices the target index array that will be enumerated | |
| * @param sizes the array containing the non-zero sizes | |
| * @param len the length of @p sizes / the number of arrays | |
| * @return @c true if a new combination was generated, | |
| * @c false if all combinations have been enumerated | |
| */ | |
| bool enumerate_selections(size_t** indices, const size_t* sizes, size_t len) { | |
| if (*indices == NULL) { // you may want to use nullptr in C23 | |
| *indices = calloc(len, sizeof(size_t)); | |
| return true; | |
| } | |
| for (size_t i = 0; i < len; i++) { | |
| (*indices)[i]++; | |
| if ((*indices)[i] >= sizes[i]) { | |
| (*indices)[i] = 0; | |
| if (i == len - 1) { | |
| return false; | |
| } | |
| } else { | |
| break; | |
| } | |
| } | |
| return true; | |
| } | |
| // A simple test program. | |
| int main(void) { | |
| // expected output is an enumeration of all | |
| // combination of indices for five hypothetical | |
| // arrays with the sizes stored in the test array | |
| size_t test[5] = {3, 7, 2, 4, 5}; | |
| size_t *indices = NULL; | |
| while (enumerate_selections(&indices, test, 5)) { | |
| for (size_t i = 0 ; i < 5 ; i++) { | |
| printf("%zu ", indices[i]); | |
| } | |
| putchar('\n'); | |
| } | |
| free(indices); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment