In the normal way what I do ? WARNING (SOLUTION)!

In the normal way what I do ? WARNING (SOLUTION)!
0.0 0

#1

Hi, campers. I am about to finish solving the basic algorithm scripts. But I wonder something. Sometimes, actually most of the time, I have been complicating the algorithms myself. For example, for the “Where do I belong” algorithm, my solutiıon like this and this solution work without problem:

code

After my solution, I looked at the other solutions to see other’s way. But they are so simple. For example like these :

function getIndexToIns(arr, num) {
 
  var times = arr.length; 
  var count = 0; 
  for (i=0;i<times;i++){
    if(num>arr[i]){count++;} }
    return count; 
}

or

function getIndexToIns(arr, num) {

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

  var i = 0;
  while (num > arr[i]) {
  i++;
  }

  return i;
}

Do I want to ask something that am I wrong? Is my solution too long or complicated? Is this normal? Could you give me any advice about my code and my way? By the way, sorry about my English :slight_smile:


#2

Here are some suggestions/thoughts on your code:

  • On line 9 of your code, you don’t need to return the arr.indexOf(arr[i]); because you already know the index is i, so return i.
  • Change your first else into else if(arr[i] < num), and have the final else come after the else if so that it looks like:
if (num == arr[i]) {
  ...
} else if (arr[i] < num) {
  ...
} else {
  return i; // instead of arr.indexOf(arr[i])
}
  • On line 11 you’re checking if arr[i] is less than num. Then once you’ve established that it is less than num, you do the same check again and check if i equals arr.length - 1. You don’t need to check arr[i] < num within the if block where you just checked it.
    • I did this kind of thing a lot when I first started programming.
    • When you’re writing the code inside an if block, try to say to yourself something like (ok, I know that arr[i] is definitely less thannum` on this line"
  • Make some variables that help explain some of the code. Instead of referring to arr.length - 1, make a variable to store that number.
return lastIndex;

is a lot easier to understand at a glance than

return arr.length - 1;

Don’t go overboard with making a variable for every little thing though.

Sometimes short code isn’t very readable. Do your best to write readable, easy to maintain code and don’t worry about how long it is.

Your English is great by the way.


#3

Thank you so much for your obvious answer and advice :slight_smile: