Why does the continue statement print even numbers, but will print odd numbers if replaced by console.log() in the following?
// print even numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) != 0) {
continue;
}
console.log(i);
}
//print odd numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) != 0) {
console.log(i);
}
}
In the first example, the loop continues with the next iteration if the number is odd (and therefore the program does not reach console.log()). In this next iteration the number is even and will be printed.
The second example is quite trivial: you only print the number if it is odd.
When the continue statement is executed, the rest of the contents of the loop body are skipped and execution returns to the top of the loop, to start the next iteration of the loop. So this:
if ((i % 2) != 0) {
continue;
}
means "If i is odd, skip back to the top of the loop, don't execute the rest of the loop body." That means the odd number isn't printed.
In your second example, you're only outputting when the condition is true, so you've ended up doing the opposite output, but in a different way: Only calling console.log when the number is odd.
You can make the first one output only even numbers by removing the continue, changing the condition, and moving console.log into the if body:
// print even numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) === 0) { // *** Changed condition
console.log(i); // *** Moved `console.log`
}
}
That does even numbers in the same basic way the second one did odd numbers.
Or you can change the second one work like the first one, but in general it's best to avoid using continue (there are probably exceptions to that general rule):
// print odd numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) == 0) { // *** Changed condition
continue;
}
console.log(i);
}
Related
I submitted the following codes for the Palindrome Index challenge on HackerRank, but it fails some test cases with the error Exceeded time limit. I am not sure what is wrong with my codes.
Basically, I implement a distinct "helper" function to check if a string is a palindrome. In the PalindromeIndex function, I first check if a string is a palidrome then return -1, else I will loop through the string, try to remove each letter to see if the remaining string is a palindrome.
If it is, return the index right there; else, continue.
If the loop finishes without returning any index, that means there is no result, I return -1.
That is what I am trying to do, but I cannot find out the problem here. Thanks!
function isPalindrome(s) {
for (let i = 0; i < s.length; i++) {
if (s[i] !== s[s.length - 1 - i]) {
return false;
}
}
return true;
}
function palindromeIndex(s) {
let result = isPalindrome(s);
if (result) {
return -1;
}
else {
for (let i = 0; i < s.length; i++) {
let newS = s.slice(0,i) + s.slice(i+1);
if (isPalindrome(newS)) {
return i;
}
}
return -1
}
}
You need to optimize your palindrome function. Just run loop from 0 to half of array.
function isPalindrome(s) {
for (let i = 0; i < s.length/2; i++) {
if (s[i] !== s[s.length - 1 - i]) {
return false;
}
}
return true;
}
I will just draw up the basic idea, because I guess you want to try for yourself:
aaa = -1
aaab = 3
baaa = 0
bbaa = -1
You only want to loop through the string once.
You only need to loop through half the string, and do comparisons.
I would just focus on moving indexes.
String: baaa
Default variables:
position: -1
startNudge: 0
endNudge: 0
At index i (start at 0):
check i + startNudge against string.length - 1 - i + endNudge.
If not equal:
check index i + 1 + startNudge against string.length - 1 - i + endNudge.
if equal, set position to i and set startNudge to 1.
else, check i + startNudge against string.length - 2 - i + endNudge.
if equal, set position to string.length - 1 - i and set endNudge to -1.
else break loop by returning -1.
if position already saved, break loop by returning -1.
continue loop.
Return position if loop completes.
...else I will loop through the string, try to remove each letter to
see if the remaining string is a palindrome
This is the problem. It isn't necessary to loop through the whole string again, because as soon as a pair of letters is found in the string which break the palindrome - the answer must be either the index of the first letter or the second letter of the pair OR - if the removal of both letters don't produce a palindrome - then return -1.
function palindromeIndex(s) {
function isPalindrome(s) {
for(let i=0; i< Math.floor(s.length/2);i++) {
if(s[i] !== s[s.length-1-i]) {
return false;
}
}
return true;
}
for(let i=0; i< Math.floor(s.length/2); i++) {
if(s[i] !== s[s.length-1-i]) {
if(isPalindrome(s.slice(i, s.length-i-1))) {
return s.length-i-1;
} else if(isPalindrome(s.slice(i+1,s.length-i))) {
return i;
} else {
return -1;
}
}
}
return -1;
}
console.log(palindromeIndex('aabaa'))
console.log(palindromeIndex('aaab'))
console.log(palindromeIndex('baaa'))
console.log(palindromeIndex('baaabcc'))
This solution will have a time complexity of O(n) because only one loop is necessary
I'm having some frustration with this code. I may not be seeing it.
I keep getting either an "Unexpected Token" or "ILLEGAL" error (the latter which completely preplexed me, considering I've never seen an error like that before in my life.
I've been double checking the syntax and I'm thinking it may be something I'm just not catching?
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) {
4 print ("fizz")
5 }
6 if (n%5===0) {
7 print ("buzz")
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i];
11 }
12 }
13 }
14
15
16 fizzBuzz(100);
I'd be thankful for the help! <3
You need some changes:
remove line numbers,
check first for 'fizz buzz' value and use console.log for output. Then use continue statement for jumping to top for next loop,
use i instead of n for checking.
function fizzBuzz(n) {
for (i = 0; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("fizz buzz");
continue;
}
if (i % 3 === 0) {
console.log("fizz");
continue;
}
if (i % 5 === 0) {
console.log("buzz");
continue;
}
console.log(i);
}
}
fizzBuzz(100);
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) { You're checking if the maximum number (n) is divisible by 3.
4 print ("fizz") You should be checking i.
5 }
6 if (n%5===0) { You're checking if the maximum number (n) is divisible by 5.
7 print ("buzz") You should be checking i.
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i]; You're returning an array with a single element: i.
11 } You should print i instead.
12 }
13 }
14
15
16 fizzBuzz(100);
The line numbers are what's causing the "ILLEGAL" error. Remove them.
print in JavaScript opens the print dialog to literally print paper out of a printer. Use console.log
If a number is divisible by both 3 and 5, fizzbuzz should be printed. Your code prints fizz and buzz on separate lines.
Working version ( https://www.youtube.com/watch?v=QPZ0pIK_wsc ) :
function fizzBuzz(n) {
for (var i = 0; i <= n; i++) {
var printVal = "";
if (i % 3 === 0) {
printVal += "fizz";
}
if (i % 5 === 0) {
printVal += "buzz";
}
if (printVal === "") {
printVal = i;
}
console.log(printVal);
}
}
fizzBuzz(100);
Lets decrease number of if statements, I have seen many fizzbuzzs - I would like to try another approach
const fizzBuzz = (i = 0, ret) => {
while (++i, ret = '', i <= 100) {
if (i % 3 === 0) {
ret += `fizz`
}
if (i % 5 === 0) {
ret += `buzz`
}
console.log(ret || i)
}
}
fizzBuzz()
The most important part is console.log(ret || i) - empty string is falsy value, so console will log ret if there is some value or current i value
If you're trying to print to your browser's console, use console.log() instead of print(), since print() will open the printer preview in a browser. I'm using Chrome. Remember to check the console by pressing F12 and clicking on "console" in case you've created a html file that includes your javascript script.
Since you are iterating i until it reaches the value of n, you if statements should look like:
if(i%3===0){
// your code...
}
Based on your code, it seems like you want to check for a value that is not a multiple of 3 && a multiple of 5. However, the fizzbuzz challenge requires to print fizzbuzz when encountering a number that is both a multiple of 3 && a multiple of 5. So, you'll need to add the following condition:
if (i%3 === 0 && i%5 === 0) {
console.log("fizzbuzz");
continue; /* Continue may or may not be necessary depending on your program's logic. Continue allows to re-enter the loop
without checking for the remaining if statements. If you use continue, this condition must be the first if statement inside the loop */
}
Your function doesn't need to return anything, since you're using console.log() to visualize the values in each loop iteration. That's why you need to change return [i] for console.log(i).
Don't give up and keep trying!
If you have further questions, I'll be glad to help you.
I am a very beginner JS "developer" (student) and I have run into a question I haven't been able to solve: why does the value of the repeated letters in my 'helperHash' increase when I am not using an else statement and why this same value DOESN't increase if I use an else statement? My code runs as expected but I am having problems understanding the logic behind this issue...
The code is supposed to return an array with the letters that have 1 or more repetitions in the given str.
function nonUniqueLetters(str){
var strToChars = str.split('');
var finalArr = [];
var helperHash = {};
for (let i = 0; i < strToChars.length; i += 1){
let char = str[i];
if (!helperHash[char]){
helperHash[char] = 0;
}
helperHash[char] += 1; //HERE! why doesn't this work if inside an else?
}
for (var key in helperHash){
if (helperHash[key] > 1){
finalArr.push(key);
}
}
return finalArr;
}
For helperHash[char]…
The initial value is undefined and !undefined is true so it sets the value to 0.
The next time char has the same value, helperHash[char] is 0 and !0 is also true so it sets the value to 0 (which it already is, so it makes no difference).
Instead of testing if the value is a false value, test if it is undefined, or if it exists at all.
if (typeof helperHash[char] === "undefined")
or
if (char in helperHash)
Logic error.
How the current code works:
if (!helperHash[char]){
// Enters here only when helperHash[char] is not set (or 0, but it is never 0)
helperHash[char] = 0;
}
// Always increment
helperHash[char] += 1;
// There is no 0 in helperHash at this point
Why putting helperHash[char] += 1 in an else branch doesn't work:
if (!helperHash[char]){
// Enters here only when helperHash[char] is not set or 0
helperHash[char] = 0;
// Still 0, will take this branch again on the next occurrence of char
} else {
// Increment only if it was already 1 or more (this never happens)
helperHash[char] += 1;
}
// Here helperHash contains only 0 for all keys
How to make it work:
if (!helperHash[char]){
// This is the first occurrence of char, let's count it
helperHash[char] = 1;
} else {
// This is a subsequent occurrence of char, let's count it too
helperHash[char] += 1;
}
// There is no 0 in helperHash at this point
The reason is this if (!helperHash[char]){ and how integers are converted to booleans in Javascript.
You initialize every member of the hash to 0 which equals a boolean false, so the else is never hit because helperHash[char] === 0 === false and thus !helperHash[char] is true for all values initialized with 0
Your if condition:
!helperHash[char]
is always evaluating to true (helperHash never has characters in it that are "falsy"). So, an else branch of that if would never be hit.
I'm trying to create javascript that will count from 1 to 1000 and push any multiples of 3, 5 into an array called multiples then print that array out using console.log(). For some reason my code isn't working. Does anyone know why?
var n;
var multiples = [];
for(n = 1; n <= 1000; n += 1) {
console.log("Counting");
}
if(n % 3 === 0) {
n.push(multiples);
}
else {
}
if(n % 5 === 0) {
n.push(multiples);
}
else {
}
if(n >= 1000) {
console.log(multiples);
}
else {
}
There are few issues with your code. Using {} in your for block designates the scope of the code executing in each iteration. So in order to access each value for n you need to be placing your conditional statements inside of the {} and not outside of them.
There is a slight syntax error with your multiples array. In order to push a value into an array you would use the arrayname followed by the dot operator and then the push function with the argument being the value pushed. In terms of multiples and n, this means multiples.push(n).
When using an if() block, else is not required.
It is generally best practice to include the variable declaration inside of for loops, and also to use ++ as opposed to += 1.
Overall, your code would need to look more like this
var multiples = [];
console.log("Counting");
for(var n = 1; n <= 1000; n++) {
if(n % 3 === 0) {
multiples.push(n);
}
if(n % 5 === 0) {
multiples.push(n);
}
}
console.log(multiples);
I'm trying to do a function that'll print the numbers between 1-27 in my console.log.
When a number can be divided by 3, it should replace the number with "Fizz"
When a number can be divided by 5, replace it with "Buzz".
If the number can be divided by both 3 and 5, replace it with "Fizzbuzz"
Reference: http://en.wikipedia.org/wiki/Fizz_buzz)
This is my code:
var fizzbuzz = function(start,stop) {
for (var x=1;x <= stop; x++)
var string =',';
if (x%3 == 0) {
string += 'Fizz';
}
if (x%5 == 0){
string += 'Buzz';
}
if (x%5 && x%3){
string += 'Fizzbuzz';
}
return string;
};
Console.log is giving me "," and I'm not sure what I've done wrong.
Just to clarify.
I want my answer to print out 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,Fizz Buzz,16,17,Fizz,19,Buzz,Fizz,22,23,Fizz,Buzz,26,Fizz and so on depending on 'stop' in the If-statement.
Valentins comment is correct, you do need to add brackets around your loop.
You are however also redefining the string var in every iteration of the loop.
The last if also makes the output a bit wrong as for example 15 would hit all 3 statements and print FizzBuzzFizzBuzz
so go with something like
var fizzbuzz = function(start,stop) {
var string = '';
var addComma = false;
for (var x=1;x <= stop; x++){
addComma = false;
if (x%3 == 0) {
string += 'Fizz';
addComma = true;
}
if (x%5 == 0){
string += 'Buzz';
addComma = true;
}
if(addComma && x!== stop){
string+=','
}
}
return string;
};
This is not the best way to keep track of where to add a comma, but it does the job.
for(let x = 0; x <=30; x++) {
if (x % 15 === 0) {
console.log('Fizzbuzz')
} else if (x % 5 === 0) {
console.log('Buzz')
} else if (x % 3 === 0) {
console.log('Fizz')
} else {
console.log(x)
}
}
this is how i dealt with it
You need to correct your for loop
You have
for (var x=1;x <= stop; x++)
var string =',';
being executed up until x <= stop.
Javascript allows you to avoid using brackets if you want to execute one line statements like so.
if (a===true)
alert(a); // This is executed when a === true
alert(b); // This is always executed no matter what a is
Indentation here was to make a point but the if statement would execute everything until the first semicolon.
On the other hand if you wanted to perform multiple lines of code if a === true you would choose to use curly braces like so
// Alert a and alert b are only executed if a is true
if (a===true) {
alert(a);
alert(b);
}
The if statement would execute everything in the curly braces.
Its important to note that return stops execution and exits the function. Once you reach a return statement the loop will be exited. That is why you should return the whole string after the for loop.
This is a better implementation but you should definitely try implementing it yourself
var fizzbuzz = function(start,stop) {
var string = '';
for (var x=1;x <= stop; x++) {
var status = x.toString(); //Each time the loop executes a new variable `status`is created and set to the value `x` for that loop.
// x is checked as to whether it is divisible by 3 or 5 or both, if it is divisible its status is set to a that value
if (x%3 === 0) {
status = 'Fizz';
}
if (x%5 === 0){
status = 'Buzz';
}
if (x%5 === 0 && x%3 === 0){
status = 'Fizzbuzz';
}
string += status; // Append status to the end
if (x !== stop){ // If x is not equal to the value of stop add a comma
string += ',';
}
}
return string; //This returns the string value which has had statuses and commas appended to it.
};
There are multiple problems with this:
(1) The construct
for (var x=1;x <= 10; x++)
statement;
otherstatement;
will execute statement 10 times before it executes other statement. Without braces, Javascript assumes that the next statement is the contents of the for loop;
(2) The string variable is redefined in every loop which gets rid of the preceding version, so the return statement only prints out the last value of string.
(3) The logic of the fizzBuzz if statements are wrong. If you follow this for a statement that divides by 15, it executes all three statements. The third iff statement is therefore completely redundant.
A solution would look like:
var fizzBuzz = function(x){
if(x%15==0){
return "Fizzbuzz";
}
if(x%3==0){
return "Fizz";
}
if(x%5==0){
return "Buzz";
}
return x;
};
var mainFunction = function(start,stop){
var str="";
for(var i=start; i < stop; i++){
str += fizzBuzz(i) + ", ";
}
return str;
};
Note that the third if statement for %15 is necessary only if this version demands that you print Fizzbuzz, rather than FizzBuzz.