|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function arrayCouples(arr) take the |
| 3 | + * arr parameter being passed which will be an array of an even number of |
| 4 | + * positive integers, and determine if each pair of integers, [k, k+1], [k+2, |
| 5 | + * k+3], etc. in the array has a corresponding reversed pair somewhere else in |
| 6 | + * the array. For example: if arr is [4, 5, 1, 4, 5, 4, 4, 1] then your program |
| 7 | + * should output the string yes because the first pair 4, 5 has the reversed |
| 8 | + * pair 5, 4 in the array, and the next pair, 1, 4 has the reversed pair 4, 1 in |
| 9 | + * the array as well. But if the array doesn't contain all pairs with their |
| 10 | + * reversed pairs, then your program should output a string of the integer pairs |
| 11 | + * that are incorrect, in the order that they appear in the array. |
| 12 | + * |
| 13 | + * For example: if arr is [6, 2, 2, 6, 5, 14, 14, 1] then your program should |
| 14 | + * output the string 5,14,14,1 with only a comma separating the integers. |
| 15 | + * @param {array} arr |
| 16 | + * @return {string} |
| 17 | + */ |
| 18 | +function arrayCouples(arr) { |
| 19 | + const unmatchedPairs = []; |
| 20 | + for (let i = 0; i < arr.length; i += 2) { |
| 21 | + let left = arr[i]; |
| 22 | + let right = arr[i + 1]; |
| 23 | + if (!pairInArray(arr, [right, left], i)) { |
| 24 | + unmatchedPairs.push([left, right]); |
| 25 | + } |
| 26 | + } |
| 27 | + return unmatchedPairs.length === 0 ? 'yes' : unmatchedPairs.join(','); |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Iterates over array of numbers by index delta of 2 and checks for a pair of |
| 32 | + * numbers |
| 33 | + * @param {array} arr array of numbers |
| 34 | + * @param {array} pair array of length 2, a pair of numbers |
| 35 | + * @param {number} excludeIndex an even numbered index to skip |
| 36 | + * @return {boolean} |
| 37 | + */ |
| 38 | +function pairInArray(arr, pair, excludeIndex) { |
| 39 | + let [left, right] = pair; |
| 40 | + for (let i = 0; i < arr.length; i += 2) { |
| 41 | + if (excludeIndex !== i && arr[i] === left && arr[i + 1] === right) { |
| 42 | + return true; |
| 43 | + } |
| 44 | + } |
| 45 | + return false; |
| 46 | +} |
| 47 | + |
| 48 | +module.exports = arrayCouples; |
0 commit comments