I need help with this problem. I feel like prior to the Basic Algorithm Scripting section, freecodecamp held my hand with detailed explanations to problems and examples. Now that they stopped doing that, it feels like I did a bad job of retaining all of this new information. Outside of HMTL, CSS, and writing the start of a for loop…I basically feel lost. This is all I have for this problem:
function getIndexToIns(arr, num) {
const array1 = [40, 60, 50];
array1.sort();
console.log(getIndexToIns([40, 60], 50));
I’m trying my best to not just look up the answers.
Can you explain how you would do this entirely by hand, with zero code, if I gave you a list of unsorted numbers written down on a piece of paper and asked you where a new number would go in the list if the list was sorted?
With zero code, if you asked me where a number would go if the list were sorted, I would tell you 50 needs to go in the middle of 40 and 60. I would tell you that is the second spot, but of course in an array the 1st spot is actually 0 so we would be placing 50 in the 1st spot.
So my guess is that I need to get the numbers in the correct order, then return the value of the spot the number outside of the array ends up. I just don’t know how to go about doing this.
But how do you know that (there’s a purpose, I promise)
How would you tell a elementary school kid that knows their numbers what to do. Write down a list of steps for them to follow. Remember to be specific, because this elementary school kid hasn’t done this before.
Assuming the kid knows his or her numbers, I would tell them that the array needs to start with the smallest number and end with the largest number. And therefore, that is how you know 50 goes in the middle, right?
If you tell the computer that the beginning of the array is spot 0. Then you should be able to ask the computer what spot is 8 in…then it will spit out the number 3. In this case, the number outside of the array is num…so you would have to write something that finds what spot num is in…inside the array
Step 1: If index (i) equals 0 then it must equal 2 and not 8 (because 2 < 8)
Step 2: If index (i) equals 1 then it must equal 5 and not 8 (because 5 < 8)
Step 3: If index (i) equals 2 then it must equal 7 and not 8 (because 7 < 8)
Step 4: If index (i) equals 4 then it must equal 10 and not 8 (because 10 > 8)
Therefore since the array is 0-4, 8 must be in spot (i) 3.
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i += 1) {
if (arr[i] <= num) {
return i;
}
return arr.length;
}
}
Instead of doing multiple and using specific numbers I changed it to only do one, but the return arr.length is giving me 0 when it should be 1
I also looked up how to properly use the sort() method
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i += 1) {
if (arr[i] > num) {
return i;
}
return arr.length;
}
}