Skip to content

construct the array #7

Open
Open

Description

Activity

  1. prabaprakash commented on Aug 4, 2020

    @prabaprakash
    OwnerAuthor

    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
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions