Hi fam happy Valentine's. I'm not looking for a code solution but some insights about how could I go about iterating over an array let's call it array = [1, 1, 1], and not moving to the next element in the array until a condition is fulfilled. For example I want to start at index 0 and only go to the next index (1) after the value of such index is (modified/changed) to be greater than the value of the index before it. At 0 index we have the value 1, I want before moving to index 1 to change the value of index 1 to be greater then the value of index 0. Something like this if we have array = [1, 1, 1] I want to iterate over the array, start at 0 index. Compare if the value of 0 index is greater or equal than the value of index 1 (the next index) If so than add 1 to the value of index 1 until that value is greater than the value of index 0. First iteration we get array = [1, 2, 1]. Next iteration we get array = [1, 2, 3].
At this point I have tried to iterate over the array with a for loop grab each element, compare and add 1 to the element but when I get to the last element it does not add anything since I am at the end of the array and there is no item to loop over. I get array = [1, 2, 2] Please help fam. This is what I have so far.
// array
const array = [1, 1, 1]
// iterating over array
for (let i = 0; i < array.length; i++) {
// compare
if (array[i] >= array[i + 1]) {
// increase next number by 1
array[i + 1] += 1
}
}
You could start from index 1, because you can not change the value at index 0 because of the missing previous value.
Inside the loop increment the value until it is greater than the value at the last index.
const array = [1, 1, 1]
for (let i = 1; i < array.length; i++) {
while (array[i] <= array[i - 1]) array[i]++;
}
console.log(array);
If you don't want to iterate for the increment, you could update the value directly.
const array = [1.2, 1, 1]
for (let i = 1; i < array.length; i++) {
if (array[i] <= array[i - 1]) array[i] = Math.floor(array[i - 1] + 1);
}
console.log(array);
Happy Valentines!
Let's look at what may be causing your array to return [1,2,2]. Good practice (And a bit tedious) is to follow along your inputs and see item by item how your array gets manipulated.
You may have noticed the undesired behaviour happens on the second pass. It's because you're adding 1 to the value and not incrementing based on the index you're on.
Now.. lets get to fixing!
If we assume your input is always [1,1,1] (ASSUMPTIONS MATTER :) ) you can simply change array.
array[i + 1] += 1 to array[i+1] += array[i]
If you're looking for a more comprehensive approach where you can take any array input, sort and display an incrementing array -- that's a little further ahead! Focus on the fundamentals :)