brigysl brigysl - 12 days ago 5
Javascript Question

Need to Optimize the function

I'm working on this function that has to return all possible values of adding

a
and
b
n
times for example if
n = 1
then possible values would be
a + a
a + b
and
b + b
. function below works but it's too slow and I want to optimize it. Any suggestions? Thanks a lot!



function processData(n, a, b){
var ans = [0];
for(var i = 0; i < n; i++){
var temp = [];
for(var j = 0; j < ans.length; j++){
var aa = ans[j] + a;
if(temp.includes(aa) === false){
temp.push(aa);
}
var bb = ans[j] + b;
if(temp.includes(bb) === false){
temp.push(bb);
}
}
ans = temp;
}
ans.sort(function(a, b){return a - b});
return ans;
}




Answer
function processData(n, a, b) {
  var ans = [];
  if (a == b) {
    for (var i=0; i<n+1; i++) {
      ans.push(a * n);
    }
    return ans;
  } else if (a > b) {
    var temp = a;
    a = b;
    b = temp;
  }
  var diff = b - a;
  for (var i=0; i<n+1; i++) {
      ans.push(a * n + diff * i);
  }
  return ans;
}

Okay, this is by far the most efficient solution. I've just tested it on fiddle.

All other three solutions greatly outperform yours. Mine is better than @abc123's because there's no need for sorting and better than @georg's because there's no need for using set or sorting.

Comments