Firstly, style looks good. Indentation, spacing, etc. is good. Common mistakes include indenting code inconsistently or in a way that does not match the scope of the code, your code does not have those issues.
change()
All this appears to do is move the first element to the last place and shift all the other elements down by 1. You could do this without creating a separate array:
function change(A) {
let tmp = A[0];
for (let i = 0; i < A.length - 1;) {
A[i] = A[++i];
}
A[A.length - 1] = tmp;
}
Remove the if
in the loop in change()
regardless
But if you wanted to use the method that creates a temporary copy of the original array, instead of checking for the last iteration of the loop:
for (let i = 0; i < x.length; i++) {
A[i] = x[i + 1];
if (i == (x.length - 1)) {
A[i] = x[0];
}
}
Just move the statement outside the loop (and make the loop iterate one less time because you will overwrite the value anyway):
for (let i = 0; i < x.length - 1; i++) {
A[i] = x[i + 1];
}
A[x.length - 1] = x[0];
combinations()
and global variables
combinations()
simply accesses a global array hardcoded in the function. Defining a function that takes no arguments and immediately calling it once is not really better than just having the function body by itself. For better practice and code reuse, you should make combinations()
accept an array parameter:
function combinations(A) {
let b = [];
for (let i = 0; i < A.length; i++) {
b.push([A[0], A[1], A[2]]);
b.push([A[0], A[2], A[1]]);
change(A);
}
console.log(b);
}
Additionally, b
was not used outside combinations()
so should be a local variable instead.
Revised:
function change(A) {
let tmp = A[0];
for (let i = 0; i < A.length - 1;) {
A[i] = A[++i];
}
A[A.length - 1] = tmp;
}
function combinations(A) {
let b = [];
for (let i = 0; i < A.length; i++) {
b.push([A[0], A[1], A[2]]);
b.push([A[0], A[2], A[1]]);
change(A);
}
console.log(b);
}
combinations(["A", "B", "C"]);
As for finding the combinations of arrays larger than 3, you already have a way to do this with arrays of 3, so for one additional element, you could insert that in each one of the possible positions in each one of the existing combinations. You could implement a recursive approach to handle an arbitrary number of elements.