Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
¿Cómo se divide la permutación de matriz por (n)?

Entonces tengo una matriz

 const arr = [ 1, 4, 5, 8]

Quiero obtener todas las combinaciones posibles de esta matriz divididas por (n) número, por ejemplo

 function getNPermutate(arr, n) { } getNPermutate(arr, 3) // [[1, 4, 5], [1, 4, 8], [4, 5, 8],[1, 5 ,8] ]

!array puede tener cualquier longitud

Encontré la solución con permutación simple, pero no entiendo cómo se hace la permutación dividida

 function permute(nums) { let result = []; if (nums.length === 0) return []; if (nums.length === 1) return [nums]; for (let i = 0; i < nums.length; i++) { const currentNum = nums[i]; const remainingNums = nums.slice(0, i).concat(nums.slice(i + 1)); const remainingNumsPermuted = permute(remainingNums); for (let j = 0; j < remainingNumsPermuted.length; j++) { const permutedArray = [currentNum].concat(remainingNumsPermuted[j]); result.push(permutedArray); } } return result; } console.log(permute([1,2,3,4]))
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puedes probar este:

Guion:

 function test() { var array = [1, 4, 5, 8]; console.log(getCombinations(array, 3)) } function getCombinations(chars, len) { var result = []; var f = function(prefix, chars) { for (var i = 0; i < chars.length; i++) { var elem = [...prefix, chars[i]]; if(elem.length == len) result.push(elem); f(elem, chars.slice(i + 1)); } } f([], chars); return result; }

Producción:

producción

about 4 years ago · Juan Pablo Isaza Report

0

Podrías usar un generador recursivo:

 function* iterPerms(arr, n, first=0) { if (n > arr.length - first) return; if (n === 0) return yield []; for (const res of iterPerms(arr, n - 1, first + 1)) yield [arr[first], ...res]; yield* iterPerms(arr, n, first + 1); } const arr = [1, 4, 5, 8]; for (let perm of iterPerms(arr, 3)) console.log(...perm);

Para convertir el generador en una función normal que devuelve una matriz anidada, haz lo siguiente:

 const getNPermutate = (arr, n) => Array.from(iterPerms(arr, n));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!