Как остановить бесконечный цикл в for который запускается с некоторыми значениями?

function addWheat(blocks) {

  if (blocks.length > 2 && blocks.length !== 3) {

    let totalNumber = 0;

    for(let i = 0; i < blocks.length; i++){
      for(let z = 0; z < blocks.length; z++){
        if (blocks[i] > blocks[z]) {
          totalNumber += blocks[i] - blocks[z]
        }
        else {
          i = z
        }
      }
    }
      return totalNumber
  }

    if (blocks.length === 3) {
      if (blocks[0] > blocks[1] && blocks[1] < blocks[2]) {
        const firstMinValue = Math.min(...blocks);
        const indexMinValue = blocks.indexOf(firstMinValue);
    
        blocks.splice(indexMinValue, 1);
    
        const secondMinValue = Math.min(...blocks);
        const result = secondMinValue - firstMinValue;
        
        return result
      }
    }
  return 0
}


console.log(addWheat([4, 1, 3])) // 2
console.log(addWheat([2, 1, 5, 2, 7, 4, 10])) // 7
console.log(addWheat([2, 0, 1, 5, 2, 7])) // 6
console.log(addWheat([2, 4, 2]))// 0
console.log(addWheat([7, 4])) // 0
console.log(addWheat([])) // 0

Но если поставить значения, допустим [2, 1, 5, 2, 7, 4, 10, 10] или [15,9,6,10,11,2,5] то программа попадает в infinity loop, что делать?

Я решаю задачу где каждый элемент массива равен одному блоку контейнера, нужно посчитать сколько зерна влезет между блоками, нужно что бы оно не высыпалось: enter image description here

Думал ставить break но не знаю как правильно или делать проверку:

if (levels.length - 1 < levels.length - 2) Но она не работает для всех вариантов когда появляется infinity loop


Ответы (1 шт):

Автор решения: Andrey Semykin

К сожалению, не разобрался в логике твоей программы, ничего не скажу по поводу бесконечного цикла. Но в таком виде все тесты проходит нормально:

function addWheat(blocks) {

  if (blocks.length < 3) return 0;

  let res = 0;
  let maxHight = blocks.reduce((max, b) => Math.max(max, b), 0);

  function calcVolume(left, right){
let hight = Math.min(blocks[left], blocks[right]);
return blocks.filter((b, i) => i>left && i<right).reduce((acc, b) => acc += hight - b, 0);
  }

  let left = 0;
  let rigth = 1;

  do{
while (blocks[left] < blocks [left+1]) left++;
let right = left+1;
let maxRight = right;
while (blocks[left] > blocks[right] && right < blocks.length - 1 && blocks[right] < maxHight){
    right++;
    if (blocks[right] > blocks[maxRight]) maxRight = right;
} 
if(right == blocks.length - 1){
    if(maxRight > left + 1) right = maxRight;
    else return res;
}  
res += calcVolume(left, right);
left = right;

  }while (left < blocks.length - 2)
  
  return res;

}


console.log('2= ', addWheat([4, 1, 3])) // 2
console.log('7= ', addWheat([2, 1, 5, 2, 7, 4, 10])) // 7
console.log('6= ', addWheat([2, 0, 1, 5, 2, 7])) // 6
console.log('0= ', addWheat([2, 4, 2]))// 0
console.log('0= ', addWheat([7, 4])) // 0
console.log('0= ', addWheat([])) // 0
console.log('9= ', addWheat([4,0,3,5,0,4])) 
console.log('3= ', addWheat([4,0,3,2,1,0])) // 0
console.log('0= ', addWheat([3, 2, 1]))

→ Ссылка