从数组中打印对的唯一排列
print unique permutations of pairs from an array
给定一个数组,打印出数组中所有不重复且不相同的对排列。数组不包含重复元素。
例如:
String[] array = {"Cheese", "Pepperoni", "Black Olives", "Chicken"}
期望的示例输出:
- 奶酪,意大利辣香肠
- 奶酪、黑橄榄
- 奶酪,鸡肉
- 黑橄榄、意大利辣香肠
...
无效:
- 奶酪,奶酪
- 奶酪,意大利辣香肠
意大利辣香肠、奶酪
只有一对输入。 [奶酪,意大利辣香肠] 或 [意大利辣香肠,奶酪]
private Map<Integer, List<String>> getPairs(String[] array) {
Map<Integer, List<String>> map = new HashMap<>();
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (i == j)
continue;
ArrayList<String> list = new ArrayList<>();
list.add(array[i]);
list.add(array[j]);
map.put(count, list);
++count;
}
}
// System.out.println(map);
return map;
}
我的代码打印出重复项。你能帮忙吗
更改您的内部 for 循环声明:
for (int j = 0; j < array.length; j++) {
到
for (int j = i + 1; j < array.length; j++) {
假设 array
的元素不包含重复项,这避免了 "cheese, cheese" 的情况(因为 j
和 i
永远不相等),以及 "Cheese, Pepperoni" 和 "Pepperoni, Cheese" 的情况,因为 j
永远不会小于 i
.
(那么if (i == j) continue;
也是多余的)
给定一个数组,打印出数组中所有不重复且不相同的对排列。数组不包含重复元素。 例如:
String[] array = {"Cheese", "Pepperoni", "Black Olives", "Chicken"}
期望的示例输出:
- 奶酪,意大利辣香肠
- 奶酪、黑橄榄
- 奶酪,鸡肉
- 黑橄榄、意大利辣香肠 ...
无效:
- 奶酪,奶酪
- 奶酪,意大利辣香肠
意大利辣香肠、奶酪
只有一对输入。 [奶酪,意大利辣香肠] 或 [意大利辣香肠,奶酪]
private Map<Integer, List<String>> getPairs(String[] array) {
Map<Integer, List<String>> map = new HashMap<>();
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (i == j)
continue;
ArrayList<String> list = new ArrayList<>();
list.add(array[i]);
list.add(array[j]);
map.put(count, list);
++count;
}
}
// System.out.println(map);
return map;
}
我的代码打印出重复项。你能帮忙吗
更改您的内部 for 循环声明:
for (int j = 0; j < array.length; j++) {
到
for (int j = i + 1; j < array.length; j++) {
假设 array
的元素不包含重复项,这避免了 "cheese, cheese" 的情况(因为 j
和 i
永远不相等),以及 "Cheese, Pepperoni" 和 "Pepperoni, Cheese" 的情况,因为 j
永远不会小于 i
.
(那么if (i == j) continue;
也是多余的)