Day 4 implementation in Java
parent
d32cbd51ec
commit
12c1267fcc
|
|
@ -0,0 +1,39 @@
|
|||
package day4;
|
||||
|
||||
import io.vavr.collection.List;
|
||||
import lombok.Getter;
|
||||
|
||||
public class Card {
|
||||
private static final String CARD_ID_SEPARATOR = ":";
|
||||
private static final String CARD_NUMBERS_SEPARATOR = "\\|";
|
||||
private static final String CARD_ID_PREFIX = "Card";
|
||||
|
||||
@Getter
|
||||
private final Integer id;
|
||||
private final List<Integer> winningNumbers;
|
||||
private final List<Integer> cardNumbers;
|
||||
public Card(String cardRepresentation) {
|
||||
String[] splitCardRepresentation = cardRepresentation.split(CARD_ID_SEPARATOR, 2);
|
||||
this.id = Integer.parseInt(splitCardRepresentation[0].replace(CARD_ID_PREFIX, "").replaceAll(" ", ""));
|
||||
|
||||
String[] splitNumbers = splitCardRepresentation[1].split(CARD_NUMBERS_SEPARATOR, 2);
|
||||
this.winningNumbers = convertStringToListOfNumbers(splitNumbers[0]);
|
||||
this.cardNumbers = convertStringToListOfNumbers(splitNumbers[1]);
|
||||
}
|
||||
|
||||
private List<Integer> convertStringToListOfNumbers(String inputString) {
|
||||
return List.of(inputString.split(" "))
|
||||
.filter(string -> !string.isEmpty())
|
||||
.map(string -> string.replaceAll(" ", ""))
|
||||
.map(Integer::parseInt);
|
||||
}
|
||||
|
||||
public Integer getNumberOfMatches() {
|
||||
return cardNumbers.filter(winningNumbers::contains).length();
|
||||
}
|
||||
|
||||
public Integer getScore() {
|
||||
Integer numberOfMatches = getNumberOfMatches();
|
||||
return numberOfMatches == 0 ? 0 : (new Double(Math.pow(2, numberOfMatches - 1))).intValue();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package day4;
|
||||
|
||||
import io.vavr.collection.List;
|
||||
import util.FileReader;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
String inputFilePath = System.getProperty("user.dir") + "\\java\\src\\main\\java\\day4\\input.txt";
|
||||
FileReader reader = new FileReader(inputFilePath);
|
||||
List<String> inputData = List.ofAll(reader.readContents());
|
||||
|
||||
List<Card> cards = inputData.map(Card::new);
|
||||
System.out.println(cards.map(Card::getScore).reduce(Integer::sum));
|
||||
|
||||
HashMap<Card, Integer> cardsCount = new HashMap<>();
|
||||
cards.forEach(card -> cardsCount.put(card, 1));
|
||||
cards.forEach(card -> {
|
||||
Integer matches = card.getNumberOfMatches();
|
||||
Integer numberOfCards = cardsCount.get(card);
|
||||
for (Integer index = card.getId(); index < card.getId() + matches; index++) {
|
||||
Card currentCard = cards.get(index);
|
||||
cardsCount.put(currentCard, cardsCount.get(currentCard) + numberOfCards);
|
||||
}
|
||||
});
|
||||
|
||||
Integer numberOfCards = cardsCount.values().stream().reduce(Integer::sum).orElse(0);
|
||||
System.out.println(numberOfCards);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue