prabaprakash / Hackerrank-JavaScript-Solutions

Solved entire Easy, few Medium Problems. A total of 171/563 challenges solved by JavaScript
https://www.hackerrank.com/prabaprakash
125 stars 64 forks source link

construct the array #7

Open prabaprakash opened 4 years ago

prabaprakash commented 4 years ago

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

prabaprakash commented 4 years ago

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
}