Skip to content

Instantly share code, notes, and snippets.

@leo-bianchi
Forked from adyngom/sockMerchant.js
Last active April 5, 2020 02:40
Show Gist options
  • Save leo-bianchi/9f0ebd0722672509f10fbc7214d619c9 to your computer and use it in GitHub Desktop.
Save leo-bianchi/9f0ebd0722672509f10fbc7214d619c9 to your computer and use it in GitHub Desktop.
function stockAndCount(n, arr) {
let pairs = 0; // pairs number
const colors = arr.reduce((acc, val) => {
acc[val] ? (acc[val] += 1) : (acc[val] = 1);
return acc;
}, {}); // return an object with colors (numbers) as keys and quantity as value
Object.keys(colors).forEach((n) => { // for each key in colors
let _pair = parseInt(colors[n] / 2); // looks for even numbers
if (_pair >= 1) pairs += _pair; // total
});
return pairs;
}
const n = 9;
const socks = [10, 20, 20, 10, 10, 10, 10, 10, 20];
console.group('Stocked and counted');
console.log(`There is a total of ${stockAndCount(n, socks)} pairs`);
console.groupEnd();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment