2015-12-29 106 views
0

我希望生成顯示不同的/獨特的數字組合的結果。避免重複打印

對於例如:如果數量是4位,即:4789然後輸出將在478789489479格式(在只有遞增的順序。) 我的代碼是:上述程序的

import java.util.Arrays; 
import java.util.HashSet; 
import java.util.Random; 
import java.util.Scanner; 

public class Permutation{ 
    static void permute(int[] a, int k) { 
     int temp; 
     if (k == a.length) { 
      for (int i = 0; i < a.length - 1; i++) { 
       for (int j = i + 1; j < a.length - 1; j++) { 
        if (a[i] > a[j]) { 
         temp = a[i]; 
         a[i] = a[j]; 
         a[j] = temp; 
        } 
        } 
      System.out.print(a[i]); 
      } 
     System.out.println(); 
     } else { 
      int tempLength = (a.length); 
      for (int i = k; i < tempLength; i++) { 
       temp = a[k]; 
       a[k] = a[i]; 
       a[i] = temp; 
       permute(a, k + 1); 
      } 
     } 
    } 

    public static void main(String args[]) { 

     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the length of list: "); 
     int N = sc.nextInt(); 
     int[] sequence = new int[N]; 
     System.out.println("---------"); 
     for (int i = 0; i < N; i++) 
      { 
     sequence[i] = sc.nextInt(); 
      } 
     System.out.println("The original sequence is: "); 
     for (int i = 0; i < N; i++){ 
     System.out.print(sequence[i] + " "); 
     System.out.println("\nThe permuted sequences are: "); 
     permute(sequence, 0); 
     sc.close(); 
    }} 

輸出是:

Enter the length of list: 4 
--------- 
1 
2 
7 
8 
The original sequence is: 
1 2 7 8 

The permuted sequences are: 

127,128,128,127,178,127,127,128,128,127,178,127, 
127,128,128,127,178,127,278,127,127,128,178,127 

所以這個結果顯示了一些重複的元素。 我想避免在數組中顯示這樣的重複元素。 在上面的代碼,我期待作爲輸出:127,128,178,278 幫助,提前謝謝。

+0

通過線調試它線,你會發現問題出在哪裏 –

+0

實際上,的System.out.println(),它通過for循環顯示元件,第一環路會顯示圖1,用於第二它顯示2和用於第三顯示器7 ,所以有點困惑如何把這個數字作爲整體,我的意思是127作爲一個數字。 – Duke

回答

0

您可以使用StringBuilder

private static String[] getDigitsArray(String str) { 
    StringBuilder sb = new StringBuilder(str); 
    sb.deleteCharAt(3).append(",") 
      .append(new StringBuilder(str).deleteCharAt(0)).append(",") 
      .append(new StringBuilder(str).deleteCharAt(1)).append(",") 
      .append(new StringBuilder(str).deleteCharAt(2)); 
    return sb.toString().split(","); 
} 

簡單的使用:

String[] array = getDigitsArray("4789"); 
System.out.println("Result: "+Arrays.toString(array)); 

而且它的結果:

Result: [478, 789, 489, 479] 

,每4位string你可以使用上面的代碼,它會返回一個array,裏面有元素,然後你可以做你想做的事情。