[英]Avoid to print duplicates
我希望產生的結果顯示不同的獨特數字組合。
例如:如果數字是4位數字,即:4789,則輸出將為478,789,489,479(僅以遞增順序)。我的代碼是:
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幫助,在此先感謝您。
您可以使用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
,其中包含用於元素的array
,然后您可以執行所需的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.