Skip to content

Commit 06d08a4

Browse files
committed
Added hard/array_couples
1 parent edaf5f2 commit 06d08a4

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

hard/array_couples.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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;

hard/array_couples.test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const arrayCouples = require('./array_couples');
2+
3+
describe('arrayCouples()', () => {
4+
test('correctly returns string true for matching pairs', () => {
5+
expect(arrayCouples([4, 5, 1, 4, 5, 4, 4, 1])).toBe('yes');
6+
expect(arrayCouples([5, 4, 6, 7, 7, 6, 4, 5])).toBe('yes');
7+
});
8+
9+
test('correctly returns string of unmatched pairs', () => {
10+
expect(arrayCouples([6, 2, 2, 6, 5, 14, 14, 1])).toBe('5,14,14,1');
11+
expect(arrayCouples([2, 1, 1, 2, 3, 3])).toBe('3,3');
12+
});
13+
});

0 commit comments

Comments
 (0)