Skip to content

Commit 54c6764

Browse files
committed
refactor: use CollectionUtil.permutations to calculate possible antennas permutations
1 parent 00df560 commit 54c6764

File tree

1 file changed

+11
-18
lines changed

1 file changed

+11
-18
lines changed

src/main/java/com/adventofcode/flashk/day08/ResonantCollinearity.java

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.adventofcode.flashk.day08;
22

33
import com.adventofcode.flashk.common.Vector2;
4+
import org.apache.commons.collections4.CollectionUtils;
45

56
import java.util.ArrayList;
67
import java.util.HashMap;
@@ -16,6 +17,7 @@ public class ResonantCollinearity {
1617
private final int rows;
1718
private final int cols;
1819
private final Map<Character, List<Vector2>> antennasPerFrequency = new HashMap<>();
20+
private Set<Vector2> antinodes;
1921

2022
public ResonantCollinearity(char[][] input) {
2123

@@ -38,32 +40,23 @@ public ResonantCollinearity(char[][] input) {
3840
}
3941

4042
public int solve(boolean countHarmonics) {
41-
Set<Vector2> antinodeLocations = new HashSet<>();
4243

43-
for(Map.Entry<Character,List<Vector2>> frequency : antennasPerFrequency.entrySet()) {
44-
45-
List<Vector2> antennas = frequency.getValue();
46-
47-
for (int i = 0; i < antennas.size(); i++) {
48-
for (int j = 1; j < antennas.size(); j++) {
49-
Vector2 antenna1 = antennas.get(i);
50-
Vector2 antenna2 = antennas.get(j);
51-
52-
if (antenna1.equals(antenna2)) {
53-
continue;
54-
}
44+
antinodes = new HashSet<>();
5545

56-
findAntinodes(countHarmonics, antenna1, antenna2, antinodeLocations);
57-
findAntinodes(countHarmonics, antenna2, antenna1, antinodeLocations);
46+
for(Map.Entry<Character,List<Vector2>> frequency : antennasPerFrequency.entrySet()) {
5847

59-
}
48+
List<Vector2> antennas = frequency.getValue();
49+
for(List<Vector2> pair : CollectionUtils.permutations(antennas)) {
50+
findAntinodes(countHarmonics, pair.get(0), pair.get(1));
51+
findAntinodes(countHarmonics, pair.get(1), pair.get(0));
6052
}
53+
6154
}
6255

63-
return antinodeLocations.size();
56+
return antinodes.size();
6457
}
6558

66-
private void findAntinodes(boolean countHarmonics, Vector2 antennaA, Vector2 antennaB, Set<Vector2> antinodes) {
59+
private void findAntinodes(boolean countHarmonics, Vector2 antennaA, Vector2 antennaB) {
6760
Vector2 direction = Vector2.direction(antennaA, antennaB);
6861
Vector2 antinode = new Vector2(antennaA);
6962
do {

0 commit comments

Comments
 (0)