const input = await Deno.readTextFile("input.txt");
const lines = input.split("\n").map(x=> x.trim()).filter(x=> x.length > 0);

const stars = [] as [number, number][];
lines.forEach(((line,y)=>{
    for (let x = 0; x < line.length; x++) {
        const ch = line[x];
        if(ch === "#"){
            stars.push([x,y])
        }
    }
}));

const emptyRows = lines.map(line => {
    return line.indexOf("#") === -1
});

const emptyColumns = [];
for (let i=0; i< lines[0].length; i++){
    let isExist = false;
    for (let j = 0; j < lines.length; j++) {
        if (lines[j][i] === "#"){
            isExist = true;
            break;
        }
    }
    emptyColumns.push(!isExist);
}
console.log("columns",emptyColumns, "rows", emptyRows)

function reduceMap<T,R>(array: T[], init:R, fn: (acc: R, elem: T) => R){
    let acc = init;
    const ret = [] as R[];
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        acc = fn(acc, element);
        ret.push(acc)
    }
    return ret;
}

const columnsAdder = reduceMap(emptyColumns, 0, (acc, elem)=>{
    return acc + (elem ? 1000000 - 1 : 0);
});

const rowsAdder = reduceMap(emptyRows, 0, (acc, elem)=>{
    return acc + (elem ? 1000000 - 1 : 0);
});
console.log(columnsAdder, rowsAdder);

// expand stars
const expandedStars = stars.map(star => {
    const [x,y] = star;
    return [
        x 
        + columnsAdder[x],
        y 
        + rowsAdder[y],
    ] as [number, number]
});

console.log(expandedStars);

function drawStarMap(stars: [number,number][], width: number, height:number){
    const map = new Array(height).fill(0).map(()=>new Array(width).fill("."));
    stars.forEach(([x,y])=>{
        map[y][x] = "#";
    });
    return map.map(x => x.join("")).join("\n");
}

// console.log(drawStarMap(expandedStars, 13, 12));


// for each only stars pair, get distance
const dists = expandedStars.flatMap((star1, i)=>{
    return expandedStars.slice(i+1).map((star2)=>{
        const dist = Math.abs(star1[0] - star2[0]) + Math.abs(star1[1] - star2[1])
        return dist;
    })
});

console.log(dists);
console.log(dists.reduce((a, b) => a + b, 0));