import { Coll, Collection, Collection2D } from "util/collection";
import { CountMap } from "util/count-map";

type Color = "red" | "green" | "blue";

// If blank strings/ints is not enough
export const inputMapper = (inputs: string): Collection<[number, Color]> => {
  const [_, games] = inputs.split(": ");
  const sets = games.split("; ");

  const p = sets.map((s) => s.split(", ")).flat().map((s) => {
    const [count, color] = s.split(" ");
    return [parseInt(count), color] as [number, Color] as [number, Color];
  });

  return Coll(...p);
};

export function solution1(inputs: Collection2D<[number, Color]>): number {
  let result = 0;

  for (let i = 0; i < inputs.length; i++) {
    const game = inputs[i];

    const counter = new CountMap();
    for (const [count, color] of game) {
      counter.max(color, count);
    }

    if (
      counter.get("red") <= 12 &&
      counter.get("green") <= 13 &&
      counter.get("blue") <= 14
    ) {
      result += i + 1;
    }
  }

  return result;
}

export function solution2(inputs: Collection2D<[number, Color]>): number {
  let result = 0;

  for (let i = 0; i < inputs.length; i++) {
    const game = inputs[i];

    const counter = new CountMap();
    for (const [count, color] of game) {
      counter.max(color, count);
    }

    result += counter.get("red") * counter.get("green") * counter.get("blue");
  }

  return result;
}
