6

I need help to optimize a function

 2 years ago
source link: https://www.codesd.com/item/i-need-help-to-optimize-a-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

I need help to optimize a function

advertisements

Basically I want to generate a an angle (0 - 360 degrees) that isn't within a specified range of a number of other angles. I already made this function to check two angles:

function check(angle1, angle2, range) {
    var diff = angle1 - angle2;

    if(Math.abs(diff % 360) <= range || (360-Math.abs(diff % 360)) <= range) {
        return true;
    } else {
        return false;
    }
}

Simple enough, but I need to check a random angle against all other angles, proceed if it passes, generate a new angle and recheck if it fails, and recognise when it's not possible for any new angle to pass.

I think this would work:

var others = [array of objects];

...

for(var i = 0; i < 360; i++) {
    var pass = true;
    for(var n = 0; n < others.length; n++) {
        if(check(i, others[n].angle, 5)) {
            pass = false;
            break;
        }
    }
    if(pass) return i;
}

return false;

However that is a lot of looping and I would much prefer a random angle rather than incrementing. Is there a faster and better way to do this? Thanks.

Edit: decided to do something like this, got the idea from @TheBronx's answer.

var angles = [];

var range = 5;

function alterAngle(a, n) {
  var angle = a + n;
  if(angle < 0) angle = 360 + angle;
  if(angle > 360) angle = angle - 360;
  return angle;
}

// in the function

var angle = Math.floor(Math.random() * 360);

if(angles.indexOf(angle) == -1) {
  for(var i = -range; i <= range; i++)
    angles.push(alterAngle(angle, i));
}


Idea. Imagine your angles are cards in a deck. Once you generate a random angle, you remove that angle from the deck, and also the angles within your range. When you have to generate a new angle, instead of generating a random between 0..360 you just have to "pick a card". This will always work, unless you don't have more "cards" available.

The problem is, do you have a lot of cards? Do you have enough time to initialize the "cards" at start?

Just an idea... Don't know if it is good or not but seems promising.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK