Javascript Array subsets()

Description

Javascript Array subsets()


Array.prototype.subsets = function () {
  if (this.length === 1) {
    return [[], this];
  }// w w  w. j  a v a  2s . co  m
  let resultArr = [];
  const lastElement = this[this.length - 1];

  let subs = this.slice(0, -1).subsets();
  subs.forEach((el) => {
    // console.log(el);

    resultArr.push(el);
    // console.log(resultArr.push(el));
    resultArr.push(el.concat(lastElement));
    // console.log(resultArr.push(el.concat(lastElement)));
  });
  // console.log(resultArr);
  return resultArr;
};

console.log([1, 2, 3].subsets());

Javascript Array subsets()

Array.prototype.subsets = function () {
  var subs = [[]];

  this.forEach(function(el){
    subs.forEach(function(sub){
      subs.push(sub.concat(el));/*from   w w w  .j  av  a2  s .c o  m*/
    })
  });

  return subs;
};


var a = [1,2,3]

a.subsets(); // [[],[1],[2],[1,2]]

Array.prototype.bSearch = function (target) {

  if (this.length < 1){
    return false;
  }

  var middle = Math.floor(this.length/2) + 1;
  var mid = this[middle];
  var left = this.slice(0,middle);
  var right = this.slice(middle);

  if (mid === target){
    return true;
  }else if (mid > target) {
    return left.bSearch(target);
  }else {
    return right.bSearch(target);
  }

};

var a = [1,2,3,4,5,6,7]

a.bSearch(1);
a.bSearch(7);
a.bSearch(3);
a.bSearch(8);

Javascript Array subsets()

Array.prototype.subsets = function () {
  if (this.length === 0) {
    return this;/*  ww w .  j  av  a 2s. co m*/
  }
  var subs = [];

  for (var i = 0; i < this.length; i++) {
    subs.push(this);
    new_arr = this.slice();
    // console.log(this);
    new_arr.splice(i,1);
    // console.log(new_arr);
    // console.log(new_arr);
    subs.push(new_arr)
    // subs.concat(new_arr.subsets())
  }
  return subs.myUniq();
};
a = [1,2,3]
console.log(a.subsets());



PreviousNext

Related