簡體   English   中英

我如何排序排列

[英]How do I sort permutation

我已經編譯了代碼,並且可以正常工作,我目前正在嘗試添加一種排序方法,以使排列具有降序排序功能。

我已經嘗試了許多數組排序功能。 我不知道我需要更改以配置排序方法。

import java.util.*;

public class Permutation { 



public static void main(String[] args) 

{ 
    String str;

    Scanner in = new Scanner(System.in);
    System.out.println("Enter details");
    str = in.nextLine();
    System.out.println("You entered " + str);

    int n = str.length(); 
    Permutation permutation = new Permutation(); 
    permutation.permute(str, 0, n - 1); 

} 

/** 
 * permutation function 
 * @param str string to calculate permutation for 
 * @param l starting index 
 * @param r end index 
 */
private void permute(String str, int l, int r) 
{ 
    if (l == r) 
        System.out.println(str); 
    else { 
        for (int i = l; i <= r; i++) { 
            str = swap(str, l, i); 
            permute(str, l + 1, r); 
            //str = swap(str, l, i);

        }
    } 
} 

/** 
 * Swap Characters at position 
 * @param a string value 
 * @param i position 1 
 * @param j position 2 
 * @return swapped string 
 */
public String swap(String a, int i, int j) 
{ 
    char temp; 
    char charArray[] = a.toCharArray(); 
    temp = charArray[i]; 
    charArray[i] = charArray[j];
    charArray[j] = temp; 
    return String.valueOf(charArray);

}
} 

我的程序運行正常,我得到了結果。 我只需要以降序格式對結果進行排序。 我在完成此功能時遇到問題。

我認為您有兩種解決問題的方法。

  1. 無需立即打印出排列,而是在permutate()的開頭創建一個數組String[] permutatedStrings ,並在現在打印它們的位置添加排列的字符串。 在該方法的最后,您執行Arrays.sort(permutatedStrings, Comparator<String>.comparingInt((String str) -> Integer.parseInt(str) * -1);
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Permutation {

    public static void main(String[] args)

    {
    String str;

    Scanner in = new Scanner(System.in);
    System.out.println("Enter details");
    str = in.nextLine();
    in.close();
    System.out.println("You entered " + str);

    str = str.replaceAll("\\D+", "");
    // Eliminating excess character, leaving integers

    try {
        Integer.parseInt(str);
    } catch (NumberFormatException e) {
        System.out.println("No Valid Numbers");
    }
    // Error exception is thrown where there is no integer present

    int n = str.length();
    Permutation permutation = new Permutation();
    ArrayList<String> permutatedStrings = new ArrayList<>();
    ArrayList<String> resultList = permutation.permute(permutatedStrings, str, 0, n - 1);
    Object[] result = resultList.toArray();
    Arrays.sort(result, Comparator.comparingInt((Object string) -> Integer.parseInt((String) string) * -1));

    for (Object object : result) {
        System.out.println((String) object);
    }

    }

    /**
     * permutation function
     * 
     * @param str string to calculate permutation for
     * @param l   starting index
     * @param r   end index
     */
    private ArrayList<String> permute(ArrayList<String> permutatedStrings, String str, int l, int r) {
    if (l == r) {
        permutatedStrings.add(str);
    } else {
        for (int i = l; i <= r; i++) {
        str = swap(str, l, i);
        permute(permutatedStrings, str, l + 1, r);
        // str = swap(str, l, i);

        }
    }
    return permutatedStrings;
    }

    /**
     * Swap Characters at position
     * 
     * @param a string value
     * @param i position 1
     * @param j position 2
     * @return swapped string
     */
    public String swap(String a, int i, int j) {
    char temp;
    char charArray[] = a.toCharArray();
    temp = charArray[i];
    charArray[i] = charArray[j];
    charArray[j] = temp;
    return String.valueOf(charArray);

    }
}
  1. 第二種方法是按順序創建排列。 首先,您對數字進行排序。 然后根據Nayuki項目進行pe。

我為您提供可讀的解決方案。 添加了一些評論。

import java.util.*;

public class Permutation {

    public static void main(String[] args) {
         String str;

         Scanner in = new Scanner(System.in);
         System.out.println("Enter details");
         str = in.nextLine();
         System.out.println("You entered " + str);


         str = str.replaceAll("\\D+", "");
         //Eliminating excess character, leaving integers

         try {
             Integer.parseInt(str);
         } catch (NumberFormatException e) {
             System.out.println("No Valid Numbers");
         }
         // Error exception is thrown where there is no integer present

         int n = str.length();
         Permutation permutation = new Permutation();

         // permutations get accumulated in here
         Set<String> result = new TreeSet<>(new Comparator<String>() {
             @Override
             public int compare(String o1, String o2) {
                 //reversed order - o2.compareTo(o1) - results in descending order out of the box -
                 // no need to cast to integer all call implicit sort().
                 // As a bonus: you don't care about possible duplicates.
                 return o2.compareTo(o1);
             }
         });

         permutation.permute(str, 0, n - 1, result);

         // listing is here now
         result.forEach(res -> System.out.println(res));

     }

     /**
     * permutation function
      *
      * @param str string to calculate permutation for
      * @param l   starting index
      * @param r   end index
      */
     private Set<String> permute(String str, int l, int r, Set<String> result) {
         if (l == r) {
             result.add(str);
             return result;
             // too early to print!
             //System.out.println(str);
         } else {
             for (int i = l; i <= r; i++) {
                 str = swap(str, l, i);
                 // result of the call can be ignored
                 permute(str, l + 1, r, result);
                 //str = swap(str, l, i);
             }
         }
         // unreachable, it's OK
         return null;
     }

     /**
      * Swap Characters at position
      *
      * @param a string value
      * @param i position 1
      * @param j position 2
      * @return swapped string
      */
     public String swap(String a, int i, int j) {
         char temp;
         char charArray[] = a.toCharArray();
         temp = charArray[i];
         charArray[i] = charArray[j];
         charArray[j] = temp;
         return String.valueOf(charArray);

     }
 } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM