-
Notifications
You must be signed in to change notification settings - Fork 0
/
variations_without_repetitions.java
56 lines (48 loc) · 1.51 KB
/
variations_without_repetitions.java
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
// Variations without Repetitions
// Given a set of elements, find all variations of k elements without repetitions.
// Input Output
// A B C
// 2
// A B
// A C
// B A
// B C
// C A
// C B
// 1. Get the input elements
// 2. Get the number of elements to choose
// 3. Create an array to hold the variations
// 4. Create a list to hold the result
// 5. Create a method to permute the elements
// 6. Create a method to swap the elements
// 7. Print the result - use the same method as in permutations without repetitions
import java.util.*;
public class Main {
public static String[] elements;
public static String[] variations;
public static boolean[] used;
public static List<String> result = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
elements = scanner.nextLine().split("\\s+");
int k = Integer.parseInt(scanner.nextLine());
variations = new String[k];
used = new boolean[elements.length];
permute(0);
result.forEach(System.out::println);
}
private static void permute(int index) {
if (index >= variations.length) {
result.add(String.join(" ", variations));
} else {
for (int i = 0; i < elements.length; i++) {
if (!used[i]) {
used[i] = true;
variations[index] = elements[i];
permute(index + 1);
used[i] = false;
}
}
}
}
}