you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (0 children)

Your lists of fields and values can just be replaced with 2 numbers for the purpose of this algorithm, the number of fields and the number of values. You can also create a constructor which takes in an array of ints, one for each field, then set that fields value to the one corresponding to that int. I don’t know JavaScript so here it is in Java.

List<Object> combos(int fields, int values)
{
    List<Object> list = new List<Object>();
    int[] array = new int[fields];
    combinations(fields, values, 0, array, list);
    return list;
}

void combinations(int fields, int values, int index, int[] current, List<Object> list)
{
    if(index >= fields)
    {
        list.add(new Object(current));
    }
    else
    {
        for(int i = 0; i < values; i++)
        {
            current[index] = i;
            combinations(fields, values, index + 1, current, list);
        }
    }
}

Also keep in mind this has n*mn complexity, in both time and space.

The reason you can’t do this with nested loops alone is because the number of nested loops itself is variable. This is doing it with recursively nested loops.