|
| 1 | +package Day03; |
| 2 | + |
| 3 | +import advent.utils.AdventMathUtils; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +public class BinaryPowerConsumptionDiagnoser { |
| 9 | + |
| 10 | + public long diagnoseBinaryPowerConsumption(List<String> binaryReportEntries) { |
| 11 | + int reportSize = binaryReportEntries.get(0).length(); |
| 12 | + StringBuilder gamma = new StringBuilder(); |
| 13 | + StringBuilder epsilon = new StringBuilder(); |
| 14 | + for (int bitPosition = 0; bitPosition < reportSize; bitPosition++) { |
| 15 | + char mostFrequentAtPos = getMostFrequentElementAtPosition(binaryReportEntries, bitPosition); |
| 16 | + gamma.append(mostFrequentAtPos); |
| 17 | + epsilon.append(mostFrequentAtPos == '1' ? '0' : '1'); |
| 18 | + } |
| 19 | + return multiplyRates(gamma.toString(), epsilon.toString()); |
| 20 | + } |
| 21 | + |
| 22 | + public long diagnoseLifeSupportRating(List<String> reportEntries) { |
| 23 | + List<String> oxygenRate = new ArrayList<>(List.copyOf(reportEntries)); |
| 24 | + List<String> cO2Rate = new ArrayList<>(List.copyOf(reportEntries)); |
| 25 | + int reportSize = reportEntries.get(0).length(); |
| 26 | + |
| 27 | + for (int bitPosition = 0; bitPosition < reportSize; bitPosition++) { |
| 28 | + char mostFrequentOxygenElement = getMostFrequentElementAtPosition(oxygenRate, bitPosition); |
| 29 | + char leastFrequentCo2Element = getMostFrequentElementAtPosition(cO2Rate, bitPosition) == '1' ? '0' : '1'; |
| 30 | + |
| 31 | + int finalBitPosition = bitPosition; |
| 32 | + if (oxygenRate.size() > 1) { |
| 33 | + oxygenRate.removeIf(p -> p.charAt(finalBitPosition) != mostFrequentOxygenElement); |
| 34 | + } |
| 35 | + if (cO2Rate.size() > 1) { |
| 36 | + cO2Rate.removeIf(p -> p.charAt(finalBitPosition) != leastFrequentCo2Element); |
| 37 | + } |
| 38 | + if (cO2Rate.size() == 1 && oxygenRate.size() == 1) { |
| 39 | + break; |
| 40 | + } |
| 41 | + } |
| 42 | + return multiplyRates(oxygenRate.get(0), cO2Rate.get(0)); |
| 43 | + } |
| 44 | + |
| 45 | + private long multiplyRates(String s, String s2) { |
| 46 | + return Integer.parseInt(s, 2) * Integer.parseInt(s2, 2); |
| 47 | + } |
| 48 | + |
| 49 | + private char getMostFrequentElementAtPosition(List<String> reportEntries, int bitPosition) { |
| 50 | + List<Character> currentPositionList = new ArrayList<>(); |
| 51 | + for (String currentReport : reportEntries) { |
| 52 | + currentPositionList.add(currentReport.charAt(bitPosition)); |
| 53 | + } |
| 54 | + List<Character> mostFrequentElementsInList = AdventMathUtils.findMostFrequentElementsInList(currentPositionList); |
| 55 | + if (mostFrequentElementsInList.size() == 1) { |
| 56 | + return mostFrequentElementsInList.get(0); |
| 57 | + } else { |
| 58 | + return '1'; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments