Infinite While loop mod 3 - javascript

I basically just want to print numbers a list of numbers a skip multiples of 3. I got it to work but the initial way i tried it did not work and i do not understand why, just need someone to please explain why it doesn't work and goes into an infinite loop.
This is the problem, why does it go into an infinite loop? I am clearly missing a key concept about code, if someone could help thanks.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
document.write( i + "</br>");
i++;
}
I know you can do it this way.
while (i <= 10)
{
if (i % 3 != 0) {
document.write("Number is " + i + "<br />");
}
i++
}

If we ignore the code producing the output and look only at the code checking and modifying i, it might become a little more clear why it's not working. It also helps to format our code for extra clarity.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
i++;
}
Start with i = 0.
i <= 10 is true. Enter the loop.
i % 3 == 0 is true. Enter the if block.
continue;. Go straight to the top of the while loop again. Do not pass i++;. Do not collect 1.
Lather. Rinse. Repeat (infinitely).

continue jumps to the next iteration and doesnt complete the rest of your code in the while. So i is not being incremented but rather staying as 0 becuase you wrote continue before incrementing the i. so therefore it is in an endless loop, it is always less than 10

Related

Freecodecamp - Counting Cards

I know there are a number of ways to complete this challenge and I can simply a different approach to pass the requirement however I am struggling to understand what's wrong with my code.
Challenge - https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/counting-cards/
Any help would be much appreciated.
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count+=0;
} else (count--;)
if (count > 0){
return count + " Bet";
} else (
return count + " Hold";
)
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
Firstly, when you try to execute your code, you should be seeing a Syntax Error, pointing to the semicolon in (count--;). The reason for this is: else expects a statements, if it sees a parenthesis it means the statement is an expression, and in an expression, semicolons can't appear inside parentheses (this is rather simplified). The correct way to write it is either without parentheses (generally frowned upon) as else count--;, or with curly braces: else { count--; }.
When you fix that error, there will be another one of the same kind, as you seem to systematically use parentheses instead of curly braces after else.
After that, your code kind of works. There's questionable comparisons of card, that can be a letter or a number, with an integer, but it coincidentally works the way you hope it does (because 'K', 'Q' and 'J' happen to be evaluated as greater than 7 and 10.) It would be better to not rely on such magic, and have a translation table between letters and values - or at least, if you're going to rely on magic, comment so that readers are aware you are aware of the magic. Also, count+=0 is a void statement, it does nothing, and could have been left out. That leaves you with an empty else if, but that's not an error. However, it would probably be much more readable if you had if (card < 7) { count--; } else if (card >= 10) { count++; }.
stupid mistake's.
answer is below:
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count;
} else {count--;
}
if (count > 0){
return count + " Bet"
} else {
return count + " Hold"
}
// Only change code above this line
}

Javascript setTimeout give another timeout

I have a trouble with setTimeout function in javascript, my purpose is to give timeout for each insert statement, after reach given maxrecord, it will pause for 2 hours, then continue the insert statement.
Right now im only make a work for first condition wich is given delay for each insert. But i dont know how to give 2 hour delay before continue to insert.
my code like this,
var ids = $("#listId").val().split('\n');
var index = 1;
for(var i = 0; i < ids.length; i++) {
(function(i){
setTimeout(function(){
if (index <= interval) {
console.log("INDEX : " + index + " INTERVAL : " + interval);
} else {
console.log("SHOULD BREAK FOR 2 HOURS (NOTHING TODO HERE, JUST DELAY) THEN CONTINUE FROM LAST IDS");
}
index++;
}, 1000 * i);
}(i));
}
as you can see, i need to give 2 hour's delay after index <= interval and then continue again with last i.
Appreciate your help.
You are setting all of your timeouts at once, at the start, with predefined durations.
You cannot (easily) go on to modify how those times are set based on an arbitrary condition (this 2 hour delay you speak of)
Instead, you should do something like:
function nextRow() {
// handle a single row
i++;
if( i < ids.length) setTimeout(nextRow,delay);
// where delay is either 1000 or 7200000 as needed
}
nextRow(); // start the loop

Check lines A and count it until it changes to lines B javascript

I am sorry in advance if my title is somehow misleading and I am really sorry for my English if you wouldn't understand me, it's just not my native language!
I will try to explain as better as I can about what I try to achieve. I try to do this for past two entire days and I really need your help!
Let's say I have array with the following numbers:
2 4 6 8 10 1 3 5 2 4
I am trying to count how many even and odd numbers are here in a row, and when even/odd changes - count it again. So my answer from the array above should be:
5 (5 even numbers in a row) 3 (3 odd lines in a row) (2 even lines in a row)
Also when the counting isn't stopped it should post "<br>" instead of counted evens/odds, so it could show me results one time near to each line.
Check this example image:
I have this script which is counting, but it has a few issues: when number is even, it shows counting twice. Next, I can't figure it out how to add <br> to these lines where counting and add result only at the last line of counting. Also my counting result should be at the top, so the script should count from the end as I guess, and when I try i-- it starts the infinite loop...
var digits = ["2, 4, 6, 8, 10, 1, 3, 5, 2, 4"]
var evenCount=1, oddCount=1;
for(var i =0; i < digits.length; i++){
if(digits[i] % 2 ==0){
var oddCount=1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
}
else
var evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
Check my fiddle to see it in action:
https://jsfiddle.net/xk861vf9/8/
First, I think your code show counting twice because you misses two '{' after "for loop" and "else". After I fix the code format, I don't see it counting twice anymore.
$(document).ready(function() {
$("#sub").bind("click", function() {
$("#res").html("");
var digits = $('#content').find("span").map(function() {
return $(this).text();
});
var evenCount = 1;
var oddCount = 1;
for(var i =0; i < digits.length; i++) {
if (digits[i] % 2 ==0) {
oddCount = 1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
} else {
evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
}
});
});
Second, they are many ways to implement that. Take a look at this jsfiddle code as an example.
https://jsfiddle.net/xk861vf9/11/
The concept is to print the counted number after even/odd number changes. Then use for loop to print <br> x times (counted number - 1) so if counted number is 4, there will be 3 <br> tags followed.We also have to check if current number is the last number in array and print the counted number or else the last counted number will be skipped.
Hope this help! :)
Ps. Sorry for my bad English, not my native language too.

FizzBuzz game- how to create a comma-separated string

I should create a function called 'fizzBuzz()' that takes two arguments 'start' and 'stop' and returns a comma-separated string. The arguments represents the starting point and stop point of the game 'Fizz Buzz'. (http://en.wikipedia.org/wiki/Fizz_buzz). Shortly it means, in a range of numbers I should print all numbers that are divisible by three as Fizz and the numbers divisible by 5 as Buzz, the rest as is. The function should run from start to stop and add 'Fizz', 'Buzz' or both to the 'result'-variable at the appropriate numbers.
If 'stop' is equal or lower than 'start', the function should return an error message.
function fizzBuzz(start, stop) {
for(var i= start; i <= stop; i++) {{
if (i % 5 == 0)
print "Buzz";
else if (i % 3 == 0)
print "Fizz";
else
print i;
}
console.log(",")
}
My problem is that I donĀ“t know how to make the loop work. Right now when I try to print fizzBuzz(2,24) Nothing comes out. The console tells me that there is semi colon missing at row 4 (same line as "Buzz".
Also, I wonder if this will work with an if/else statement since there are some numbers that are both divisible by 3 and 5. Would it be more clever to use a switch?
Lastly, I want to add an if-statement like the following somewhere.
if(start == stop || start> stop)
alarm("choose different numbers");
Should it be inside the function? || means "or", is that correct?
Thanks in advance!
The problem with your code (apart from the extra {) is that you are calling return in your for loop. This causes the function to stop and return only 2.
What you want to do is make a string variable where you add the numbers and then return that. Here is an example of what I mean:
function fizzBuzz(start, stop) {
var returnString = "";
for (var i= start; i <= stop; i++) {
if (i % 5 == 0)
returnString += "Buzz";
else if (i % 3 == 0)
returnString += "Fizz";
else
returnString += i;
returnString += ",";
}
return returnString;
}
Edit: Sorry, I didn't see your second question! Yes, you should put the if statement for if(start == stop || start> stop) alarm("choose different numbers"); at the beginning of the function, before any other code is run (in my example, before var returnString = ""; but after the {). However, there are two things that you should note. First, the function to show a message in JavaScript is alert, not alarm. Second, you should include a return; statement in the if after your alert so that your function doesn't continue after alerting the user to pick different numbers.

99 Bottle song code in pure js

Can some please help me to tell me where i am going wrong in my code. I have been working on it for a little while but i am still stuck please help. this is my code so far. Thanks for the help in advance.
This is my javascript
var bottles;
var beerNum = 99;
// This program will count to 99 for us
// Set up a counter variable, and start it on zero (good place to start)
var counter = 0;
// While loop
while (counter < 99) {
// This line increments (or adds 1) to our counter each time the loop goes around.
counter--;
// This line finds the HTML element with an ID of "output" and puts the value of our counter in it, followed by a line break <br />
// The += operator takes what's already stored and appends our new value to it
document.getElementById('output').innerHTML += counter + "<br />";
}
if (bottles = beerNum){
document.getElementById('output')>innerHTML += bottles + beerNum + "of beer on the wall";
}
And this is my HTML.
<p id="output"></p>
and i have a fiddle to accompany it
http://jsfiddle.net/Matt1990/X4UHD/39/
This might help you out a bit:
for(var i=99; i>0; i--){
document.getElementById("output").innerHTML += i + "Bottles on the wall take one down, pass it around." + "<br>";
}
http://jsfiddle.net/a0knrxzs/
EDIT:
We don't need a while loop, a for loop will just stop when it is no longer greater than 0. While loops are for stopping the loop after a something has been changed.

Categories