Skip to content

Instantly share code, notes, and snippets.

@gie3d
Created March 26, 2020 02:07
Show Gist options
  • Save gie3d/bd2a1385536ceb1d77855be89638b0b7 to your computer and use it in GitHub Desktop.
Save gie3d/bd2a1385536ceb1d77855be89638b0b7 to your computer and use it in GitHub Desktop.
const fs = require('fs');
fs.readFile('input', 'utf8', (err, contents) => {
// console.log(contents);
const data = parseData(contents);
data.prices.sort((a, b) => a > b);
const result = solve(data.prices, data.m);
console.log(result);
});
const solve = (prices, targetPrice) => {
let result = null;
for (let i = 0; i < prices.length - 1; i++) {
let currentResult = compare(prices[i], targetPrice, prices.slice(i));
// console.log(currentResult);
if (currentResult) {
if (!result || currentResult.diff < result.diff) {
result = currentResult;
}
// console.log('result: ', result);
}
}
return result;
};
const compare = (basePrice, targetPrice, prices) => {
if (prices.length === 1) {
if (basePrice + prices[0] === targetPrice) {
return {
diff: prices[0] - basePrice,
left: basePrice,
right: prices[0],
};
} else {
return null;
}
} else if (basePrice + prices[0] === targetPrice) {
return {
diff: prices[0] - basePrice,
left: basePrice,
right: prices[0],
};
} else {
return compare(basePrice, targetPrice, prices.slice(1));
}
};
const parseData = contents => {
let result = {};
try {
const splitContents = contents.split(/\r?\n/);
result.n = parseInt(splitContents[0]);
result.prices = splitContents[1].split(' ').map(x => parseInt(x));
result.m = parseInt(splitContents[2]);
} catch (e) {
console.log('error: ', e);
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment