Variable Number of Nested For Loops

后端 未结 3 2088
盖世英雄少女心
盖世英雄少女心 2021-02-08 12:03

I\'m making a word unscrambler in java. Right now I have a program that can print all rearrangements of 3 letters chosen from a word with 3 or more letters (no repeats). So for

3条回答
  •  攒了一身酷
    2021-02-08 12:57

    Based on what @DrYap said, I wrote this (it's a little different than his):

    Here is the code to start it off:

    for(int i = 1; i <= len; i++)
    {
        newWords.add(new ArrayList());
        loop(i);
    }
    

    Here is the loop method. A lot of the variables were declared as instance variables so I don't have to pass them into the parameter:

    public static void loop(int level)
    {
        if (level == 0)
        {
            int pos = indices.size() - 1;
            int pos2 = newWords.get(pos).size();
            newWords.get(pos).add("");
            for (Integer letIndex : indices)
            {
                String previous = newWords.get(pos).get(pos2);
                newWords.get(pos).set(pos2, previous + lets.get(letIndex));
            }
        }
        else
        {
            for (int i = 0; i < len; i++)
            {
                if (!indices.contains(i))
                {
                    int indicesIndex = indices.size();
    
                    indices.add((Integer) i);
                    loop(level - 1);
                    indices.remove(indicesIndex);
                }
            }
        }
    }
    

提交回复
热议问题