1
+ package ru .mirea .practice .s0000001 .task1 ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ public class JohnsonTrotter {
6
+ private int [] permutation ; // Текущая перестановка
7
+ private int [] directions ; // Направления элементов
8
+ private int n ; // Количество элементов
9
+
10
+ public JohnsonTrotter (int n ) {
11
+ this .n = n ;
12
+ this .permutation = new int [n ];
13
+ this .directions = new int [n ];
14
+ for (int i = 0 ; i < n ; i ++) {
15
+ permutation [i ] = i + 1 ; // Заполнение перестановки числами от 1 до n
16
+ directions [i ] = -1 ; // Изначально все элементы направлены влево
17
+ }
18
+ }
19
+
20
+ public void generatePermutations () {
21
+ boolean morePermutations = true ;
22
+
23
+ while (morePermutations ) {
24
+ // Печать текущей перестановки
25
+ System .out .println (Arrays .toString (permutation ));
26
+
27
+ // Найти наибольший элемент, который может двигаться
28
+ int largestMobileIndex = -1 ;
29
+ int largestMobileValue = -1 ;
30
+
31
+ for (int i = 0 ; i < n ; i ++) {
32
+ if (isMobile (i )) {
33
+ if (permutation [i ] > largestMobileValue ) {
34
+ largestMobileValue = permutation [i ];
35
+ largestMobileIndex = i ;
36
+ }
37
+ }
38
+ }
39
+
40
+ // Если не осталось мобильных элементов, завершить
41
+ if (largestMobileIndex == -1 ) {
42
+ morePermutations = false ;
43
+ } else {
44
+ // Перемещение наибольшего мобильного элемента
45
+ move (largestMobileIndex );
46
+
47
+ // Изменение направления перемещенного элемента
48
+ int movedValue = permutation [largestMobileIndex ];
49
+ for (int i = 0 ; i < n ; i ++) {
50
+ if (permutation [i ] > movedValue ) {
51
+ directions [i ] = -directions [i ]; // Изменяем направление
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ private boolean isMobile (int index ) {
59
+ int direction = directions [index ];
60
+ int newIndex = index + direction ;
61
+
62
+ // Проверка, находится ли новый индекс в пределах массива
63
+ return newIndex >= 0 && newIndex < n && permutation [newIndex ] < permutation [index ];
64
+ }
65
+
66
+ private void move (int index ) {
67
+ int direction = directions [index ];
68
+ int newIndex = index + direction ;
69
+
70
+ // Меняем местами элементы
71
+ int temp = permutation [index ];
72
+ permutation [index ] = permutation [newIndex ];
73
+ permutation [newIndex ] = temp ;
74
+ }
75
+
76
+ public static void main (String [] args ) {
77
+ int n = 3 ; // Задайте количество элементов
78
+ JohnsonTrotter jt = new JohnsonTrotter (n );
79
+ jt .generatePermutations ();
80
+ }
81
+ }
0 commit comments