How do you iterate over all configurations of m variables belonging to the same domain of size n?

為{幸葍}努か 提交于 2019-12-05 14:52:28

You can simply use recursion.

Some pseudo-code:

void someFunction(int[] arr, int n, int depth)
{
  if (depth == 0)
  {
    // do something with the stored elements
    return;
  }

  for (int i = 0; i < n; i++)
  {
    // store arr[i]
    someFunction(arr, n, depth-1);
  }
}

There are a few ways to store arr[i]. One way could be to pass an array of size initialDepth down via the recursive call, along with the current index in that array. We increase the index on every recursive call, and put arr[i] at the current index. Then, when the depth == 0 if-statement triggers, we'll have an array containing a permutation, which we could do whatever with.


This, as your code, would repeat elements (i.e. one permutation will consist exclusively of the first element repeated a few times). If you wish to avoid this, you can instead swap the first element with each other element at the first step, then recurse, swapping the second element with each other element at the second step, and so on.

void someFunction(int[] arr, int n, int pos, int depth)
{
  if (pos == depth)
  {
    // do something with the elements in arr from 0 to pos
    return;
  }

  for (int i = pos; i < n; i++)
  {
    // swap arr[pos] and arr[i]
    someFunction(arr, n, pos+1, depth);
    // swap arr[pos] and arr[i] back
  }
}

Call with someFunction(inputArray, n, 0, desiredDepth).

Use backtracking (depth-first search). The general idea will be something like this:

void Generate(int n) {
    if ((0..n).count(i => used[i]) >= NUMBER_OF_ELEMENTS_DESIRED_FOR_A_PERMUTATION) {
        print this permutation;
        return;
    }
    used[n] = true;
    foreach (int next in (0..n).where(i => !used[i])) 
        Generate(next);
    used[n] = false;
}

You can be use recursion, Something like this:

public static void main(String[] args) {
        char[] alphabet = new char[] {'a','f','j'};
        possibleStrings(2, alphabet,"");
    }

    public static void possibleStrings(int maxLength, char[] alphabet, String curr) {
        if(curr.length() == maxLength) {
            System.out.println(curr);
        } else {
            for(int i = 0; i < alphabet.length; i++) {
                String oldCurr = curr;
                curr += alphabet[i];
                possibleStrings(maxLength,alphabet,curr);
                curr = oldCurr;
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!