-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
66 lines (52 loc) · 1.92 KB
/
NextPermutation.java
File metadata and controls
66 lines (52 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//2008 - 4
//Input must be exact.
import java.util.*;
public class NextPermutation {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
int times = input.nextInt();
for(int i = 0; i < times; i++){
int numElements = input.nextInt();
String rawElements = inputString.nextLine();
String[] stringElements = rawElements.split(" ");
int[] elements = new int[stringElements.length];
ArrayList<Integer> processed = new ArrayList<Integer>();
for(int x = 0; x < stringElements.length; x++){
elements[x] = Integer.parseInt(stringElements[x]);
}
for(int x = numElements - 1; x > 0; x--){
if(elements[x] > elements[x - 1]){
//We got the index
//Switch [x-1] with whatever the next largest value in processed is
int newValue = numElements;
processed.add(elements[x]);
for(int j = 0; j < processed.size(); j++){
if(processed.get(j) > elements[x - 1] && processed.get(j) < newValue){
newValue = processed.get(j);
processed.set(j, elements[x - 1]);
}
}
//We have the right arraylist now, so output
Collections.sort(processed);//Is this right?
for(int j = 0; j < elements.length; j++){
System.out.print(elements[j] + " ");
}
System.out.println();
for(int j = 0; j < x - 1; j++){
System.out.print(elements[j] + " ");
}
System.out.print(newValue + " ");
for(int j = 0; j < processed.size(); j++){
System.out.print(processed.get(j) + " ");
}
System.out.println();
System.out.println();
break;
} else {
processed.add(elements[x]);
}
}
}
}
}