Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Common array elements
- // https://www.codewars.com/kata/5a6225e5d8e145b540000127
- class MultiSet {
- constructor(arr = []) {
- this.dataSet = {};
- for (let item of arr) {
- this.addItem(item);
- }
- }
- setItem(item, quantity = 1) {
- this.dataSet[item] = quantity;
- }
- addItem(item) {
- if (this.dataSet[item])
- this.dataSet[item]++;
- else
- this.dataSet[item] = 1;
- }
- getItem(item) {
- return this.dataSet[item] || 0;
- }
- }
- function common(arr1, arr2, arr3) {
- // Associamo un multiset ad ogni array
- const [ms1, ms2, ms3] = [
- new MultiSet(arr1),
- new MultiSet(arr2),
- new MultiSet(arr3),
- ];
- // Uniamo gli elementi in un unico array
- const merged = [...arr1, ...arr2, ...arr3];
- // Troviamo gli elementi in comune in tutti e 3 gli array
- const common = new MultiSet();
- for (let item of merged) {
- common.setItem(
- item,
- Math.min(
- ms1.getItem(
- item),
- ms2.getItem(item),
- ms3.getItem(item),
- )
- )
- }
- // Somma degli elementi
- // Presenti sia in arr1 che in arr2 che in arr3
- let sum = 0;
- for (let [item, quantity] of Object.entries(common.dataSet)) {
- sum += item * quantity;
- }
- return sum;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement