Вопрос

I have a permutation recursive array which works fine but I need to store the result not just print them out,I have to store each print out in a separate array or the whole in one array

here is the original:

public static void Permute(String soFar, String rest)  
        {  
           if (rest.isEmpty())  
           {
               System.out.println(soFar);  

           }           
            else  
           {  
               for (int i =0; i < rest.length(); i++)  
                {  
                    String next = soFar + rest.charAt(i);  
                    String remaining  = rest.substring(0,i) + rest.substring(i+1);  
                    Permute(next,remaining);  
                }  
           }  
        }  

and I changed it but the problem is that return arr is not proper in there I should do something else because the arr would become empty because other recursive function would be called and I don't want it

public static String Permute(String soFar, String rest,String arr)  
    {  
       if (rest.isEmpty())  
       {
        //   System.out.println(soFar);  
       arr+=soFar;
       }           
        else  
       {  
           for (int i =0; i < rest.length(); i++)  
            {  
                String next = soFar + rest.charAt(i);  
                String remaining  = rest.substring(0,i) + rest.substring(i+1);  
                Permute(next,remaining,arr);  
            }  
       }  
    return arr;
    }  
Это было полезно?

Решение

Change your arr parameter to be a List. Then instead of the println() just keep adding to this List. Also, when you call permute for the first time, make sure you pass in an allocated List. Like so:

public void ParentFunction()
{
    List<String> results = new ArrayList<String>();
    Permute(..., ..., results);
    // Now you have all results inside "results" variable.
}

public static void Permute(String soFar, String rest, List<String> results)  
{
    if (rest.isEmpty())  
    {
        //System.out.println(soFar);  
        results.add(soFar); // ADD TO RESULT LIST
    }           
    else  
    {  
        for (int i = 0; i < rest.length(); i++)  
        {  
            String next = soFar + rest.charAt(i);  
            String remaining  = rest.substring(0, i) + rest.substring(i + 1);  
            Permute(next, remaining, results);  
        }  
    }
} 

Другие советы

One way;

  1. Create an instance variable of type List: List<String> myList = new ArrayList<String>();
  2. Replace System.out.println(soFar); with myList.add(soFar);
  3. Probably in the end convert your list to an array: String[] arr = (String[]) myList.toArray();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top