如何按特定序列匹配比较两个数组的对应元素值
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.
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:
k1starts from the value derived fromx1andv1(per example logic), incrementing byv1each step until reaching 10000.k2follows the same logic withx2andv2.
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 ink1and index 3 ink2—different positions, so we return "NO".
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:
Incorrect array generation logic
The example showsx1=0 v1=3producesk1=[3,6,9,...], but the original code starts pushing fromx1(0), resulting ink1=[0,3,6,...]. This mismatch makes the entire check invalid right from the start.Buggy loop termination condition
The third loop runs up toi <= 10000, but bothk1andk2will almost certainly be much shorter than 10000 elements. Onceiexceeds the length of either array,k1[i]andk2[i]becomeundefined, andundefined === undefinedwill evaluate totrue—causing the function to incorrectly return "YES" for cases where no valid match exists.Unreachable code
Thebreakstatement afterreturn 'YES'will never run, sincereturnimmediately exits the function. It's redundant and can be removed.No proper "NO" return
If no matching index is found, the function will exit without returning anything (it returnsundefinedinstead of "NO"). Theconsole.log('NO')also spams the console with unnecessary output during the loop.
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

