You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按特定序列匹配比较两个数组的对应元素值

Hey there! Let's break down this problem step by step—first clarifying the requirement, then analyzing the provided JavaScript code to see where it goes wrong, and finally fixing it with better solutions.

Problem Statement

We need to generate two arrays following specific rules, then check if there exists any index i where the elements at that position in both arrays are exactly equal. The array rules are:

  • k1 starts from the value derived from x1 and v1 (per example logic), incrementing by v1 each step until reaching 10000.
  • k2 follows the same logic with x2 and v2.
Example Analysis

Let's walk through the given examples to solidify the requirement:

  • Example 1 (Returns "YES")

    x1=0 v1=3 x2=4 v2=2 k1=[3,6,9,12,15,18] k2=[6,8,10,12,14,16]
    At index 3, both arrays have the value 12 (k1[3] = 12, k2[3] = 12), so we return "YES".

  • Example 2 (Returns "NO")

    x1=0 v1=2 x2=5 v2=3 k1=[2,4,6,8,10,12,14] k2=[5,8,11,14,17,20,23]
    Even though 14 appears in both arrays, it's at index 6 in k1 and index 3 in k2—different positions, so we return "NO".

Validation of the Provided JavaScript Code

First, let's look at the original code:

function car(x1, v1, x2, v2) { 
  let k1 = []; 
  let k2 = []; 
  for (var i = x1; i <= 10000; i+=v1) { 
    k1.push(i) 
  } 
  for (var i = x2; i <= 10000; i+=v2) { 
    k2.push(i) 
  } 
  for (var i = 0; i <= 10000; i++) { 
    if (k1[i] === k2[i]) { 
      return 'YES' 
      break; // This line is unreachable
    } else {
      console.log('NO')
    } 
  } 
}

This code has several critical issues:

  1. Incorrect array generation logic
    The example shows x1=0 v1=3 produces k1=[3,6,9,...], but the original code starts pushing from x1 (0), resulting in k1=[0,3,6,...]. This mismatch makes the entire check invalid right from the start.

  2. Buggy loop termination condition
    The third loop runs up to i <= 10000, but both k1 and k2 will almost certainly be much shorter than 10000 elements. Once i exceeds the length of either array, k1[i] and k2[i] become undefined, and undefined === undefined will evaluate to true—causing the function to incorrectly return "YES" for cases where no valid match exists.

  3. Unreachable code
    The break statement after return 'YES' will never run, since return immediately exits the function. It's redundant and can be removed.

  4. No proper "NO" return
    If no matching index is found, the function will exit without returning anything (it returns undefined instead of "NO"). The console.log('NO') also spams the console with unnecessary output during the loop.

Fixed Solutions

Solution 1: Corrected Array-Based Approach

This fixes the array generation logic and loop conditions to align with the problem requirements:

function car(x1, v1, x2, v2) { 
  let k1 = []; 
  let k2 = []; 
  // Generate arrays matching the example logic: start at x + v, increment by v until <=10000
  for (let i = x1 + v1; i <= 10000; i += v1) { 
    k1.push(i); 
  } 
  for (let i = x2 + v2; i <= 10000; i += v2) { 
    k2.push(i); 
  } 
  // Only loop through valid indices (up to the shorter array's length)
  const maxValidIndex = Math.min(k1.length, k2.length); 
  for (let i = 0; i < maxValidIndex; i++) { 
    if (k1[i] === k2[i]) { 
      return 'YES'; 
    } 
  } 
  // If no matches found after checking all valid indices
  return 'NO'; 
}

Solution 2: Math-Based Approach (More Efficient)

Instead of generating entire arrays, we can use mathematical derivation to directly check if a valid index exists. This avoids memory overhead and runs in constant time:

function car(x1, v1, x2, v2) {
  // Handle edge case: same speed
  if (v1 === v2) {
    // If first positions match, all positions will match; else never
    return (x1 + v1) === (x2 + v2) ? 'YES' : 'NO';
  }

  // Derive the equation: x1 + v1*(i+1) = x2 + v2*(i+1)
  // Rearranged: (v1 - v2)*(i+1) = x2 - x1
  const numerator = x2 - x1;
  const denominator = v1 - v2;

  // Check if the result is a positive integer (since i+1 must be at least 1)
  if (numerator % denominator !== 0) {
    return 'NO';
  }
  const steps = numerator / denominator;
  if (steps <= 0) {
    return 'NO';
  }

  // Verify the calculated position doesn't exceed 10000
  const targetPosition = x1 + v1 * steps;
  if (targetPosition > 10000 || (x2 + v2 * steps) > 10000) {
    return 'NO';
  }

  return 'YES';
}

内容的提问来源于stack exchange,提问作者okky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:39:25