Skip to main content
edited tags
Link
John
  • 49
  • 4
Guessed langauge
Link
Toby Speight
  • 81.8k
  • 14
  • 101
  • 309
deleted 12 characters in body
Source Link
toolic
  • 6.4k
  • 4
  • 20
  • 79

I wrote this code to get all possible arrangements for an array containing 3 elements.:

let a = ["A", "B", "C"];
let b = [];

function change(A) {
    let x = [];
    for (let i = 0; i < A.length; i++) {
        x.push(A[i]);
    }
    for (let i = 0; i < x.length; i++) {
        A[i] = x[i + 1];
        if (i == (x.length - 1)) {
            A[i] = x[0];
        }
    }
}

function combinations() {
    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();

My question is howHow can I write this more conciseconcisely, and how is it possible to get all possible arrangements of an array consisting of more than 3 elements.?

I wrote this code to get all possible arrangements for an array containing 3 elements.

let a = ["A", "B", "C"];
let b = [];

function change(A) {
    let x = [];
    for (let i = 0; i < A.length; i++) {
        x.push(A[i]);
    }
    for (let i = 0; i < x.length; i++) {
        A[i] = x[i + 1];
        if (i == (x.length - 1)) {
            A[i] = x[0];
        }
    }
}

function combinations() {
    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();

My question is how can I write this more concise and how is it possible to get all possible arrangements of an array consisting of more than 3 elements.

I wrote this code to get all possible arrangements for an array containing 3 elements:

let a = ["A", "B", "C"];
let b = [];

function change(A) {
    let x = [];
    for (let i = 0; i < A.length; i++) {
        x.push(A[i]);
    }
    for (let i = 0; i < x.length; i++) {
        A[i] = x[i + 1];
        if (i == (x.length - 1)) {
            A[i] = x[0];
        }
    }
}

function combinations() {
    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();

How can I write this more concisely, and how is it possible to get all possible arrangements of an array consisting of more than 3 elements?

Source Link
John
  • 49
  • 4
Loading