Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import lsm.helpers.Note;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.HashMap;
- public class Cabbage {
- public static void main(String... args) {
- Note.writenl("Final score: " + score("5D,QS,JC,KH,AC"));
- Note.nl();
- Note.writenl("Final score: " + score("8C,AD,10C,6H,7S"));
- Note.nl();
- Note.writenl("Final score: " + score("AC,6D,5C,10C,8C"));
- }
- private static int score(String input) {
- Card[] cards = Arrays.stream(input.split(",")).map(Card::new).toArray(Card[]::new);
- int score = 0;
- Note.writenl(Arrays.stream(cards).mapToInt(i -> i.n).toArray());
- score += flushes(cards) + nobs(cards);
- Note.writenl("flushes: " + flushes(cards));
- Note.writenl("nobs: " + nobs(cards));
- Arrays.sort(cards, Comparator.comparingInt(o -> o.n));
- score += pairs(cards) + runs(cards) + count(cards);
- Note.writenl("pairs: " + pairs(cards));
- Note.writenl("runs: " + runs(cards));
- Note.writenl("counts: " + count(cards));
- return score;
- }
- private static int count(Card[] cards) {
- return count(cards, 0, 0);
- }
- private static int count(Card[] cards, int i, int val) {
- if(i >= cards.length) return 0;
- int score = 0;
- score += count(cards, i + 1, val);
- val += cards[i].val;
- if(val == 15) score += 2;
- score += count(cards, i + 1, val);
- return score;
- }
- private static int runs(Card[] cards) {
- int streak = 1;
- int best = 1;
- for(int i = 1; i < cards.length; i++)
- if(cards[i].n == cards[i - 1].n + 1) {
- streak++;
- best = streak > best ? streak : best;
- }
- else streak = 1;
- return best > 2 ? best : 0;
- }
- private static int pairs(Card[] cards) {
- int score = 0;
- HashMap<Integer, Integer> map = new HashMap<>();
- for(Card card : cards)
- map.put(card.n, map.getOrDefault(card.n, 0) + 1);
- for(int key : map.keySet())
- switch(map.get(key)){
- case 2: score += 2; break;
- case 3: score += 6; break;
- case 4: score += 12; break;
- }
- return score;
- }
- private static int nobs(Card[] cards) {
- int i = 0;
- for(int j = 0; j < cards.length - 1; j++)
- if(cards[j].type == cards[4].type && cards[j].n == 11)
- i++;
- return i;
- }
- private static int flushes(Card[] cards) {
- char type = cards[0].type;
- for(int i = 1; i < 4; i++)
- if(cards[i].type != type) return 0;
- return cards[4].type == type ? 5 : 4;
- }
- }
- class Card{
- int n;
- int val;
- char type;
- Card(String card) {
- String val = card.substring(0, card.length() - 1);
- type = card.charAt(card.length() - 1);
- try{
- n = Integer.parseInt(val);
- this.val = n;
- } catch(Exception ignored) {
- switch(val) {
- case "A": n = 1; this.val = 1; break;
- case "J": n = 11; this.val = 10; break;
- case "Q": n = 12; this.val = 10; break;
- case "K": n = 13; this.val = 10; break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement