import { Coll, Collection } from "util/collection";

export interface MappedInputs {
  time: number;
  distance: number;
}

// If blank strings/ints is not enough
export const inputMapper = (
  inputs: Collection<string>,
): Collection<MappedInputs> => {
  const times = inputs[0].split("Time:", 2)[1].replace(/ +/g, " ").trim().split(
    " ",
  ).map(Number);

  const distances = inputs[1].split("Distance:", 2)[1].replace(
    / +/g,
    " ",
  ).trim().split(" ").map(Number);

  return Coll(...times.map((
    time,
    i,
  ) => ({ time, distance: distances[i] } as MappedInputs)));
};

function countOptions(time: number, distance: number): number {
  let result = 0;

  for (let i = 0; i < time; i++) {
    if (i * (time - i) > distance) {
      result++;
    }
  }

  return result;
}

export function solution1(inputs: Collection<MappedInputs>): number {
  const results = inputs.map(({ time, distance }) =>
    countOptions(time, distance)
  );

  return results.filter((r) => r > 0).reduce((acc, curr) => acc * curr, 1);
}

export function solution2(inputs: Collection<MappedInputs>): number {
  const input = inputs.map((v) => ({
    time: v.time + "",
    distance: v.distance + "",
  })).reduce(
    (acc, cur) => {
      return {
        time: acc.time + cur.time,
        distance: acc.distance + cur.distance,
      };
    },
    { time: "", distance: "" },
  );

  return countOptions(Number(input.time), Number(input.distance));
}
