diff --git a/2022/CampCleanup.java b/2022/CampCleanup.java new file mode 100644 index 0000000..c925040 --- /dev/null +++ b/2022/CampCleanup.java @@ -0,0 +1,58 @@ +package adventofcode; + +import java.util.List; + +public class CampCleanup { + public static void main(String[] args) { + List fileContents = CodeUtility.readFile("/Users/raghu.kokku/code/AdventOfCode/CampCleanup.txt"); + + int count =0; + int overlapCount = 0; + + + for (String line : fileContents ) { + if (isPair(line)) { + count++; + } + if (doesOverlap(line)) { + overlapCount++; + } + } + + System.out.printf("Count = %d\n", count); + System.out.printf("Count of overlap = %d", overlapCount); + + } + + private static boolean isPair(String line) { + String[] pairs = line.split(","); + + String[] firstPair = pairs[0].split("-"); + String[] secondPair = pairs[1].split("-"); + + int firstNumberInPair1 = Integer.valueOf(firstPair[0]); + int secondNumberInPair1 = Integer.valueOf(firstPair[1]); + int firstNumberInPair2 = Integer.valueOf(secondPair[0]); + int secondNumberInPair2 = Integer.valueOf(secondPair[1]); + + return ((firstNumberInPair1 <= firstNumberInPair2 && secondNumberInPair1 >= secondNumberInPair2) || + ((firstNumberInPair1 >= firstNumberInPair2 && secondNumberInPair1 <= secondNumberInPair2))); + } + + private static boolean doesOverlap(String line) { + String[] pairs = line.split(","); + + String[] firstPair = pairs[0].split("-"); + String[] secondPair = pairs[1].split("-"); + + int firstNumberInPair1 = Integer.valueOf(firstPair[0]); + int secondNumberInPair1 = Integer.valueOf(firstPair[1]); + int firstNumberInPair2 = Integer.valueOf(secondPair[0]); + int secondNumberInPair2 = Integer.valueOf(secondPair[1]); + + return (firstNumberInPair2 >= firstNumberInPair1 && firstNumberInPair2 <= secondNumberInPair1) || + (firstNumberInPair1 >= firstNumberInPair2 && firstNumberInPair1 <= secondNumberInPair2) || + (secondNumberInPair1 == secondNumberInPair2); + } + +} diff --git a/2022/CodeUtility.java b/2022/CodeUtility.java new file mode 100644 index 0000000..4ca48f7 --- /dev/null +++ b/2022/CodeUtility.java @@ -0,0 +1,18 @@ +package adventofcode; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +public class CodeUtility { + + protected static List readFile(String filePath) { + try { + return Files.readAllLines(Paths.get(filePath)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/2022/Commands.java b/2022/Commands.java new file mode 100644 index 0000000..05fde16 --- /dev/null +++ b/2022/Commands.java @@ -0,0 +1,30 @@ +package adventofcode; + +import java.util.LinkedList; + +class Graph { + int vertex; + LinkedList list[]; + + public Graph (int vertex) { + this.vertex = vertex; + list = new LinkedList[vertex]; + + for(int i=0; i(); + } + } + + public void addEdge(String source, String destination) { + list[source].add(destination); + } +} + + + + + + +public class Commands { + +} diff --git a/2022/ElfCalorieCounter.java b/2022/ElfCalorieCounter.java new file mode 100644 index 0000000..86959fa --- /dev/null +++ b/2022/ElfCalorieCounter.java @@ -0,0 +1,66 @@ +package adventofcode; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Collections; + +import org.apache.commons.lang3.StringUtils; +/* + * 1) Read all lines from an input file. + * 2) Iterate through each line and sum the values until you encounter new line + * 3) Calculate the max as we sum the values for each elf + */ + +public class ElfCalorieCounter { + + public static void main(String[] args) { + + final String filePath = "/Users/raghu.kokku/code/AdventOfCode/ElfCalorieCounter.txt"; + + int maxCalories = Integer.MIN_VALUE; + + try { + List allInputLines = Files.readAllLines(Paths.get(filePath)); + List listOfItems = new ArrayList<>(); + Set maxCaloriesOfEachElf = new HashSet<>(); + + for (String line : allInputLines) { + + if(StringUtils.isBlank(line)) { + maxCaloriesOfEachElf.add(caloriesForEachElf(listOfItems)); + maxCalories = Math.max(maxCalories, caloriesForEachElf(listOfItems)); + listOfItems.clear(); + } else { + listOfItems.add(Integer.valueOf(line)); + } + } + + System.out.printf("Max calories = %d\n", maxCalories); + + System.out.printf("Max calories of first three = %d", sumOfTopThree(maxCaloriesOfEachElf)); + + + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static int caloriesForEachElf(List calories) { + return calories.stream().mapToInt(c -> c).sum(); + } + + private static int sumOfTopThree(Set maxCalories) { + + List listOfCalories = new ArrayList<>(maxCalories); + + Collections.sort(listOfCalories, Collections.reverseOrder()); + + return (listOfCalories.get(0) + listOfCalories.get(1) + listOfCalories.get(2)); + } + +} diff --git a/2022/GrovePositioningSystem.java b/2022/GrovePositioningSystem.java new file mode 100644 index 0000000..0fa90a0 --- /dev/null +++ b/2022/GrovePositioningSystem.java @@ -0,0 +1,13 @@ +package adventofcode; + +import java.util.List; +import java.util.stream.Collectors; + +public class GrovePositioningSystem { + public static void main(String[] args) { + List fileContents = CodeUtility.readFile("/Users/raghu.kokku/code/AdventOfCode/gps.txt"); + List fileContentsInInts = fileContents.stream().map(Integer::parseInt).collect(Collectors.toList()); + } + + +} diff --git a/2022/MonkeyMath.java b/2022/MonkeyMath.java new file mode 100644 index 0000000..2584780 --- /dev/null +++ b/2022/MonkeyMath.java @@ -0,0 +1,43 @@ +package adventofcode; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MonkeyMath { + + private static List operators = List.of("+", "-", "/", "*"); + private static List fileContents = CodeUtility.readFile("/Users/raghu.kokku/code/AdventOfCode/monkey-yells1.txt"); + private static Map dataMap = dataMap(fileContents); + + public static void main(String[] args) { + + int sum =0; + + for (String value : dataMap.values()) { + + //sum = monkeyMath(value, sum); + + } + + System.out.println("Sum = " + sum); + + } + + + + private static Map dataMap(List fileContents) { + Map dataMap = new HashMap<>(); + + for(String line : fileContents) { + String[] keyValues = line.split(":"); + + String key = keyValues[0].trim(); + String value = keyValues[1].trim(); + + dataMap.put(key, value); + } + + return dataMap; + } +} diff --git a/2022/NoSpaceDisk.java b/2022/NoSpaceDisk.java new file mode 100644 index 0000000..5e6c9b8 --- /dev/null +++ b/2022/NoSpaceDisk.java @@ -0,0 +1 @@ +package adventofcode; diff --git a/2022/RockPaperScissors.java b/2022/RockPaperScissors.java new file mode 100644 index 0000000..fce30d0 --- /dev/null +++ b/2022/RockPaperScissors.java @@ -0,0 +1,90 @@ +package adventofcode; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; + +public class RockPaperScissors { + public static void main(String[] args) { + + List myOptions = List.of("X", "Y", "Z"); + + Map myMap = constructMap(new HashMap<>(), myOptions); + + List winCombinations = List.of("AY", "BZ", "CX"); + List drawCombinations = List.of("AX", "BY", "CZ"); + List loseCombinations = List.of("AZ", "BX", "CY"); + + int totalScore = 0; + + for (String line : readInputFile()) { + + String opponent = line.split(" ")[0]; + String player = line.split(" ")[1]; + + String combination = StringUtils.join(opponent, player); + + if (winCombinations.contains(combination)) { + totalScore += myMap.get(player) + 6; + } else if (drawCombinations.contains(combination)) { + totalScore += myMap.get(player) + 3; + } else if (loseCombinations.contains(combination)) { + totalScore += myMap.get(player); + } + } + + System.out.printf("Total score = %d\n", totalScore); + System.out.printf("Total score = %d", partTwo(myMap, winCombinations, drawCombinations, loseCombinations)); + + } + + private static Map constructMap(Map playerMap, List listOfOptions) { + int i = 1; + for(String c : listOfOptions) { + playerMap.put(c, i++); + } + return playerMap; + } + + private static List readInputFile() { + try { + return Files.readAllLines(Paths.get("/Users/raghu.kokku/code/AdventOfCode/RockPaperScissors.txt")); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static int partTwo(Map compareMap, List winCombinations, + List drawCombinations, List loseCombinations) { + int score = 0; + + for (String line : readInputFile()) { + String opponent = line.split(" ")[0]; + String player = line.split(" ")[1]; + + if (player.equals("Y")) { + List result = drawCombinations.stream().filter(s -> s.startsWith(opponent)).collect(Collectors.toList()); + char[] chars = result.get(0).toCharArray(); + score += compareMap.get(String.valueOf(chars[1])) + 3; + } else if (player.equals("X")) { + List result = loseCombinations.stream().filter(s -> s.startsWith(opponent)).collect(Collectors.toList()); + char[] chars = result.get(0).toCharArray(); + score += compareMap.get(String.valueOf(chars[1])) + 0; + } else if (player.equals("Z")) { + List result = winCombinations.stream().filter(s -> s.startsWith(opponent)).collect(Collectors.toList()); + char[] chars = result.get(0).toCharArray(); + score += compareMap.get(String.valueOf(chars[1])) + 6; + } + } + + return score; + } + + +} diff --git a/2022/RuckSack.java b/2022/RuckSack.java new file mode 100644 index 0000000..af0b5a3 --- /dev/null +++ b/2022/RuckSack.java @@ -0,0 +1,105 @@ +package adventofcode; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RuckSack { + + private final static Map characterMap = characterMap(new HashMap<>()); + + public static void main(String[] args) { + + String filePath = "/Users/raghu.kokku/code/AdventOfCode/rucksack.txt"; + + List ruckSacks = CodeUtility.readFile(filePath); + int sum =0; + + for(String line : ruckSacks) { + + int median = line.length() / 2; + String firstString = line.substring(0, median); + String secondString = line.substring(median, line.length()); + + char result = compareStringsAndReturnChar(firstString, secondString); + + if (Character.isLowerCase(result)) { + sum += characterMap.get(result); + } else { + sum += (characterMap.get(Character.toLowerCase(result)) + 26); + } + } + + System.out.printf("Sum = %d\n", sum); + System.out.printf("Sum of priorities = %d", sumOfPrioritiesForGroup(ruckSacks)); + + } + + private static Map characterMap(Map lowercaseMap) { + int priority =1; + + for (int i = 97; i< 124; i++) { + lowercaseMap.put((char)i, priority++); + } + + return lowercaseMap; + } + + private static char compareStringsAndReturnChar(String first, String second) { + char[] firstChars = first.toCharArray(); + + for(char ch : firstChars) { + if (second.indexOf(ch) != -1) { + return ch; + } + } + return 0; + } + + private static void compareStringsAndPopulateMap(String first, String second, Map comparisionMap) { + char[] firstChars = first.toCharArray(); + + for(char ch : firstChars) { + if (second.indexOf(ch) != -1) { + int count = comparisionMap.getOrDefault(ch, 0); + comparisionMap.put(ch, count+1); + } + } + } + + private static char checkIfCharacterExists(String str, Map comparisionMap) { + + for(char ch : str.toCharArray()) { + boolean exists = comparisionMap.entrySet().stream().anyMatch(entry -> ch == entry.getKey()); + if (exists) { + return ch; + } + } + return Character.MIN_VALUE; + } + + private static int sumOfPrioritiesForGroup(List listOfItemTypes) { + + int sum = 0; + + Map comparisionMap = new HashMap<>(); + + for(int i=0;i fileContents = CodeUtility.readFile("/Users/raghu.kokku/code/AdventOfCode/crates.txt"); + Map> dataMap = constructMap(); + + supplyStack(fileContents, dataMap); + + System.out.printf("Message = %s\n", peek(dataMap)); + } + + private static String peek(Map> dataMap) { + StringBuilder result = new StringBuilder(); + + dataMap.entrySet().forEach(entry -> { + Stack stackInMap = entry.getValue(); + if (!stackInMap.isEmpty()) { + result.append(stackInMap.peek()); + } + }); + + return result.toString(); + } + + private static void supplyStack(List fileContents, Map> dataMap) { + + for (String line : fileContents) { + String replacedStringWithUnderscores = line.replace("move ", "").replace(" from ","_").replace(" to ","_"); + String[] digits = replacedStringWithUnderscores.split("_"); + + int numberOfMoves = Integer.parseInt(digits[0]); + int sourceStackNumber = Integer.parseInt(digits[1]); + int destStackNumber = Integer.parseInt(digits[2]); + + Stack sourceStack = dataMap.get(sourceStackNumber); + Stack destinationStack = dataMap.get(destStackNumber); + + if (numberOfMoves <= sourceStack.size()) { + StringBuilder result = new StringBuilder(); + for (int i=0 ; i> constructMap() { + Map> dataMap = new HashMap<>(); + + dataMap.put(1, List.of("B", "Q", "C")); + dataMap.put(2, List.of("R", "Q", "W", "Z")); + dataMap.put(3, List.of("B", "M", "R", "L", "V")); + dataMap.put(4, List.of("C", "G", "H", "V", "T", "W")); + dataMap.put(5, List.of("D", "Z", "H", "B", "N", "V", "G")); + dataMap.put(6, List.of("H", "N", "P", "C", "J", "F", "V", "Q")); + dataMap.put(7, List.of("D", "G", "T", "R", "W", "Z", "S")); + dataMap.put(8, List.of("C", "G", "M", "N", "B", "W", "Z", "P")); + dataMap.put(9, List.of("N", "J", "B", "M", "W", "Q", "F", "P")); + + return constructStackMap(dataMap); + + } + + private static Map> constructStackMap(Map> dataMap) { + + Map> stackMap = new HashMap<>(); + + for(Map.Entry> entry : dataMap.entrySet()) { + + int key = entry.getKey(); + List values = entry.getValue(); + Stack crates = new Stack<>(); + + values.stream().forEach(s -> { + crates.push(s); + }); + + stackMap.put(key, crates); + } + + return stackMap; + } + +} diff --git a/2022/TreeVisibility.java b/2022/TreeVisibility.java new file mode 100644 index 0000000..e3564a3 --- /dev/null +++ b/2022/TreeVisibility.java @@ -0,0 +1,59 @@ +package adventofcode; + +import java.util.List; + +public class TreeVisibility { + public static void main(String[] args) { + + List fileContents = CodeUtility.readFile("/Users/raghu.kokku/code/AdventOfCode/map1.txt"); + + int[][] matrix = convertFileContentsToMatrix(fileContents); + + int edges = numberOfEdgeColumns(fileContents) + numberOfEdgeRows(fileContents); + + int visibleTrees = visibleTrees(matrix); + + System.out.println(edges+visibleTrees); + } + + + private static int visibleTrees(int[][] matrix) { + int numberOfVisibleTrees = 0; + int length = matrix.length - 1; + + for (int row = 1; row < length; row++ ) { + for (int column = 1; column < length; column++) { + if (matrix[row][column] > matrix[row-1][column] || matrix[row][column] > matrix[row][column-1] + || matrix[row][column] > matrix[row+1][column] || matrix[row][column] > matrix[row][column+1]) { + numberOfVisibleTrees++; + } + } + } + return numberOfVisibleTrees; + + } + + private static int[][] convertFileContentsToMatrix(List fileContents) { + + int[][] matrix = new int[fileContents.size()][fileContents.get(0).toCharArray().length]; + + for (int row = 0; row< fileContents.size(); row++) { + char[] chars = fileContents.get(row).toCharArray(); + for (int column =0; column < chars.length; column++) { + matrix[row][column] = Character.getNumericValue(chars[column]); + } + } + + return matrix; + } + + private static int numberOfEdgeColumns(List fileContents) { + char[] chars = fileContents.get(0).toCharArray(); + return 2 * chars.length; + } + + private static int numberOfEdgeRows(List fileContents) { + return 2 * (fileContents.size() -2); + } + +} diff --git a/2022/TuningTrouble.java b/2022/TuningTrouble.java new file mode 100644 index 0000000..313a9dd --- /dev/null +++ b/2022/TuningTrouble.java @@ -0,0 +1,84 @@ +package adventofcode; + +import java.util.HashSet; +import java.util.List; +import java.util.Scanner; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +public class TuningTrouble { + public static void main(String[] args) { + List fileContents = CodeUtility.readFile("/Users/raghu.kokku/code/AdventOfCode/marker.txt"); + + Scanner scan = new Scanner(System.in); + int countOfDistinctCharacters = scan.nextInt(); + + + + System.out.printf("Result = %d", findMarker(fileContents, countOfDistinctCharacters)); + System.out.printf("Result = %d", findMarkerDynamically(fileContents, countOfDistinctCharacters)); + + } + + private static int findMarker(List fileContents, int countOfDistinctCharacters) { + Set setOfCharacters = new HashSet<>(); + + int start = 0; + int end = 0; + + for (String line : fileContents) { + char[] chars = line.toCharArray(); + + while (end < chars.length) { + + if (setOfCharacters.size() == countOfDistinctCharacters) { + return end; + } + + if (setOfCharacters.add(chars[end])) { + end++; + } else if (!setOfCharacters.add(chars[end])) { + start++; + end = start; + setOfCharacters.clear(); + } + } + } + + return 0; + } + + private static int findMarkerDynamically(List fileContents, int countOfDistinctCharacters) { + String markerString = StringUtils.EMPTY; + + int start = 0; + int end = 0; + + for (String line : fileContents) { + char[] chars = line.toCharArray(); + + while (end < chars.length) { + + if (markerString.length() == countOfDistinctCharacters) { + return end; + } + + if (markerString.contains(String.valueOf(chars[end]))) { + markerString = StringUtils.EMPTY; + start++; + end = start; + } else { + markerString = StringUtils.join(markerString, chars[end]); + end ++; + } + } + } + return 0; + } + + + + + +}