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

143
Views
in this combination recursive, is it always return correct answer?

Below is widely known combination function.

function getCombination(arr,selectNumber){
    const result = [];
        if(selectNumber == 1) {
            return arr.map(el => [el])
    };

    arr.forEach((fixed, index, array)=>{

        const rest = array.slice(index+1);
        const combinations = getCombination(rest, selectNumber - 1);
        const attached = combinations.map((el => [fixed,...el]));

        result.push(...attached);

    });

    return result;
};

I traced code and found some useless calculations when (index == array.length-1) in forEach segment. so I added "if()" in that. is it always return correct results?

function getCombination(arr,selectNumber){
    const result = [];
        if(selectNumber == 1) {
            return arr.map(el => [el])
    };

    arr.forEach((fixed, index, array)=>{

        if(index == array.length-1) return; /* I added this line */

        const rest = array.slice(index+1);
        const combinations = getCombination(rest, selectNumber - 1);
        const attached = combinations.map((el => [fixed,...el]));

        result.push(...attached);

    });

    return result;
};

about 4 years ago · Juan Pablo Isaza
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!