"Where do I belong" algorithm

"Where do I belong" algorithm
0

#1

Hi Everyone,

I completed this challenge successfully, so I’m not asking for anyone to solve it for me. However, my code seems kind of verbose and inefficient, so I am looking for examples of how others solved it, so I can learn from them.

Here is my code:

function getIndexToIns(arr, num) {
  var diff = 0;
  var minDiff = 0;
  var insPos = 0;
  function sortNumber(a,b) {
    return a - b;
  }
  arr.sort(sortNumber);
  for(var i = 0; i < arr.length; i++){
    diff = num - arr[i];
    if(i === 0 || (diff < minDiff && diff >= 0)){
      minDiff = diff;
      if(arr[i] == num){
        insPos = i;
      }
      else{
        insPos = i + 1; 
      }
    }
  }
  return insPos;
}

#2

Hi what you did is sort out the array and then more or less sorted it again with the num and got the position of the num … other way would be to arr.push(num) … this adds the num to the array … then run your arr.sort(sortNumber) … as now you have all the numbers sorted . then just …
return arr.indexOf(num) …


#4

@P1xt, thanks for this very insightful post. This is exactly the type of input I was hoping to receive. I am trying to become a better programmer in the sense of solving problems more elegantly and efficiently. You’ve done a great job here.


#6

@P1xt Thanks for the advice. I will do my best to put it into practice.


#7

Hi all. I am new to JS. This is my first post. And this is my solution.

 function getIndexToIns(arr, num) {
      // Find my place in this sorted array.

  arr.push(num);
  arr.sort(function(a,b){
    return a-b;
  });
  return arr.indexOf(num);

}

#8

Mine was identical to ddamajas.

Got most of it from reading the documentation.


#9

My solution was quite simple, although it used an additional array method.

function getIndexToIns(arr, num) {
  arr.push(num);
  var sortedArray = arr.sort(function(a,b){return a-b;});
   function indexer(element) {
		return element == num;
   }
return sortedArray.findIndex(indexer);
}

#10

Hi @dpberry552 here is how I solved. I believe it’s an elegant way to approach .

function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.push(num);
arr = arr.sort(function(a,b) {
return a-b;
});

num = arr.indexOf(num);

return num;
}