我希望生成显示不同的不同/唯一数字组合的结果。
例如:如果数字是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 帮助,提前谢谢。
答案 0 :(得分: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
,里面有元素,然后你可以做你想要的。