Skip to content

Instantly share code, notes, and snippets.

@davidair
Created October 22, 2018 19:13
Show Gist options
  • Save davidair/8cd9e906eeab26083a4a3727001830ff to your computer and use it in GitHub Desktop.
Save davidair/8cd9e906eeab26083a4a3727001830ff to your computer and use it in GitHub Desktop.
#include <iostream>
#include <sstream>
void IterativeNestedLoop(int depth, int max, std::function<void(int* slots, int)> action)
{
// Initialize the slots to hold the current iteration value for each depth
int* slots = (int*)alloca(sizeof(int) * depth);
for (int i = 0; i < depth; i++)
{
slots[i] = 0;
}
int index = 0;
while (true)
{
action(slots, depth);
// Increment
slots[0]++;
// Carry
while (slots[index] == max)
{
// Overflow, we're done
if (index == depth - 1)
{
return;
}
slots[index++] = 0;
slots[index]++;
}
index = 0;
}
}
void DoStuff(int* slots, int depth) {
std::stringstream values;
for(int i = 0; i < depth; i++)
{
values << slots[i] << ", ";
}
std::cout << values.str() << std::endl;
}
int main(int argc, const char * argv[]) {
IterativeNestedLoop(3, 10, DoStuff);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment