Nag
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
// PROBLEM 1
// Given two arrays, determine if arrays has elements in common
containsCommonItems = function (arrayA, arrayB) {
for (let i = 0; i < arrayA.length; i++) {
for (let j = 0; j < arrayB.length; j++) {
if (arrayA[i] === arrayB[j]) {
return true;
}
}
}
return false;
}
containsCommonItemsBetter = function (arrayA, arrayB) {
map = {}
for (let i = 0; i < arrayA.length; i++) {
map[arrayA[i]] = true;
}
for (let i = 0; i < arrayB.length; i++) {
if (map[arrayB[i]]) {
return true
}
}
return false
}
containsCommonItemsJSSpecific = function (arrayA, arrayB) {
return arrayA.some( e => arrayB.includes(e));
}
let arrA = ['e', 't', 'a', 'a', 'a', 'f'];
let arrB = ['b', 'v', 't', 'h', 'w'];
let arrC = ['e', 't', 'a', 'a', 'a', 'f'];
let arrD = ['b', 'v', 'k', 'z', 'w'];
let result = containsCommonItems(arrA, arrB)
if (result === true) {
console.log("Test 1: OK");
}
else
{
console.log("Test 1: Failed");
}
result = containsCommonItems(arrC, arrD)
if (result === false) {
console.log("Test 2: OK");
}
else
{
console.log("Test 2: Failed");
}
result = containsCommonItemsBetter(arrA, arrB)
if (result === true) {
console.log("Test 3: OK");
}
else
{
console.log("Test 3: Failed");
}
result = containsCommonItemsBetter(arrC, arrD)
if (result === false) {
console.log("Test 4: OK");
}
else
{
console.log("Test 4: Failed");
}
result = containsCommonItemsJSSpecific(arrA, arrB)
if (result === true) {
console.log("Test 5: OK");
}
else
{
console.log("Test 5: Failed");
}
result = containsCommonItemsBetter(arrC, arrD)
if (result === false) {
console.log("Test 6: OK");
}
else
{
console.log("Test 6: Failed");
}
// PROBLEM 2
// Given an intger array and an integer N, determine if there is pair of elements in the array that add up N
function hasPairWithSum(myArray, total) {
const aSet = new Set();
for (let i = 0; i < myArray.length; i++) {
if (aSet.has(total - myArray[i])) {
return true;
}
aSet.add(myArray[i]);
}
return false;
}
aArray = [6, 4, 3, 2, 1, 7];
if (hasPairWithSum(aArray, 9)) {
console.log("Test 7: OK");
} else {
console.log("Test 7: Failed");
}
if (!hasPairWithSum(aArray, 2)) {
console.log("Test 8: OK");
} else {
console.log("Test 8: Failed");
}
JavaScript
INFO