Problem Statement:  
For given one dimesional array of numbers find all possible subsets
of that array with specific length.
e.g.
For Array [1,2,3] 
If we want to find all subsets of length 2 then 
Output should be
[
  [1,2],
  [1,3],
  [2,3]
]
Solution:
  function getAllSubsetsOfSpecificLength(array,length) {
      const subsets = [[]];
      const subsetsOfSpecificLength = [];
      for (const el of array) {
          const last = subsets.length - 1;
          for (let i = 0; i <= last; i++) {
              let set = [...subsets[i], el];
              subsets.push(set);
              if(set.length == length){
                  subsetsOfSpecificLength.push(set)
              }
              if(set.length > length){
                  break;
              }
          }
      }
      return subsetsOfSpecificLength;
  }
  let array = [1, 2, 3];
  let result = getAllSubsetsOfSpecificLength(array,2);
  console.log(result); 
Output:
  [ [ 1, 2 ], [ 1, 3 ], [ 2, 3 ] ]
No comments:
Post a Comment