ユーザーは自分の番号の桁数を入力し、次に自分の番号を入力する必要があります。コードは、再帰なしで、可能なすべての方法でその番号を配置する必要があります。
たとえば、123 という数字は 6 つの方法で配置できます。
123 132 213 231 312 321
補足ですが、この質問の仕方に何か問題がある場合、またはさらに情報が必要な場合は、お知らせください。私の質問に対する答えがわからなくても。私は本当にこの質問に答えてもらう必要があります.私はそれについて気が狂い始めていると思います.
ユーザーは自分の番号の桁数を入力し、次に自分の番号を入力する必要があります。コードは、再帰なしで、可能なすべての方法でその番号を配置する必要があります。
たとえば、123 という数字は 6 つの方法で配置できます。
123 132 213 231 312 321
補足ですが、この質問の仕方に何か問題がある場合、またはさらに情報が必要な場合は、お知らせください。私の質問に対する答えがわからなくても。私は本当にこの質問に答えてもらう必要があります.私はそれについて気が狂い始めていると思います.
少しグーグルで調べると、いくつかのアルゴリズムが見つかります。たとえば、5 行で記述できるJohnson-Trotter Algorithmです。
最初の順列を <1 <2 ... <n で初期化します モバイル整数が存在する間 最大のモバイル整数 k を見つける スワップ k と、それが見ている隣接する整数 k より大きいすべての整数の方向を逆にする
これは、すべての順列を生成することと同じです。
For generating the next permutation after the current one(the first one is 123):
1. Find from right to left the first position pos where current[pos] < current[pos + 1]
2. Increment current[pos] to the next possible number(some numbers are maybe already used)
3. At the remaining positions(> pos) put the smallest possible numbers not used.
4. Go to 1.
すべての順列を出力する作業コードは次のとおりです。
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
final int n = 3;
int[] current = new int[n];
for (int i = 1; i <= n; i++) {
current[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(current[i] + " ");
}
System.out.println();
used[current[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[current[i]] = false;
if (current[i] < current[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = current[pos] + 1; i <= n; i++) {
if (!used[i]) {
current[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
current[++pos] = i;
}
}
}
System.out.println(total);
}
}
PS私はたった数分でコードを書きました。コードがクリーンであるとか、変数の名前が適切であるとは主張しません。