Stuck in infinite loop when use while with continue - javascript

I wrote a code to loop through an array and when I used while and the continue statement inside it I got stuck in infinite loop:
function loop(){
var x = [1,2,3,4,5,6,7,8]
var i = 0;
while ( i < x.length){
if (x[i] % 2 == 0){
continue;
}
i++
}
console.log(x[i])
}
loop()
I tried to add the i++ outside the loop and inside it I got the same result.
The expected result is 1,3,5,....etc the actual result is infinite loop.

The issue is that i should increment whether or not the condition is true or not, otherwise it'll continue to test the same value over and over again indefinitely.
function loop(){
const x = [1,2,3,4,5,6,7,8]
for(let i = 0; i < x.length; i++){
if (x[i] % 2 == 0){
continue;
}
console.log(x[i])
}
}
loop()
Modern JS:
function loop(){
const x = [1,2,3,4,5,6,7,8]
return x.filter(n=>n % 2 !== 0);
}
const res = loop();
console.log(res);

continue goes immediately to the next iteration of the loop, skipping the rest of the loop body. So it skips over the i++, and the next iteration tests the same x[i]. Since nothing has changed, the condition succeeds again, so it keeps doing the same thing.
You just want to skip over the console.log(x[i]) statement, not everything in the body.
Also, you didn't put the console.log(x[i]) inside the loop at all, so even if the loop worked correctly you wouldn't have printed out the odd elements; it would just print x[i] after the loop is done, and since i then would be outside the array, it would print `undefined.
function loop() {
var x = [1, 2, 3, 4, 5, 6, 7, 8]
var i = 0;
while (i < x.length) {
if (x[i] % 2 != 0) {
console.log(x[i]);
}
i++
}
}
loop()
If you really want to use while and continue, you can put i++ before the test. But then you have to subtract 1 from i when using it as the array index.
function loop() {
var x = [1, 2, 3, 4, 5, 6, 7, 8]
var i = 0;
while (i < x.length) {
i++;
if (x[i - 1] % 2 == 0) {
continue;
}
console.log(x[i - 1]);
}
}
loop()
You could also use a for loop instead of while, since the i++ will be in the for() header, which is executed every time.
function loop() {
var x = [1, 2, 3, 4, 5, 6, 7, 8]
for (var i = 0; i < x.length; i++) {
if (x[i] % 2 == 0) {
continue;
}
console.log(x[i])
}
}
loop()

If your goal is to print out the odd numbers in the loop, try just printing them:
function loop() {
var x = [1,2,3,4,5,6,7,8]
var i = 0;
while ( i < x.length){
if (x[i] % 2 == 1){
console.log(x[i]);
}
i++;
}
}
loop()
What’s happening right now is that your loop is not increasing i, so when the number is even you continue right past i++ and never get past that number, leading to an infinite loop. This way, whether the number is odd or even you increment i.

It happens because you do not increase i in the condition.
Use this:
function loop(){
var x = [1,2,3,4,5,6,7,8]
var i = 0;
while ( i < x.length){
if (x[i++] % 2 == 0){
continue;
}
console.log(i);
}
console.log(x[i])
}
loop()

If you want to iterate through an array, use for loop

Related

Does anyone know how I can return the prime numbers in the matrix?

I want to build a function to know how many prime numbers there are in my matrix (5) and I want to return the quantity - 5
Can anyone understand where my mistakes are? At the end there is a mistake for sure, because I was unable to return the quantity
let matrix = [ [50,17], [19,20,6,40,14], [97] ,[31,9,5] ];
let counter = 0
for(let row = 0 ; row < matrix.length ; row++){
for(let col = 0 ; col < matrix[row].length ;col++){
function matrixPrimeNumbers(num){
for(let d = 2 ; d<= num -1 ; d++) {
if(num % d == 0){
return false;
}
num++;
return num.charAt();
}
}
}
}
There are many issues:
The function matrixPrimeNumbers is never executed. In your nested loop, you do nothing else then define the same function over and over again. The function is never invoked.
The function itself has a disfunctional loop: on the very first iteration of that loop, it will exit at the return statement. So there is actually no looping.
Calling num.charAt() is ... strange? charAt is a string method, and returns a character. Why would you want to call it on a number, and what does that have to do with finding a prime? Elsewhere you have return false, so presumably you want the function to return a boolean. True when num is prime, and false when it is not. So after the loop finishes, just add return true.
num++; is wrong. You want to determine whether num is a prime, so you should not change its value during the loop. Probably you intended to do counter++;, but it is placed at the wrong spot. This should only be done when you are certain there is no divisor, and so it should be placed after the loop. Better still, it should happen outside the function, after a call of that function.
You say you want to "return the quantity". But you never return the counter. In order to return something, you need a function for it. So wrap most of the code into a function, and let it return the counter;
It is OK to have a function for detecting whether num is a prime, but then name it accordingly, like isPrime. Use the name matrixPrimeNumbers for the main function that will do the nested looping over the matrix. I would even change the name to something more telling: countMatrixPrimeNumbers.
It is not necessary for prime detection to loop to num-1. You can stop at the square root of num.
Integers that are 1 or less are not considered primes, so you should deal with that case.
So here is a correction:
let matrix = [ [50,17], [19,20,6,40,14], [97] ,[31,9,5] ];
// Define functions at the top level, not inside for-loops
function isPrime(num) {
if (num <= 1) return false;
let root = Math.sqrt(num);
for (let d = 2; d <= root; d++) {
if (num % d == 0) {
return false;
}
}
return true;
}
function countMatrixPrimeNumbers(matrix) {
let counter = 0
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (isPrime(matrix[row][col])) {
counter++;
}
}
}
return counter;
}
// call it:
console.log(countMatrixPrimeNumbers(matrix));
First of all, you should not declare a function in a for loop. I don't think that this throw an error but with some text editor, it probably shows a warning.
You can modify this method (in ES6 syntax) to check if anumber is a prime number, and returns (0 or 1) instead of (true or false).
// This method returns 1 if the number is a prime number, else return 0
const isPrime = num => {
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return 0; // Not a prime number, return 0
return ( (num > 1) ? 1 : 0 ); // Return 1 if num > 1, else return 0
}
You can now use the isPrime function in your code like this :
let matrix = [ [50,17], [19,20,6,40,14], [97] ,[31,9,5] ];
let counter = 0
for(let row = 0 ; row < matrix.length ; row++){
// Counter will increase if isPrime returns 1
for(let col = 0 ; col < matrix[row].length ;col++)
counter += isPrime(matrix[row][col])
}
console.log(counter); // Should show in console how many prime numbesr you have in the matrix

almostIncreasingSequence - Javascript

Hi guys I'm using Codefights concurrently while I learn algorithims & data structures and I cant seem to solve this problem.
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
My code is failing due to performance and I have a general idea why considering my copying of the original array and looping through both. But I am unable to think of a more optimized way.
function almostIncreasingSequence(sequence) {
let result = false;
for(let i = 0; i < sequence.length; i++) {
let newSequence = [...sequence]
newSequence.splice(i,1)
result = isArraySequential(newSequence)
if (result) {
return result;
}
}
return result;
}
function isArraySequential(array) {
let isSequential = true;
for(let i = 0; i < array.length; i++) {
if(i == array.length - 1) {return isSequential}
if (array[i + 1] < array[i] || array[i + 1] == array[i]) {
return !isSequential;
}
}
}
You don't need to constantly check the entire array, nor use multiple loops.
The problem can be broken down to smaller questions. For each element in the list...
Is the current element greater than the last (increasing)?
Yes...
Good! We don't need to do anything.
No...
Has this happened already? If so, it's not almost increasing.
If we remove the previous item, are the surrounding items fixed?
No? What if we remove the current item instead?
Still no? Then that means we can't solve this in one move. It's not almost increasing.
The code would look something like this:
function almostIncreasingSequence(sequence) {
let invalidItemsCount = 0;
for (let i = 1; i < sequence.length; i++) {
if (sequence[i] <= sequence[i-1]) {
invalidItemsCount++;
if (invalidItemsCount > 1) return false;
if (sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;
}
}
return true;
}
var test1 = [0,1,2,3,4,7,6,7,8,9,10];
var test2 = [0,1,2,4,3,4,5,7,6,7,8,9,10];
console.log(almostIncreasingSequence(test1));
console.log(almostIncreasingSequence(test2));
Commented version:
function almostIncreasingSequence(sequence) {
//Keep track of how many replacements we've had to make
let invalidItemsCount = 0;
//Start our loop at 1 so that [i-1] doesn't refer to index "-1"
for (let i = 1; i < sequence.length; i++) {
//If this item is not increasing, we'll need to address it
if (sequence[i] <= sequence[i-1]) {
//Increment our invalidItemsCount
invalidItemsCount++;
//If this is our second invalidItem, then it's not almost increasing.
if (invalidItemsCount > 1) return false;
//If removing the previous element doesn't help, and removing the current item doesn't help,
//then we can't solve this in one move. It's not almost increasing.
if (sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;
}
}
//We've made it through the entire loop without fail. This is almost increasing.
return true;
}
var test1 = [0,1,2,3,4,7,6,7,8,9,10];
var test2 = [0,1,2,4,3,4,5,7,6,7,8,9,10];
console.log(almostIncreasingSequence(test1));
console.log(almostIncreasingSequence(test2));
This is my solution to the problem. I hope someone would find it helpful.
function almostIncreasingSequence(sequence) {
let flag = 0;
for (let i = 0; i < sequence.length; i++) {
if (sequence[i] >= sequence[i+1]){
flag++;
if(i !== 0 && sequence[i] >= sequence[i+2]){
if(sequence[i-1] >= sequence[i+1])
return false;
}
}
}
return flag < 2;
}
Checkout this solution I found, time complexity is O(n).Hope someone finds it helpful
function almostIncreasingSequence(){
let bad=0,i; //initialize the number of bad counts
for(i=1; i<sequence.length; i++){
if(sequence[i]<=sequence[i-1]){
bad++
}
// The descriptions say "removing no more than one element from the array."
// if the number of bad counts is more than one, we can't obtain the desired result so return false
if(bad>1) return false
// if the element on current index is less than or equal the adjacent element -2 steps back
// && next element is less than or equal to the element on previous index return false
if(sequence[i]<=sequence[i-2] && sequence[i+1]<=sequence[i-1])return false
}
return true
}
Here is the link
I came up with this solution in TypeScript, I put here to have some feedback.
It works because the boolean is initially undefined.
function almostIncreasingSequence(sequence: number[]): boolean {
let joker : boolean;
console.log(joker);
for (let index = 1; index < sequence.length; index++) {
const element = sequence[index];
if (sequence[index] <= sequence[index-1]) {
if (!joker) {
joker = true;
} else {
return false;
}
}
}
return true;
}
package main
import "fmt"
func main() {
fmt.Println(almostIncreasingSequence([]int{10, 1, 2, 3, 4, 5}))
fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 2, 3, 6}))
fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 4, 99, 5, 6}))
fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 4, 5, 6, 5}))
fmt.Println(almostIncreasingSequence([]int{1, 5, 3, 4, 5, 6, 5}))
}
func almostIncreasingSequence(sequence []int) bool {
count := 0
for i := 1; i <= len(sequence)-1; i++ {
if sequence[i] <= sequence[i-1] {
count++
if count > 1 {
return false
}
if i <= 1 || i == len(sequence)-1 {
continue
}
if sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1] {
return false
}
continue
}
}
return true
}

Why does this program print 3 and not 2?

I am currently learning JavaScript, and right now I am on a topic discussing the differences between let and var.
Can someone explain why this code prints 3 and not 2? How does i even reach the value of 3 when the loop should stop executing once i becomes 2?
var i;
function printNumTwo() {
return i;
}
for (i = 0; i < 3; i++) {
if(i === 2) {
printNumTwo();
}
}
print(printNumTwo()); // prints 3
You are not printing anything while i is 2, only after the loop is when you call print. The Loop stops when i becomes 3.
To have it print 2, you have to change the printNumTwo() function like so:
var i;
function printNumTwo() {
print(i);
}
for (i = 0; i < 3; i++) {
if(i === 2) {
printNumTwo();
}
}
it because you have this line
for (i = 0; i < 3; i++) {
which increment value of i, and i is global variable and when you call you printNumTwo i value reached to 3 because of loop increment i value
When you print(printNumTwo()) i is 3. Calling printNumTwo() in the if statement does nothing but returning i which is not used by anything.
So basically the for statement runs and finishes making i=3 and then i is used by your print method.
You have to change start loop with let keyword because var is a global variable and let is block scope variable. that's why getting the different value.
You can try this
var i;
function printNumTwo() {
return i;
}
for (let j = 0; j < 3; j++) {
i = j;
if(i === 2) {
printNumTwo();
}
}
cosole.log(printNumTwo());
Try to use break statement it "jumps out" of a loop and continues executing the code after the loop if the specified condition is true.
var i;
function printNumTwo() {
return i;
}
for (i = 0; i < 3; i++) {
if (i === 2) {
break;
printNumTwo();
}
}
document.write(printNumTwo()); // prints 2

Why is this function creating an infinite looop?

The first function determines if a number is prime. The second function is supposed to create an array with all prime numbers up to and including the max value, but it gives me an infinite loop for some reason.
function isPrime(num) {
for (i = 2; i < num; i++) {
if (num % i === 0) {
return false
}
}
if (num <= 1) {
return false;
}
return true;
}
function primes(max) {
var all = [];
for (i = 2; i <= max; i++) {
if (isPrime(i)) {
all.push(i);
}
}
}
primes(17);
Your i variable is global, so both functions use the same i. This means the first function changes it while the second one is looping.
As the first function will have set i to num-1 when it finishes, and num was the value of i before executing it, it effectively decrements i with one. And so i will get the same value in the next iteration of the loop in the second function, never getting forward.
Solve this by putting the var keyword in both functions.
for(var i=2; // ...etc)
The variable i in your two loops are global variables and they overwrite each other so the first loop never ends.
In ur code problem is with the scope of variable i, In prime no calculation, u can check upto the sqrt of no, if no is not divisible by any no upto its sqrt, then it will a prime no, Try this:
function isPrime(num) {
let k = Math.sqrt(num);
for (let i = 2; i <= k; i++) {
if (num % i === 0) {
return false
}
}
return true;
}
function primes(max) {
let all = [];
for (let i = 2; i <= max; i++) {
if (isPrime(i)) {
all.push(i);
}
}
console.log(all)
}
primes(17);
primes(25);

For loop qustion javascript

I want to do a for loop that is looping 50 times but I need the code block inside the loop to run just on multiples of nine(9,18,27,36..)
How can I do it?
for(var i=0; i<450; i+=9) {
...
}
Alternatively, for better readability:
for(var nines = 0, loop_counter=0; loop_counter<50; loop_counter += 1, nines = loop_counter*9) {
...
}
Something like this:
for(var i = 0; i < 50; i++) {
if (i % 9 == 0) {
//code block here
}
}
for(var i = 0; i < 50; i++) {
if (i % 9 == 0) {
console.log(i);
}
}
fiddle
for(var i = 0; i < 450; i += 9) {
console.log(i);
}
fiddle
for (var i = 1; i <= 50; ++i) {
(function(multipleOfNine) {
// Do something with multipleOfNine
}(i * 9));
}
I interpreted your question to mean you want to loop over the first 50 multiples of nine. If what you meant was you want just the multiples of nine under 50, then use EnterSB's answer.
Record which iteration of the loop you are in (simplest way is to initialize a variable outside the loop to 0 and then increment it every time you go through the loop) and then use Modulo to check if it's divisible by 9. e.g. x=i%9. If x is 0 then i's a multiple of 9.

Categories