Unexpected result inside a Nested Loop - javascript

let conditon = false
const test = [2, 0, 3, 4, 5, 6, 7]
for (let i = 0; i < 10; i++) {
for (let j = 0; j < test.length; j++) {
if (0 !== test[j]) {
conditon = true;
break;
}else{
conditon = false;
break;
}
}
console.log(conditon)
}
In this loop it console.log true but it should print false when it finds 0 in an array

You are continuously setting condition to true, because e.g. 0 !== 2 evaluates to true. This is the case for every element, except 0. 0 !== 0 which evaluates to false. You need to put an else check in there and set condition to false, then break out so that it doesn't continue and override your value again by setting condition back to true for the next iterations.
let condition = false;
const test = [2, 0, 3, 4, 5, 6, 7]
for (let i = 0; i < 10; i++) {
for (let j = 0; j < test.length; j++) {
if (0 !== test[j]) {
conditon = true;
} else {
conditon = false;
break;
}
}
console.log(conditon)
// Comment this part out if you want it to continue looping without immediately stopping.
// Otherwise the loop ends once it hits 0.
if(!condition)
break;
}
This is not the best way to do this, mind you... I'm just providing you an example on why your code works the way it does.

Here's a simplified version, which you can examine to see how it works, and which you can use as a template for a more complicated version if desired.
let condition;
const nums = [2, 0, 3, 4, 5, 6, 7];
for(let i = 0; i < 2; i++){
for (let num of nums) {
condition = (num !== 0);
console.log(num, condition);
}
console.log("\n--end of outer loop--\n\n");
}
Edit:
From your comment, I gleaned that after each trip through the outer loop, you want to report if any value in the array was zero. If this is what you're looking for, you'd do something like this:
const nums = [2, 0, 3, 4, 5, 6, 7];
for(let i = 0; i < 2; i++){
let noZerosFound = true;
console.log("checking: " + nums);
for (let num of nums) {
if(num === 0){
noZerosFound = false;
// Can include a `break` statement here for better performance
}
}
console.log("noZerosFound: " + noZerosFound);
console.log("\n");
}
And JavaScript arrays also provide some useful built-in methods for this kind of situation. So if you want, you could simply do:
const nums = [2, 0, 3, 4, 5, 6, 7];
for(let i = 0; i < 2; i++){
console.log("checking: " + nums);
// Applies the function `(num) => num !== 0` to each element of `nums`.
// If the result is true for every element, returns true.
// Otherwise, returns false.
const noZerosFound = nums.every( (num) => num !== 0);
console.log("noZerosFound: " + noZerosFound);
console.log("\n");
}
See the .every method and arrow functions on MDN for further explanation.

There are already good answers here. Let me introduce this way as an extra answer.
const test = [2, 0, 3, 4, 5, 6, 7];
console.log(!test.includes(0));
const test2 = [2, 1, 3, 4, 5, 6, 7];
console.log(!test2.includes(0));
.includes()
array.includes(<value>)
.includes() returns true if a given value is in an array, false if not.
!test.includes(0) returns true if 0 is NOT in test. false if 0 IS in test.

Related

JS for loop in for loop, problem with scope I guess

The input is an array ints [11, 2, 7, 8, 4, 6] and and integer s 10. The function is to output an array with a pair of two numbers from ints which first form a sum of 10. So here the output should be [2, 8], because 2 + 8 = 10. Why does it output empty array? The arrResults was updated in the nested for loop, so why doesn't it show up like that after the final return statement?
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (i = 0; i < ints.length; i++) {
for (j = 0; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults !== []) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
Beside the wrong comparing of an array with another array (without having the same object reference)
a = []
b = []
a === b // false
// other example
a = []
b = a
a === b // true
for checking the length,
a = []
a.length // 0
and by using a nearly quadratic time complexity of n², even with looping
i = 0; i < array.length - 1
j = i + 1; j < array.length
which is more then the half of n², but strill quadratic,
you could take a single loop with an object fo already seen values.
This approach finds the first pair of the array for a certain sum.
function sumPairs(ints, s) {
const needed = {};
for (const value of ints) {
if (needed[value]) return [s - value, value];
needed[s - value] = true;
}
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
Your code fails because you are checking to see if the array is empty. The problem is that check is never going to be false, so it exits on the first iteration.
console.log([]===[]);
console.log([]!==[]);
So code with changes to improve performance and to exit out
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (let i = 0; i < ints.length; i++) {
for (let j = i + 1; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults.length) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
There is no need to break out twice, just return the array
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (let i = 0; i < ints.length; i++) {
for (let j = i + 1; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
return [ints[i], ints[j]];
}
}
}
return null;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));

Given an array with numbers from 1 to a.length, how do i find the first duplicate number for which the second occurrence has the minimal index?

I'm trying the following code but it cant seem to work.
These are my tests:
input = 2,1,3,5,3,2expected output = 3;
input = 2,4,3,5,1expected output = -1
input = 2,4,3,5,1,7
Here is the code
function FirstDuplicate(array) {
var a = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstDuplicate = "";
for (var i = 0; i < a.length; i++) {
for (var b = i + 1; b < a.length; b++) {
if (a[i] === a[b])
firstDuplicate = a.indexOf(a[i]);
break;
}
}
return firstDuplicate;
}
You can create a an empty Set and keep adding the elements which are already passed to that Set. If a number comes which is already in Set then return it
function FirstDuplicate(array) {
let passed = new Set();
for(let x of array){
if(passed.has(x)) return x;
passed.add(x);
}
return -1;
}
console.log(FirstDuplicate([2,1,3,5,3,2]))
console.log(FirstDuplicate([2,4,3,5,1]))
console.log(FirstDuplicate([2,4,3,5,1,7]))
You could take an object with the value as key and check if the value has been seen before or not.
function getFirstDuplicate(array) {
var seen = Object.create(null),
i = 0,
value;
for (i = 0; i < array.length; i++) {
value = array[i];
if (seen[value]) return value;
seen[value] = true;
}
return -1;
}
console.log(getFirstDuplicate([1, 7, 3, 5, 4, 2, 9, 3]));
console.log(getFirstDuplicate([1, 7, 3, 5, 4, 2, 9, 6]));
We just push stuff into an object while we iterate over the array. On first occurrence we set it to true, if we find a true we know we found the first duplicate.
function f (arr) {
let tmp = {};
return (arr.find(v => (tmp[v] || (tmp[v] = true) && false)) || -1)
}
console.log(f([2,1,3,5,3,2]))
console.log(f([2,4,3,5,1]))
console.log(f([2,4,3,5,1,7]))

JavaScript: Writing this solution using higher order functions

I worked on a problem where you are given an array of numbers and a target sum, and it's your job to find a pair of numbers that sum up to the target number. Here was my solution using simple nested for loops:
function findPairForSum(integers, target) {
var output = [];
for (var i = 0; i < integers.length; i++) {
for (var j = 0; j < integers.length; j++) {
if (i !== j && integers[i] + integers[j] === target) {
output.push(integers[i], integers[j]);
return output;
}
}
}
return 'not possible';
}
findPairForSum([3, 34, 4, 12, 5, 2], 9); // --> [4, 5]
My question is, is there a cleaner way to write this solution using higher order functions (perhaps forEach?)
Here was my attempt to use forEach:
function findPairForSum(integers, target) {
var output = [];
integers.forEach(function(firstNum) {
integers.forEach(function(secondNum) {
if (firstNum + secondNum === target) {
output.push(firstNum, secondNum);
}
})
})
if (output === []) {
return 'not possible';
}
return output;
}
findPairForSum([3, 34, 4, 12, 5, 2], 9); // --> [ 4, 5, 5, 4 ]
I tried putting a return after the two pushes, but it did not return anything. So instead, I put the return at the very end.
Why won't it return after the initial two pushes? I want it to stop right there, and only push the two numbers. Instead, by putting the return at the end, it pushed 4 numbers. It should be [4,5] but I got something like [4,5,5,4].
Any advice and help would be much appreciated!
Assume we have the following set of numbers, and we must find a subset of 2 numbers whose sum is 9:
Numbers: 4, 5, 6
Your current code iterates both with i and j from 0 to length. This means that the following iterations match the condition:
Indices: 0, 1, 2
Numbers: 4, 5, 6 // (i) (j)
---------------- // ↓ ↓
i j // Numbers[0] + Numbers[1] === 9
j i // Numbers[1] + Numbers[0] === 9
As you can see, the numbers 4 and 5 are matched twice, in 2 iterations:
i === 0 && j === 1
i === 1 && j === 0
You can avoid this by making sure one simple condition is met:
j must at all times be greater than i
This condition can be met met by initializing j with i + 1 in the inner for loop:
for (var i = 0; i < integers.length; i++) {
for (var j = i + 1; j < integers.length; j++) {
// ...
}
}
This way, j can never be 0 when i is 1, because the inner for-loop will run to completion before i is ever incremented once more. Once that happens, a brand new inner for-loop is created, in which j is again set to i + 1. The following diagram is the result:
Indices: 0, 1, 2
Numbers: 4, 5, 6
----------------
i j
X i // ← j can never be 0 if (i === 1),
// so the same set is never evaluated twice.
In other words, only the following combinations for i and j are checked at most:
Indices: 0, 1, 2
----------------
i j
i j
i j
is there a cleaner way to write this solution using higher order functions (perhaps forEach?)
A for loop is actually a fine solution for your use-case. They allow you to break early - after the first time you find a valid pair of numbers. forEach or other array iterator functions on the other hand will always continue until all set indices are visited.
You are actually breaking early in your first example with the statement return output;
When you use forEach on a set of numbers with multiple valid sets, you'll always get back all numbers involved:
Indices: 0, 1, 2, 3
Numbers: 4, 5, 6, 3 // (i) (j)
------------------- // ↓ ↓
i j // Numbers[0] + Numbers[1] === 4 + 5 === 9
i j // Numbers[2] + Numbers[3] === 6 + 3 === 9
forEach, map, reduce and the like do not allow you to break early. The following snippet demonstrates this issue of the diagram above:
function findPairForSum(integers, target) {
var output = [];
integers.forEach(function(firstNum, i) {
// slice(i + 1) has the same effect as for (var j = i + 1; ...)
integers.slice(i + 1).forEach(function(secondNum, j) {
if (firstNum + secondNum === target) {
// There is no way here to stop the iteration of either
// forEach call... T_T
output.push(firstNum, secondNum);
}
});
})
if (output.length) {
return output;
}
return 'not possible';
}
console.log(findPairForSum([4, 5, 6, 3], 9)); // --> [4, 5, 6, 3]
This is why I highly recommend sticking with the for loops for this specific use case. With for loop you can simply return as you already did as soon as you encounter a valid set of numbers:
function findPairForSum(integers, target) {
for (var i = 0; i < integers.length; i++) {
for (var j = i + 1; j < integers.length; j++) {
if (integers[i] + integers[j] === target) {
return [integers[i], integers[j]];
}
}
}
return 'not possible';
}
console.log(findPairForSum([4, 5, 6, 3], 9)); // --> [4, 5]
This could be your solution:
function findPairForSum(arr, sum) {
var pairs = [];
arr.forEach(n1 => {
var n2 = arr.find(n2 => n1 + n2 == sum)
if (n2) pairs.push([n1, n2]);
});
return pairs;
}
var sums = findPairForSum([3, 34, 4, 12, 6, 2], 9);
console.log(sums)
The problem is, you iterate from the start of the array for the inner loop. You could use a copy which starts at the index of the outer loop plus one and exit early on a found value.
But this does not solves the problem with multiple pairs. The result is simply wrong.
function findPairForSum(integers, target) {
var output = [];
integers.forEach(function(firstNum, i) {
integers.slice(i + 1).some(function(secondNum) {
if (firstNum + secondNum === target) {
output.push(firstNum, secondNum);
return true;
}
});
});
return output.length && output || 'not possible';
}
// console.log(findPairForSum([3, 34, 4, 12, 5, 2], 9));
console.log(findPairForSum([3, 34, 4, 4, 12, 5, 2, 4, 5], 9));
For a solution, you need to remember which pairs are used. This approach works with only one loop and a hash table for counting missing values.
If a pair is found, the counter is decremented and the two values are pushed to the result set.
function findPairForSum(integers, target) {
var hash = Object.create(null),
output = [];
integers.forEach(function(value) {
if (hash[value]) {
output.push(target - value, value);
hash[value]--;
return;
}
hash[target - value] = (hash[target - value] || 0) + 1;
});
return output.length && output || 'not possible';
}
console.log(findPairForSum([3, 34, 4, 4, 12, 5, 2, 4, 5], 9));
This is expected, since you didn't compare the indexes.
This inner array should only loop through the indexes which larger than the outer index.
You can achieve this by using the 2nd parameter, index, in forEach's callback function:
const ints = [3, 34, 4, 12, 5, 6, 2];
function findPairForSum(integers, target) {
let result;
integers.forEach((val1, idx1) => {
integers.forEach((val2, idx2) => {
if (idx1 < idx2 && val1 + val2 === target) {
result = [val1, val2];
}
})
})
return result;
}
console.log(findPairForSum(ints, 9));
Use can reduce your array into another which has sum equals target value:
const ints = [3, 34, 4, 12, 6, 2];
const value = 9;
const resp = ints.reduce((acc, ele, idx, self) => {
let found = self.find(x => x + ele == value)
return found ? [found, ele] : acc;
}, []);
console.log(resp); // [3, 6]
You can use Array.prototype.some which will stop execution as soon as the condition becomes true. See below code.
function findPairForSum(arr, sum) {
var pairs = [];
arr.some(n1 => {
var n2 = arr.find(n2 => n1 + n2 == sum)
if (n2) {
pairs.push(n1, n2); return true;
};
return false;
});
return pairs.length > 0 ? pairs : "not possible";
}
console.log(findPairForSum([3, 34, 4, 12, 7, 2], 9));

Validate if the last value of array is greater than previous value

I have an array with value, [0,3,4,6,0], How do I validate if the before values is less than the after values?
var array = [0,3,4,6,0];
for(var i = 0; i < array.length; i++){
//if the value of 0 >,3 >,4, > 6
//return false;
}
I need to require the user to enter an ordered sequence of numbers like 5, 4, 3, 2, 1. Hence, I need to validate if the enter is not in an ordered sequence.
A possible solution in ES5 using Array#every
function customValidate(array) {
var length = array.length;
return array.every(function(value, index) {
var nextIndex = index + 1;
return nextIndex < length ? value <= array[nextIndex] : true;
});
}
console.log(customValidate([1, 2, 3, 4, 5]));
console.log(customValidate([5, 4, 3, 2, 1]));
console.log(customValidate([0, 0, 0, 4, 5]));
console.log(customValidate([0, 0, 0, 2, 1]));
Iterate all the array, expect true until you reach a false, where you can break out of the loop.
function ordered(array) {
var isOk = true; // Set to true initially
for (var i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
// If something doesn't match, we're done, the list isn't in order
isOk = false;
break;
}
}
document.write(isOk + "<br />");
}
ordered([]);
ordered([0, 0, 0, 1]);
ordered([1, 0]);
ordered([0, 0, 0, 1, 3, 4, 5]);
ordered([5, 0, 4, 1, 3, 4]);
function inOrder(array){
for(var i = 0; i < array.length - 1; i++){
if((array[i] < array[i+1]))
return false;
}
return true;
}
What you can do is to loop the array and compare adjacent elements like this:
var isOk = false;
for (var i = 0; i < array.length - 1; i++) {
if (array[i] > array[i+1]) {
isOk = true;
break;
}
}
Thus flag isOk will ensure that the whole array is sorted in descending order.

Javascript: How to find first duplicate value and return its index?

I have to find first duplicate value in array and then return its index in variable firstIndex. This has to be done with for loop which should stop after having found first duplicate. I know this is probably pretty simple but I got stuck. So far I have this but it doesn't seem to be working:
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
for (var a = 0; a < numbers4.length; a++) {
for (var b = a+1; b < numbers4.length; b++) {
if (numbers4[a] === numbers4[b])
firstIndex = numbers4.indexOf(numbers4[a]);
break;
}
}
console.log(firstIndex);
Console prints out 1 which is fine because 2 is first duplicate, but when I change numbers in array, the loop doesn't work. Can you advise what can be changed here?
Thanks in advance!
If I correctly understand your question, that's should help you...
Basically, you need for a double iteration.
const firstDupeIndex = list => list.findIndex(
(item, index) => list.lastIndexOf(item) !== index
);
console.log(
"First Dupe at index:",
firstDupeIndex([5, 2, 3, 4, 4, 6, 7, 1, 2, 3])
);
Thee above implementation comes with the drawback of being O(n2), due to nesting the lastIndexOf within the findIndex function.
A better solution would be to index your occurrences by building a dictionary, therefore keeping time complexity to just O(n) in the worst case. Probably a little bit less neat, but surely more efficient with big inputs.
const firstDupeIndex = (list) => {
const dict = {};
for (const [index, value] of list.entries()) {
if (dict.hasOwnProperty(value)) {
return dict[value];
}
dict[value] = index;
}
return -1;
};
console.log(
"First Dupe at index:",
firstDupeIndex(['a', 'b', 'c', 'd', 'e', 'b', 'z', 't', 'c'])
);
Change your code with the following
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
var isMatch=false;
for (var a = 0; a < numbers4.length; a++) {
for (var b = a+1; b < numbers4.length; b++) {
if (numbers4[a] === numbers4[b]){
firstIndex = numbers4.indexOf(numbers4[a]);
isMatch=true;
break;
}
}
if (isMatch) {break;}
}
console.log(firstIndex);
I would use an object remembering the values already found... Something like that should work ;)
var numbers4 = [5, 2, 3, 4, 4, 6, 7, 1, 2, 3];
function findFirstDuplicateIndex(arr){
var found = {};
for (var a = 0, aa = arr.length; a < aa ; a++) {
if (found[arr[a]])
return found[arr[a]];
found[numbers4[a]] = a
}
}
console.log(findFirstDuplicateIndex(numbers4));
It's quite fast because you just loop one time through the array. The rest of the time you just access an object property or you set the object property... Let me know if you have questions ;)
However maybe there something faster... It's just an idea ^^
PS: It also works with words, not just numbers
Your break; terminates b loop, because if() is not using parenthesis {}.
Additionally, firstIndex should be simply set to either a or b depending on whether you need to return the duplicate's first occurance or first repetition.
It should be:
if (numbers4[a] === numbers4[b])
{
firstIndex = a;
break;
}
Your problem is - you have two loops and only one break, you need to break out of both.
Why not simply return the index as soon as values match?
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
function getDuplicate(numbers4)
{
for (var a = 0; a < numbers4.length; a++) {
for (var b = a+1; b < numbers4.length; b++) {
if (numbers4[a] === numbers4[b]){
return a;
}
}
}
}
console.log(getDuplicate(numbers4 ));
However, you can optimize your code further by keeping a map
function getDuplicate( numbers )
{
var map = {};
for (var a = 0; a < numbers.length; a++)
{
if( map[ numbers[ a ] ] )
{
return a;
}
map[ numbers[ a ] ] = true;
}
return -1;
}
You can check if indexOf() is not equal to lastIndexOf() and return value and break loop
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
for (var i = 0; i < numbers4.length; i++) {
if (numbers4.indexOf(numbers4[i]) != numbers4.lastIndexOf(numbers4[i])) {
firstIndex = i;
break;
}
}
console.log(firstIndex)
You don't even need nested for loops.
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
for (var a = 1; a < numbers4.length; a++) { //start from second elem since first is never a duplicate
if (numbers4.lastIndexOf(numbers4[a])> a) {
firstIndex = a;
break;
}
}
console.log(firstIndex); //1
All you have to do during iterating is to check if current value exists somewhere further in array. That is done by checking last index of this value's occurrence using lastIndexOf().
var numbers = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex;
var len = numbers.length;
for (var i = 0; i < len; i++) {
var tmpArray = numbers.slice(i + 1, len);
var index = tmpArray.indexOf(numbers[i]);
if (index !== -1) {
firstIndex = index + i + 1;
break;
}
}
console.log(firstIndex);
Update:
Actually your logic is right, but you missed braces for if condition and also if the condition satisfies then it means firstIndex is the same as a
This is your code with braces,
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
for (var a = 0; a < numbers4.length; a++) {
for (var b = a + 1; b < numbers4.length; b++) {
if (numbers4[a] === numbers4[b]) {
firstIndex = a
break;
}
}
}
console.log(firstIndex);
The question states the first dupe in the array has to be found along with it's index. So I return an object where the i property is the index and the e property is the first duplicate element itself. One way of performing this task would be
var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3],
headDupe = (a,r={}) => (r.e = a.find((n,i) => (r.i = a.indexOf(n), r.i < i)),r);
console.log(headDupe(numbers4));

Categories

Resources