Skip to content

Instantly share code, notes, and snippets.

@dimasmiftah
Created January 30, 2021 09:40
Show Gist options
  • Select an option

  • Save dimasmiftah/63a899f018c903326ecccdac91b21e56 to your computer and use it in GitHub Desktop.

Select an option

Save dimasmiftah/63a899f018c903326ecccdac91b21e56 to your computer and use it in GitHub Desktop.
Calculate all possible combinations of r elements in a given array of size n
const calculateCombination = (arr, r) => {
const data = [];
combinationUtil(arr, data, 0, arr.length - 1, 0, r);
return calculate(result);
};
const combinationUtil = (arr, data, start, end, index, r) => {
if (index == r) {
for (let j = 0; j < r; j++) {
result.push(data[j]);
}
}
let i = start;
while (i <= end && end - i + 1 >= r - index) {
data[index] = arr[i];
combinationUtil(arr, data, i + 1, end, index + 1, r);
i += 1;
}
};
const calculate = (array) => {
let sumAbs = 0;
let divider = 0;
for (let i = 0; i < array.length; i += 2) {
sumAbs += Math.abs(array[i] - array[i + 1]);
divider++;
}
return sumAbs / divider;
};
const arr = [1, 2, 3, 4];
const r = 2;
const result = [];
calculateCombination(arr, r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment