Published
Edited
Sep 21, 2020
1 star
Insert cell
Insert cell
Insert cell
// https://medium.com/@NickMa38/combinations-and-permutations-with-an-intro-to-backtracking-d940683ea9de
combine = (list, k) => {
let combinations = [];
const backtracking = (results, path, depth, options) => {
if (depth === 0) results.push([...path]);
else
options.forEach((num, index) => {
path.push(num);
backtracking(results, path, depth - 1, options.slice(index + 1));
path.pop();
});
};
backtracking(combinations, [], k, list);
return combinations;
}
Insert cell
combine([1, 2, 3, 4, 5], 2)
Insert cell
permute = list => {
let permuted = [];
const backtracking = (permutations, path, options) => {
if (path.length === options.length) permutations.push([...path]);
else
options.forEach(option => {
if (path.includes(option)) return null;
path.push(option);
backtracking(permutations, path, options);
path.pop();
});
};
backtracking(permuted, [], list);
return permuted;
}
Insert cell
permute([1, 2, 3])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more