“Permutasi JavaScript” Kode Jawaban

Bagaimana menemukan semua permutasi array dengan JavaScript

function getArrayMutations(arr, perms = [], len = arr.length) {
  if (len === 1) perms.push(arr.slice(0))

  for (let i = 0; i < len; i++) {
    getArrayMutations(arr, perms, len - 1)

    len % 2 // parity dependent adjacent elements swap
      ? [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]]
      : [arr[i], arr[len - 1]] = [arr[len - 1], arr[i]]
  }

  return perms
}
m1ke510a

Permutasi JavaScript

const permutations = arr => {
  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
  return arr.reduce(
    (acc, item, i) =>
      acc.concat(
        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
          item,
          ...val,
        ])
      ),
    []
  );
};
Arrogant Anteater

array permutasi

const permute = (input = [], permutation = []) => {
    if (input.length === 0) return [permutation]; // this will be one of the result

    // choose each number in a loop
    return input.reduce((allPermutations, current) => {
        // reduce the input by removing the current element
        // as we'll fix it by putting it in `permutation` array
        const rest = input.filter(n => n != current);
        return [
            ...allPermutations,
            // fixing our choice in the 2nd arg
            // by concatenationg current with permutation
            ...permute(rest, [...permutation, current])
        ];
    }, []);
}
Hilarious Hoopoe

Jawaban yang mirip dengan “Permutasi JavaScript”

Pertanyaan yang mirip dengan “Permutasi JavaScript”

Lebih banyak jawaban terkait untuk “Permutasi JavaScript” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya