首页 > 解决方案 > Find the first same number in the same index on different for loops

问题描述

I want to find the first same number in the same index on different for loops and print 'Yes' if the number match and 'No' if the number does not match.

const x1 = 2;
const v1 = 1;
// 2 + 1 = 3
const x2 = 1;
const v2 = 2;
// 1 + 2 = 3

// Complete the kangaroo function below.
function kangaroo(x1, v1, x2, v2) {
  let jump1 = 0;
  let jump2 = 0;

  let jumps1 = 0;
  let jumps2 = 0;

  for(let i = x1; i <= 10; i += v1) {
    jumps1 = jump1 + i;
    console.log(jumps1)
  }

  console.log('---------------------> Hold on <--------------')

  for(let i = x2; i <= 10; i += v2) {
    jumps2 = jump2 + i;
    console.log(jumps2)
  }

  if(jumps1 === jumps2) {
    console.log('Yes');
  } else {
    console.log('No');
  }

};

kangaroo(x1, v1, x2, v2);

标签: javascript

解决方案


Add hese variables before the loops:

const loop1Numbers = {};
const loop2Numbers = {};

Add this inside your first loop:

loop1Numbers[i] = jumps1;

Add this inside your second loop:

loop2Numbers[i] = jumps2;

And finally after the loops you can check if "YES" or "NO":

let isThereAnyNumberEqualInSameIndex = false;
Object.keys(loop1Numbers).forEach(key => {
  if (loop1Numbers[key] === loop2Numbers[key]) isThereAnyNumberEqualInSameIndex = true
});

After that - isThereAnyNumberEqualInSameIndex contains true or false as you need


推荐阅读