Pull permutation from Java string

Asked 2 years ago, Updated 2 years ago, 22 views

When you put ABC in, abc acb bca bac cab cba I tried to create a code with but I couldn't get the right result. Can you tell me how the code is wrong and how to fix it?

//I'm sorry. Failed to complete....

import java.util.Arrays;

public class HW0 { public static String [] result; public static int size; public static int a=0;

private static String[] permutation(String prefix, String input) {
    size = 1;
    for(int i=0; i<input.length();i++)
    {
       size = size * (input.length()-i);
    }
    result = new String[size];

    if (input.isEmpty()) {
      result[a]=prefix;
      a++;

    }else{
        for(int i=0; i<input.length(); i++){
            permutation(prefix+input.charAt(i),
                    input.substring(0, i)+input.substring(i+1,input.length()));

            }
    }


    Arrays.sort(result);
    return result;
}


public static String[] printPermutations(String s)
{
    String[] b = permutation("",s);
    return b;

    /*
    You should return a list of strings populated by the unique permutations
    of the input, s, in alphabetical order.
    */

}

/*
Do not edit anything below this comment.
*/

public static void main(String[] args)
{
    String[] permutations = printPermutations(args[0]);
    for(String p : permutations)
    {
        System.out.println(p);
    }
}

}

java

2022-09-21 15:20

1 Answers

You have to do your homework by yourself

This is because the part that initializes the variable has been executed several times and is newly initialized every time.

    size = 1;
    for(int i=0; i<input.length();i++)
    {
       size = size * (input.length()-i);
    }
    result = new String[size];

You just need to modify it to initialize it once as shown below.

class Perm {
  public static String [] result;
  public static int size;
  public static int a=0;

  private static String[] permutation(String prefix, String input) {
    if (input.isEmpty()) {
      result[a]=prefix;
      a++;
    } } else{
      for(int i=0; i<input.length(); i++){
        permutation(prefix+input.charAt(i),
                    input.substring(0, i)+input.substring(i+1,input.length()));
      }
    }

    return result;
  }

  public static String[] printPermutations(String s) {
    size = 1;
    for (int i=0; i<s.length();i++) {
      size = size * (s.length()-i);
    }

    result = new String[size];

    String[] b = permutation("",s);
    return b;

    /*
      You should return a list of strings populated by the unique permutations
      of the input, s, in alphabetical order.
    */

  }

  /*
    Do not edit anything below this comment.
  */

  public static void main(String[] args) {
    String[] permutations = printPermutations(args[0]);
    for(String p : permutations) {
      System.out.println(p);
    }
  }

}


2022-09-21 15:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.