Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.2 kB
2
Indexable
Never
const fs = require('fs');
const input = fs.readFileSync('input.txt').toString();
const numbers = input.split(',').filter(v => v).map(Number);

const findMinCost = (numbers) => {
  const map = {};

  numbers.forEach((item) => {
    let sum = 0;

    numbers.forEach((pos) => {
      const diff = Math.abs(item - pos);

      sum += diff;
    });

    map[item] = sum;
  })

  return Math.min(...Object.values(map));
}

const findMinCost2 = (numbers) => {
  const map = {};
  const longestDistance = Math.max(...numbers);
  const shortestDistance = Math.min(...numbers);
  const length = Math.abs(longestDistance, shortestDistance);
  const allPos = [...new Array(length).fill(0).map((_, i) => i)];

  allPos.forEach((item, idx1) => {
    map[idx1] = [];
    sum = 0;

    numbers.forEach((pos) => {
      let delta = Math.abs(item - pos);
      const cost = [...new Array(delta).fill(0).map((_, i) => i + 1)].reduce((acc, v) => acc + v, 0);

      map[idx1].push(cost);
    });

    map[idx1] = map[idx1].reduce((acc, a) => acc + a);
  })
  
  return Math.min(...Object.values(map));
}

//a
console.log(findMinCost(numbers))

//b
console.log(findMinCost2(numbers));