Hackerrank-JavaScript-Solutions icon indicating copy to clipboard operation
Hackerrank-JavaScript-Solutions copied to clipboard

construct the array

Open prabaprakash opened this issue 4 years ago • 1 comments

https://www.hackerrank.com/challenges/construct-the-array/problem

prabaprakash avatar Aug 04 '20 15:08 prabaprakash

https://gist.github.com/axelpale/3118596 k combinations

const k_combinations = (set, k) => {
  if (k > set.length || k <= 0) {
    return []
  }
  
  if (k == set.length) {
    return [set]
  }
  
  if (k == 1) {
    return set.reduce((acc, cur) => [...acc, [cur]], [])
  }
  
  let combs = [], tail_combs = []
  
  for (let i = 0; i <= set.length - k + 1; i++) {
    tail_combs = k_combinations(set.slice(i + 1), k - 1)
    for (let j = 0; j < tail_combs.length; j++) {
      combs.push([set[i], ...tail_combs[j]])
    }
  }
  
  return combs
}

prabaprakash avatar Aug 04 '20 20:08 prabaprakash