import { sum } from "util/array";

// If blank strings/ints is not enough
export const inputMapper = (inputs: string) => inputs;

// index of char is their priority
const priority = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

export function solution1(inputs: string[]): number {
  const items = inputs.map((inputs) => [
    inputs.slice(0, inputs.length / 2),
    inputs.slice(inputs.length / 2),
  ]).map(([bag1, bag2]) =>
    // Find duplicate
    bag1.split("").filter((c) => bag2.includes(c))[0]
  ).map((item) => priority.indexOf(item));

  return sum(items);
}

export function partitionArray<T>(arr: T[], partitionSize: number): T[][] {
  return arr.reduce((all: T[][], one: T, i: number) => {
    const chunk = Math.floor(i / partitionSize);

    all[chunk] = ([] as T[]).concat(
      all[chunk] ?? [],
      one,
    );

    return all;
  }, []);
}

export function solution2(inputs: string[]): number {
  const groups = partitionArray(inputs, 3);

  const items = groups.map(([bag1, bag2, bag3]) =>
    bag1.split("").filter((c) => bag2.includes(c)).filter((c) =>
      bag3.includes(c)
    )[0]
  ).map((item) => priority.indexOf(item));

  return sum(items);
}
