In just a few hours the 2021 version of Advent of Code begins. I will be attempting it again this year, and posting about it, much as I did last year.
Thanks for the reminder. I may try it and see how far I go before I give up.In just a few hours the 2021 version of Advent of Code begins. I will be attempting it again this year, and posting about it, much as I did last year.
final int increaseCount = Day01.countIncreases(theDepthIntegers);
System.out.println("Part 1: " + increaseCount);
final int slidingWindowIncreaseCount = Day01.countSlidingWindowIncreases(theDepthIntegers);
System.out.println("Part 2: " + slidingWindowIncreaseCount);
public static int countIncreases(final int[] theDepthIntegers)
{
int result = 0;
for (int i=1; i<theDepthIntegers.length; i++)
{
if (theDepthIntegers[i-1] < theDepthIntegers[i]) result++;
}
return result;
}
public static int countSlidingWindowIncreases(final int[] theDepthIntegers)
{
int result = 0;
for (int i=3; i<theDepthIntegers.length; i++)
{
final int sum1 = theDepthIntegers[i-1] + theDepthIntegers[i-2] + theDepthIntegers[i-3];
final int sum2 = theDepthIntegers[i] + theDepthIntegers[i-1] + theDepthIntegers[i-2];
if (sum1 < sum2) result++;
}
return result;
}
Yeah, I considered that after I had already taken the boring predictable route just trying to get a solution submitted in quick time.you don't need to do the sums.
final long part1Result = Day02.followSubmarineInstructions(0, 0, 0, day02InputLines, false);
final long part2Result = Day02.followSubmarineInstructions(0, 0, 0, day02InputLines, true);
final Pattern p = Pattern.compile("(\\w+) +(\\d+)");
for (final String submarineInstruction : inputSubmarineInstructions)
{
final Matcher m = p.matcher(submarineInstruction);
if (m.matches())
{
final String instruction = m.group(1);
final int distance = Integer.parseInt(m.group(2));
switch (instruction)
{
case "up":
{
if (shouldUseAim)
aim -= distance;
else
depth -= distance;
}
break;
case "down":
{
if (shouldUseAim)
aim += distance;
else
depth += distance;
}
break;
case "forward":
{
if (shouldUseAim)
{
depth += distance * aim;
}
horizontalPosition += distance;
}
break;
default:
throw new IllegalStateException("Don't know how to execute submarine instruction: " + submarineInstruction);
}
}
else
{
throw new IllegalStateException("Invalid submarine instruction: " + submarineInstruction);
}
}
return depth * horizontalPosition;
public static long getPart1Answer(final String day03Input, final String[] day03InputLines, final int bitWidth)
{
int gamma = 0;
int epsilon = 0;
for(int i=bitWidth; i>0; i--)
{
final int bit = getBit(i, day03InputLines, bitWidth);
gamma = (gamma << 1) | bit;
epsilon = (epsilon << 1) | (bit==0?1:0);
}
return gamma*epsilon;
}
private static int getBit(final int bitNum, final String[] day03InputLines, final int bitWidth)
{
int oneBitCount = 0;
int zeroBitCount = 0;
final int bitCharPos = bitWidth - bitNum;
for (final String bitLine: day03InputLines)
{
final char bitChar = bitLine.charAt(bitCharPos);
if (bitChar == '0') zeroBitCount++;
else if (bitChar == '1') oneBitCount++;
else throw new IllegalStateException("Invalid bit char: " + bitChar);
}
if (oneBitCount > zeroBitCount) return 1;
return 0;
}
public static long getPart2Answer(final String day03Input, final String[] day03InputLines, final int bitWidth)
{
final Set<String> oxygenBits = new HashSet<>();
final Set<String> co2Bits = new HashSet<>();
for (final String s: day03InputLines)
{
oxygenBits.add(s);
co2Bits.add(s);
}
final int oxygenVal = workDownToOneVal(oxygenBits, 1, bitWidth);
final int co2Val = workDownToOneVal(co2Bits, 0, bitWidth);
return oxygenVal * co2Val;
}
private static int workDownToOneVal(final Set<String> bitStrings, final int bitVal, final int bitWidth)
{
final Set<String> bitStringsToProcess = new HashSet<>();
final Set<String> remainingStringsToProcess = new HashSet<>();
bitStringsToProcess.addAll(bitStrings);
for(int i=bitWidth; i>0; i--)
{
remainingStringsToProcess.clear();
final int bit = getBit(i, bitStringsToProcess, bitWidth, bitVal);
final int bitCharPos = bitWidth - i;
for (final String s: bitStringsToProcess)
{
final char bitChar = s.charAt(bitCharPos);
if ((bitChar == '1') && (bit == 1)) remainingStringsToProcess.add(s);
if ((bitChar == '0') && (bit == 0)) remainingStringsToProcess.add(s);
}
bitStringsToProcess.clear();
bitStringsToProcess.addAll(remainingStringsToProcess);
// remainingStringsToProcess.clear(); Done at top of loop
if (bitStringsToProcess.size() == 1) break;
}
if (bitStringsToProcess.size() != 1) throw new IllegalStateException("Processing didn't result in a single value");
// A bit of a hack to extract the single value from the Set<>
final List<String> entries = new ArrayList<>();
entries.addAll(bitStringsToProcess);
final String entry = entries.get(0);
// Realized too late that this loop could be replaced by
// final int result = Integer.parseInt(entry, 2);
int result = 0;
for(int i=bitWidth; i>0; i--)
{
final char bitChar = entry.charAt(bitWidth-i);
result = (result << 1) | (bitChar=='1'?1:0);
}
return result;
}
private static int getBit(final int bitNum, final Set<String> bitStringsToProcess, final int bitWidth, final int bitVal)
{
int oneBitCount = 0;
int zeroBitCount = 0;
final int bitCharPos = bitWidth - bitNum;
for (final String bitLine: bitStringsToProcess)
{
final char bitChar = bitLine.charAt(bitCharPos);
if (bitChar == '0') zeroBitCount++;
else if (bitChar == '1') oneBitCount++;
else throw new IllegalStateException("Invalid bit char: " + bitChar);
}
if (bitVal == 1)
{
if (oneBitCount == zeroBitCount) return 1;
if (oneBitCount > zeroBitCount) return 1;
return 0;
}
if (oneBitCount == zeroBitCount) return 0;
if (oneBitCount > zeroBitCount) return 0;
return 1;
}
final class BingoCard
{
private final int[][] bingoCardNumbers = new int[5][5];
private final boolean[][] wasNumberPlayed = new boolean[5][5];
private final int bingoCardNumber;
private int winningRow = -1;
private int winningCol = -1;
public BingoCard(final int bingoCardNumber,
final String line1,
final String line2,
final String line3,
final String line4,
final String line5)
{
this.bingoCardNumber = bingoCardNumber;
int[] lineVals = getLineVals(line1);
putIntLineVals(1, lineVals);
lineVals = getLineVals(line2);
putIntLineVals(2, lineVals);
lineVals = getLineVals(line3);
putIntLineVals(3, lineVals);
lineVals = getLineVals(line4);
putIntLineVals(4, lineVals);
lineVals = getLineVals(line5);
putIntLineVals(5, lineVals);
}
private int[] getLineVals(final String lineOfNumbers)
{
final Pattern p = Pattern.compile(" *(\\d+) +(\\d+) +(\\d+) +(\\d+) +(\\d+)");
final Matcher m = p.matcher(lineOfNumbers);
final int[] result = new int[5];
if (!m.matches()) throw new IllegalStateException("Couldn't parse bingo card line: " + lineOfNumbers);
result[0] = Integer.parseInt(m.group(1));
result[1] = Integer.parseInt(m.group(2));
result[2] = Integer.parseInt(m.group(3));
result[3] = Integer.parseInt(m.group(4));
result[4] = Integer.parseInt(m.group(5));
return result;
}
private void putIntLineVals(final int lineNumber, int[] lineVals)
{
bingoCardNumbers[lineNumber-1][0] = lineVals[0];
bingoCardNumbers[lineNumber-1][1] = lineVals[1];
bingoCardNumbers[lineNumber-1][2] = lineVals[2];
bingoCardNumbers[lineNumber-1][3] = lineVals[3];
bingoCardNumbers[lineNumber-1][4] = lineVals[4];
}
public int getValAtPos(final int row, final int col)
{
return bingoCardNumbers[row-1][col-1];
}
public boolean playNumber(final int numberToPlay)
{
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if (bingoCardNumbers[i][j] == numberToPlay)
{
wasNumberPlayed[i][j] = true;
}
}
}
return isABingo();
}
private boolean isABingo()
{
for(int i=0; i<5; i++)
{
boolean fullLine = true;
for(int j=0; j<5; j++)
{
if (!wasNumberPlayed[i][j])
{
fullLine = false;
break;
}
}
if (fullLine)
{
winningRow = i;
return true;
}
}
for(int j=0; j<5; j++)
{
boolean fullLine = true;
for(int i=0; i<5; i++)
{
if (!wasNumberPlayed[i][j])
{
fullLine = false;
break;
}
}
if (fullLine)
{
winningCol = j;
return true;
}
}
return false;
}
public int getCardNumber()
{
return bingoCardNumber;
}
public int getWinningRow()
{
return winningRow;
}
public int getWinningCol()
{
return winningCol;
}
public int getSumOfNonPlayedNumbers()
{
int result = 0;
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if (!wasNumberPlayed[i][j]) result += bingoCardNumbers[i][j];
}
}
return result;
}
public boolean alreadyWon()
{
return winningRow>=0 || winningCol>=0;
}
@Override
public final String toString()
{
final StringBuilder sb = new StringBuilder();
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if (wasNumberPlayed[i][j])
sb.append(String.format(" [%2d]", bingoCardNumbers[i][j]));
else
sb.append(String.format(" %2d ", bingoCardNumbers[i][j]));
}
sb.append('\n');
}
return sb.toString();
}
}
[14] [21] [17] [24] [ 4]
10 16 15 [ 9] 19
18 8 [23] 26 20
22 [11] 13 6 [ 5]
[ 2] [ 0] 12 3 [ 7]
public static long getPart2Answer(final String day04Input1, final String[] day04InputLines2)
{
final Map<Integer, BingoCard> bingoCards = new HashMap<>();
int bingoCardNumber = 0;
int bingoCardStartLine = 0;
while (bingoCardStartLine+4 < day04InputLines2.length)
{
bingoCardNumber++;
final BingoCard newBingoCard = new BingoCard(bingoCardNumber,
day04InputLines2[bingoCardStartLine],
day04InputLines2[bingoCardStartLine+1],
day04InputLines2[bingoCardStartLine+2],
day04InputLines2[bingoCardStartLine+3],
day04InputLines2[bingoCardStartLine+4]);
bingoCards.put(bingoCardNumber, newBingoCard);
bingoCardStartLine = bingoCardNumber*6; // 5 lines and a blank line
}
final int numberOfBingoCards = bingoCards.size();
System.out.println("Number of bingo cards = " + numberOfBingoCards);
int numberOfWinningCards = 0;
final int[] numbersToPlay = parseNumbersToPlay(day04Input1);
int numberPlayedThatResultedInWin = 0;
int sumOfNonPlayedNumbersOnCard = 0;
boolean haveWinner = false;
for (final int numberToPlay: numbersToPlay)
{
for (final BingoCard bingoCard: bingoCards.values())
{
if (!bingoCard.alreadyWon())
{
if (bingoCard.playNumber(numberToPlay))
{
numberOfWinningCards++;
if (numberOfWinningCards == numberOfBingoCards) // HINT: change this line to do part one
{
System.out.println(bingoCard);
System.out.format("Found final winner playing %d on card %d winningRow=%d winningCol=%d%n", numberToPlay, bingoCard.getCardNumber(), bingoCard.getWinningRow(), bingoCard.getWinningCol());
haveWinner = true;
numberPlayedThatResultedInWin = numberToPlay;
sumOfNonPlayedNumbersOnCard = bingoCard.getSumOfNonPlayedNumbers();
System.out.format("numberPlayedThatResultedInWin=%d sumOfNonPlayedNumbersOnCard=%d%n", numberPlayedThatResultedInWin, sumOfNonPlayedNumbersOnCard);
}
}
}
if (haveWinner) break;
}
if (haveWinner) break;
}
return (long)numberPlayedThatResultedInWin * (long)sumOfNonPlayedNumbersOnCard;
}
final class Point
{
final int x;
final int y;
Point(final int x, final int y)
{
this.x = x;
this.y = y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
}
final class Line
{
final int x1;
final int y1;
final int x2;
final int y2;
// For part 1 we need to filter on only horizontal or vertical lines
final boolean isHorizontal;
final boolean isVertical;
Line(final int x1, final int y1, final int x2, final int y2)
{
this.x1=x1;
this.y1=y1;
this.x2=x2;
this.y2=y2;
if (x1==x2) isVertical = true; else isVertical = false;
if (y1==y2) isHorizontal = true; else isHorizontal = false;
}
Point[] getPointsOnLine()
{
// For 45 degree lines both values will be identical, otherwise one will be 1
final int lineLen = Math.max(getSize(x1,x2), getSize(y1,y2));
final Point[] result = new Point[lineLen];
int x=x1;
int y=y1;
int xdir=0;
if (x1<x2) xdir=1;
if (x2<x1) xdir=-1;
int ydir=0;
if (y1<y2) ydir=1;
if (y2<y1) ydir=-1;
for (int i=0; i<lineLen; i++)
{
final Point p = new Point(x, y);
x+=xdir;
y+=ydir;
result[i] = p;
}
return result;
}
private static int getSize(final int val1, final int val2)
{
final int result;
if (val1<=val2)
result = val2-val1+1;
else
result = val1-val2+1;
return result;
}
@Override
public String toString()
{
return String.format("Line[%d,%d -> %d,%d]", x1,y1, x2,y2);
}
}
final class GridForLines
{
final int[][] grid;
final int width;
final int height;
GridForLines(final int width, final int height)
{
this.width = width;
this.height = height;
grid = new int[width][height];
}
void mapALineIntoGrid(final Line lineToMap)
{
final Point[] points = lineToMap.getPointsOnLine();
for (final Point p : points)
{
grid[p.getX()][p.getY()]++;
}
}
int getNumberOfPointsWithSpecifiedNumberOfLinesOrMore(final int numberOfLines)
{
int result = 0;
for (final int[] row: grid)
{
for (final int i: row)
{
if (i>=numberOfLines) result++;
}
}
return result;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (int x=0; x<width; x++)
{
for (int y=0; y<height; y++)
{
sb.append(String.format("[%2d] ", grid[x][y]));
}
sb.append("\n");
}
return sb.toString();
}
}
public static long getPart1Answer(final String day05Input, final String[] day05InputLines, final int gridSize)
{
final Pattern p = Pattern.compile(" *(\\d+),(\\d+) *-> *(\\d+),(\\d+)");
final GridForLines grid = new GridForLines(gridSize, gridSize);
for (final String lineDescription : day05InputLines)
{
final Matcher m = p.matcher(lineDescription);
if (!m.matches()) throw new IllegalStateException("Couldn't parse line description: " + lineDescription);
final Line line = new Line(
Integer.parseInt(m.group(1)),
Integer.parseInt(m.group(2)),
Integer.parseInt(m.group(3)),
Integer.parseInt(m.group(4)));
if (line.isHorizontal || line.isVertical) // Just comment out this line for part two
{
grid.mapALineIntoGrid(line);
}
}
return grid.getNumberOfPointsWithSpecifiedNumberOfLinesOrMore(2);
}
final class SchoolOfLaternFish
{
private final long[] numberOfFishAtEachLevel = new long[9];
private long totalNumberOfFish = 0;
void putAFishIn(final int fishNumber)
{
numberOfFishAtEachLevel[fishNumber]++;
totalNumberOfFish++;
}
void evolveOneDay()
{
final long numberToAddToDay6 = numberOfFishAtEachLevel[0];
final long numberToPutAtDay8 = numberOfFishAtEachLevel[0];
totalNumberOfFish += numberOfFishAtEachLevel[0];
for (int i=0; i<8; i++)
{
numberOfFishAtEachLevel[i]=numberOfFishAtEachLevel[i+1];
}
numberOfFishAtEachLevel[6] += numberToAddToDay6;
numberOfFishAtEachLevel[8] = numberToPutAtDay8;
}
long getNumberOfFishInSchool()
{
return totalNumberOfFish;
}
}
function rotate_array(arr) {
const first = arr.shift();
arr.push(first);
}
No, but you could use an array backed list I guess. I suspect that Javascript is much like Lua and treats any array as a [hash]map or something because treating an array like a stack seems odd to me. In Lua you can have array["foo"] as legitimately as array[n].Does Java have a shift and pop functions for arrays?
public static long getPart2Answer(final String day07Input, final String[] day07InputLines)
{
final int[] crabHVals = new int[day07InputLines.length];
int min = 100_000_000;
int max = -1;
for(int i=0; i<day07InputLines.length; i++)
{
final int crabHVal = Integer.parseInt(day07InputLines[i]);
crabHVals[i] = crabHVal;
if (crabHVal < min) min = crabHVal;
if (crabHVal > max) max = crabHVal;
}
// System.out.format("Num crabs=%d, minHPos=%d, maxHPos=%d%n", day07InputLines.length, min, max);
long bestMin = 100_000_000_000_000_000L;
int bestPos = -1;
// Brute force all values in range to find smallest fuel usage
for (int i=min; i<=max; i++)
{
final long minGuess = calculateFuelUse2(crabHVals, i);
if (minGuess < bestMin)
{
bestMin = minGuess;
bestPos = i;
}
}
// System.out.format("Best position=%d with fuel=%d%n", bestPos, bestMin);
return bestMin;
}
private static long calculateFuelUse2(final int[] crabHVals, final int hPosition)
{
long fuelUsed = 0;
for (final int crabHVal : crabHVals)
{
final int n = Math.abs(hPosition - crabHVal);
fuelUsed += n*(n+1)/2; // the sum of numbers from 1 to n is N(N+1)/2
}
return fuelUsed;
}
I originally solved this using basically the same algorithms you did. Then I thought about Part 1 a bit more and have a few observations.Day 7 had me thinking there must be a simpler way to solve it than I came up with, but I brute forced it anyway as it was running through my 1000 inputs in less than a second.
final class SevenSegmentLED
{
final char[] signalWireLetters;
SevenSegmentLED(final String[] signalsToDecode)
{
signalWireLetters = bruteForceDecodeSignalLetters(signalsToDecode);
}
int getDigitFromSignals(final String signal)
{
final boolean[] litSegments = decodeSignalToLitSegments(signalWireLetters, signal);
if (isZeroDigit(litSegments)) return 0;
if (isOneDigit(litSegments)) return 1;
if (isTwoDigit(litSegments)) return 2;
if (isThreeDigit(litSegments)) return 3;
if (isFourDigit(litSegments)) return 4;
if (isFiveDigit(litSegments)) return 5;
if (isSixDigit(litSegments)) return 6;
if (isSevenDigit(litSegments)) return 7;
if (isEightDigit(litSegments)) return 8;
if (isNineDigit(litSegments)) return 9;
throw new IllegalStateException("Couldn't get digit from signal");
}
private char[] bruteForceDecodeSignalLetters(final String[] signalsToDecode)
{
final char[] signalWireLetters = new char[7];
for(int a=0; a<7; a++)
{
for(int b=0; b<7; b++)
{
if (b==a) continue;
for(int c=0; c<7; c++)
{
if ((c==a) || (c==b)) continue;
for(int d=0; d<7; d++)
{
if ((d==a) || (d==b) || (d==c)) continue;
for(int e=0; e<7; e++)
{
if ((e==a) || (e==b) || (e==c) || (e==d)) continue;
for(int f=0; f<7; f++)
{
if ((f==a) || (f==b) || (f==c) || (f==d) || (f==e)) continue;
for(int g=0; g<7; g++)
{
if ((g==a) || (g==b) || (g==c) || (g==d) || (g==e) || (g==f)) continue;
signalWireLetters[a]=0;
signalWireLetters[b]=1;
signalWireLetters[c]=2;
signalWireLetters[d]=3;
signalWireLetters[e]=4;
signalWireLetters[f]=5;
signalWireLetters[g]=6;
if (signalsDecodeCorrectly(signalWireLetters, signalsToDecode))
{
return signalWireLetters;
}
}
}
}
}
}
}
}
throw new IllegalStateException("Couldn't find a valid signal decode");
}
private boolean signalsDecodeCorrectly(final char[] signalWireLetters, final String[] signalsToDecode)
{
for (final String signal : signalsToDecode)
{
final boolean[] litSegments = decodeSignalToLitSegments(signalWireLetters, signal);
if (!isValidDigit(litSegments)) return false;
}
return true;
}
private boolean[] decodeSignalToLitSegments(final char[] signalWireLetters, final String signal)
{
final boolean[] litSegments = new boolean[7];
for (final char c : signal.toCharArray())
{
switch (c)
{
case 'a':
litSegments[signalWireLetters[0]] = true;
break;
case 'b':
litSegments[signalWireLetters[1]] = true;
break;
case 'c':
litSegments[signalWireLetters[2]] = true;
break;
case 'd':
litSegments[signalWireLetters[3]] = true;
break;
case 'e':
litSegments[signalWireLetters[4]] = true;
break;
case 'f':
litSegments[signalWireLetters[5]] = true;
break;
case 'g':
litSegments[signalWireLetters[6]] = true;
break;
default:
throw new IllegalStateException("Invalid letter: " + c);
}
}
return litSegments;
}
// the rest of the code will be in the next post
// the first part of this code is in the previous post
private boolean isValidDigit(final boolean[] litSegments)
{
if (isZeroDigit(litSegments)) return true;
if (isOneDigit(litSegments)) return true;
if (isTwoDigit(litSegments)) return true;
if (isThreeDigit(litSegments)) return true;
if (isFourDigit(litSegments)) return true;
if (isFiveDigit(litSegments)) return true;
if (isSixDigit(litSegments)) return true;
if (isSevenDigit(litSegments)) return true;
if (isEightDigit(litSegments)) return true;
if (isNineDigit(litSegments)) return true;
return false;
}
private boolean isZeroDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[1]) &&
(litSegments[2]) &&
(litSegments[4]) &&
(litSegments[5]) &&
(litSegments[6]) &&
(!litSegments[3])
) return true;
return false;
}
private boolean isOneDigit(final boolean[] litSegments)
{
if (
(litSegments[2]) &&
(litSegments[5]) &&
(!litSegments[0]) &&
(!litSegments[1]) &&
(!litSegments[3]) &&
(!litSegments[4]) &&
(!litSegments[6])
) return true;
return false;
}
private boolean isTwoDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[2]) &&
(litSegments[3]) &&
(litSegments[4]) &&
(litSegments[6]) &&
(!litSegments[1]) &&
(!litSegments[5])
) return true;
return false;
}
private boolean isThreeDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[2]) &&
(litSegments[3]) &&
(litSegments[5]) &&
(litSegments[6]) &&
(!litSegments[1]) &&
(!litSegments[4])
) return true;
return false;
}
private boolean isFourDigit(final boolean[] litSegments)
{
if (
(litSegments[1]) &&
(litSegments[2]) &&
(litSegments[3]) &&
(litSegments[5]) &&
(!litSegments[0]) &&
(!litSegments[4]) &&
(!litSegments[6])
) return true;
return false;
}
private boolean isFiveDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[1]) &&
(litSegments[3]) &&
(litSegments[5]) &&
(litSegments[6]) &&
(!litSegments[2]) &&
(!litSegments[4])
) return true;
return false;
}
private boolean isSixDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[1]) &&
(litSegments[3]) &&
(litSegments[4]) &&
(litSegments[5]) &&
(litSegments[6]) &&
(!litSegments[2])
) return true;
return false;
}
private boolean isSevenDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[2]) &&
(litSegments[5]) &&
(!litSegments[1]) &&
(!litSegments[3]) &&
(!litSegments[4]) &&
(!litSegments[6])
) return true;
return false;
}
private boolean isEightDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[1]) &&
(litSegments[2]) &&
(litSegments[3]) &&
(litSegments[4]) &&
(litSegments[5]) &&
(litSegments[6])
) return true;
return false;
}
private boolean isNineDigit(final boolean[] litSegments)
{
if (
(litSegments[0]) &&
(litSegments[1]) &&
(litSegments[2]) &&
(litSegments[3]) &&
(litSegments[5]) &&
(litSegments[6]) &&
(!litSegments[4])
) return true;
return false;
}
}
public static long getPart1Answer(final String day08Input, final String[] day08InputLines)
{
final Pattern p = Pattern.compile("[\\w\\s]+ \\| ([\\w\\s]+)");
int count = 0;
for (final String s: day08InputLines)
{
final Matcher m = p.matcher(s);
if (!m.matches()) throw new IllegalStateException("Couldn't parse pattern: " + s);
final String[] parts = m.group(1).split(" ");
if (parts.length != 4) throw new IllegalStateException("Didn't get 4 parts after the | " + m.group(1));
for (final String part: parts)
{
switch(part.length())
{
case 2:
case 3:
case 4:
case 7:
count++;
break;
default: // ignore
}
}
}
return count;
}
public static long getPart2Answer(final String day08Input, final String[] day08InputLines)
{
long sum = 0;
final Pattern p = Pattern.compile("([\\w\\s]+) \\| ([\\w\\s]+)");
for (final String s: day08InputLines)
{
final Matcher m = p.matcher(s);
if (!m.matches()) throw new IllegalStateException("Couldn't parse pattern: " + s);
final String[] leftParts = m.group(1).split(" ");
if (leftParts.length != 10) throw new IllegalStateException("Didn't get 10 parts before the | " + m.group(1));
final String[] rightParts = m.group(2).split(" ");
if (rightParts.length != 4) throw new IllegalStateException("Didn't get 4 parts after the | " + m.group(1));
final SevenSegmentLED ssLED = new SevenSegmentLED(leftParts);
int fourDigits = 0;
for (final String digitSignals: rightParts)
{
fourDigits *= 10;
fourDigits += ssLED.getDigitFromSignals(digitSignals);
}
sum += fourDigits;
}
return sum;
}
While an intellectual challenge for sure, there seems little benefit to pursuing it, especially if you're at all hurrying to solve quickly. I was assuming such an approach was possible as I was doing the brute force permutations, but I decided it would be far faster to copy and paste nested loops than it would be to try any other approach. I wrote a card game server once, and it needed to check card permutations, so I have that code around here somewhere... but again it would have taken longer to find and integrate it than to do what I did.then I decided to look for a better method.