1
+ package ru .mirea .practice .s0000001 .task1 ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .List ;
5
+
6
+ public final class PermutationGenerator {
7
+
8
+ private PermutationGenerator () {
9
+ // Prevent instantiation
10
+ }
11
+
12
+ static class Item {
13
+ int number ;
14
+ boolean isMovingRight ;
15
+
16
+ Item (int number ) {
17
+ this .number = number ;
18
+ this .isMovingRight = false ; // Initially set to move left
19
+ }
20
+ }
21
+
22
+ public static void main (String [] args ) {
23
+ int count = 10 ; // Changed from 4 to 10
24
+ createPermutations (count );
25
+ }
26
+
27
+ public static void createPermutations (int count ) {
28
+ List <Item > items = new ArrayList <>();
29
+ for (int i = 1 ; i <= count ; i ++) {
30
+ items .add (new Item (i ));
31
+ }
32
+
33
+ displayPermutation (items );
34
+
35
+ while (true ) {
36
+ int indexOfLargestMovable = findLargestMovable (items );
37
+ if (indexOfLargestMovable == -1 ) {
38
+ break ;
39
+ }
40
+
41
+ Item largestItem = items .get (indexOfLargestMovable );
42
+ int targetIndex = largestItem .isMovingRight ? indexOfLargestMovable + 1 : indexOfLargestMovable - 1 ;
43
+ swapItems (items , indexOfLargestMovable , targetIndex );
44
+
45
+ for (Item item : items ) {
46
+ if (item .number > largestItem .number ) {
47
+ item .isMovingRight = !item .isMovingRight ; // Change direction
48
+ }
49
+ }
50
+
51
+ displayPermutation (items );
52
+ }
53
+ }
54
+
55
+ private static int findLargestMovable (List <Item > items ) {
56
+ int movableIndex = -1 ;
57
+ for (int i = 0 ; i < items .size (); i ++) {
58
+ Item currentItem = items .get (i );
59
+ int neighborIndex = currentItem .isMovingRight ? i + 1 : i - 1 ;
60
+
61
+ if (neighborIndex >= 0 && neighborIndex < items .size () && currentItem .number > items .get (neighborIndex ).number ) {
62
+ if (movableIndex == -1 || currentItem .number > items .get (movableIndex ).number ) {
63
+ movableIndex = i ;
64
+ }
65
+ }
66
+ }
67
+ return movableIndex ;
68
+ }
69
+
70
+ private static void swapItems (List <Item > items , int firstIndex , int secondIndex ) {
71
+ Item temp = items .get (firstIndex );
72
+ items .set (firstIndex , items .get (secondIndex ));
73
+ items .set (secondIndex , temp );
74
+ }
75
+
76
+ private static void displayPermutation (List <Item > items ) {
77
+ for (Item item : items ) {
78
+ System .out .print (item .number + " " );
79
+ }
80
+ System .out .println ();
81
+ }
82
+ }
0 commit comments