Program that calculates and shows the value of (2 to the 10th power)
This statement results in 1024. I'm not understanding how it keeps looping after it reaches "9". Does "< 10" mean loop around ten times, or loop up to a sum less than "10"? Would appreciate someone explaining this to me. Thanks!
var result = 1;
var counter = 0;
while (counter < 10) {
result = result * 2;
counter = counter + 1;
}
show(result);
Your counter is running ten times, once each for the values 0-9. When writing loops like that (that include a <) I think of the 10 as "this loop will be running ten times." It's helped a lot with minor issues like this.
Remember, there are only two really hard things in programming: cache validation, variable substitution, and off-by-one errors.
loop 1: result = 1*2 (2) counter = 1
loop 2: result = 2*2 (4) counter = 2
loop 3: result = 4*2 (8) counter = 3
...
loop 10: result = 512*2 (1024)counter = 10
It loops 10 times and as such it multiplies by two ten times and as such gives you 2^10 = 1024. Exactly.
P.S. If you only want this multiplication, you'd be better off with
result = 1 << 10
Yes ten times 0 to 9 = 10.
When the compiler sees if 10 < 10 it evaluates to false. If you want to see 10 change the condition to <=
The program will only step inside the loop if the condition for the while-loop is met. So you check it before entering the loop.
If you want the program to step inside the loop one more time, either use a do-while loop where you check the condition after the execution of the loop.
You can also change the condition to "counter <= 10" and use the while-loop as is.
Here you can find more information on while-/do-while-loops and also breaks in javascript.
When counter is 1 it result is 2^1
When counter is 2 it result is 2^2
Since counter is 10 at the end of the loop, result is 2^10.
Related
I am trying to get every single combination of elements into an array. Now I can use the method below, and remove the duplicates, but this way is far to slow for my use.
The code below would find every possible combination for 2 digits below 4. Now in the code I actually want to use this for, the least possible code would be 6 for loops (within each other) with the amount being 18 (rememeber this is the minimum).
The code below would execute amount^[amount of for loops], or amount^2 which in this case is 16. That means that in the code I want to use this for, it executes 18^6 times, or 34 million times. And this is the minimum, which would get much higher.
After trying to run my code (with 6 foor loops in which amount = 18), it crashed my browser... My question is: Is there any faster and more efficient (not elegant. I don't care how elegant it is) in which my browser won't crash?
Note: This question is not a duplicate question. All the other questions simply ask for a way to do this, however I already have a way. I am just trying to make it more efficient and faster so that it actually works correctly.
let combinations = [];
let amount = 4;
for (let a = 0; a < amount; a++) {
for (let b = 0; b < amount; b++) {
combinations.push(`${a}${b}`);
}
}
console.log(combinations);
Below is a snippet providing a possible example for how my code would work.
let possibilities = [];
let amount = 6; //Amount is set by me, so don't worry about it being incorrect
for (let a = 0; a < amount; a++) {
for (let b = 0; b < amount; b++) {
possibilities.push(a + b);
}
}
possibilities = [...new Set(possibilities)]; //Removes duplicates
possibilities.sort((a, b) => b - a); //Sorts in descending order
possibilities = possibilities.slice(0, 3); //Gets top 3 values
console.log(possibilities);
Ok, as discussed in the comments, if you need top 3 values for a particular amount, you could just do something simple like below:
let amount = 6;
let highest = amount - 1,second_highest = amount - 2,third_highest = amount - 3;
let possibilities = [
highest + highest,
highest + second_highest,
highest + third_highest
];
console.log(possibilities);
I don't know the any better solution for this, but yes there are some conditions you need to check first.
If(amount <= 0) return 'Invalid amount, Please enter a valid amount"
So if somebody enters a negative or zero value your loop will goes into infinite loop, and make the situation more worst.
if(amount === 1) return '1 possible combination'
As amount less than 1 is 0 only and combinations for 0 is 1 only, you need not to parse whole loop for 6 digits or n digits for 0 so it will get solve in complexity of 1 instead of N(no. of digits).
And for amount greater then 1 you can create manual loops, like here you created 2 loops for 2 digits, you create 6 loops for 6 digits, better create dynamic logic for this to create number of loops automatically.
You need to consider 1111, 1112 this type of combinations as well right?
Or if only 1234, 2134, 2314 this kind of scenarios are required? This can be done in very less complexity.
For duplication you can store combinations as a key value pair. and then Object.Keys will be your combinations.
I am having trouble understanding an answer to a question.
I was told to find the last element in any array the answer would be for example :
alert(countries[countries.length - 1]);
However, I was told to go loop through the entire list of array I would put for example
for(counter=0; counter < presidents.length; counter++) {
document.write(presidents[counter]);
}
Question is....
Why is is counter < presidents.length and not counter < presidents.length-1 like in the example before?
Because you need to print the last value too.
For example, let the array be,
var presidents = ["one", "two", "three", "four"];
Here, presidents.length = 4.
Now, if you do counter < presidents.length-1 then counter goes from 0 to 2.
You either need to do
counter <= presidents.length-1 or counter < presidents.length
in order to make counter go from 0 till 3.
PS: Array indices begin from 0 in JavaScript.
Because array index start with zero and last element will be in (size-1) position. In for loop, you are using less than(<) symbol. It will be < size or <= (size -1).
Probably also worth mentioning that the for loop works because of when things happen. Take the following statement:
for ([initialExpression]; [condition]; [incrementExpression]) {
[statement]
}
initialExpression is evaluated immediately and is typically used to create a variable to increment, as you did with counter=0.
condition is evaluated before executing the statement. If the condition is truthy, the statement is executed; if not, the loop is terminated.
incrementExpression is evaluated after executing the statement. So, incrementing counter here informs the next condition evaluation.
Putting it together, the condition evaluation looks like this:
if 0 < presidents.length // true
if 1 < presidents.length // true
. . .
if 44 < presidents.length // true and will produce the final president element
if 45 < presidents.length // false and terminate the loop
I have an array of words (25 of them, 0-24) and I want to do tests in a for loop that checks whether the randomly chosen word is within the interval 0-4, 5-9, 10-14 etc..
How do I do this?
else if (words[i > 4 && <= 9]){}
I tried that line in a for loop, but it gives me a syntax error.
Uncaught SyntaxError: Unexpected token <=
You're missing a left comparison in your condition. Use this as a condition:
i > 4 && i <= 9
However, note that you're not doing anything useful with the condition. Your result will be akin to words[true] or words[false].
Update
You've now elaborated a little more. If I understand you correctly, you want to pick a random word from your array, and then work out which interval of 5 it resides at within the array.
In the below example, the interval is indexed; so 0 = 0-4, 1 = 5-9, 2 = 10-14 and so on...
var words = [ "Synergetic", "unsteeped", "goldcup", "coronach", "swamper", "rehearse", "rusty", "reannotation", "dunne", "unblenched", "classification", "interpolation", "toper", "grisliest.", "Rechart", "imbower", "reilluminating", "glucagon", "interassuring", "parallelepipedon", "doyenne", "neenah", "tetragram" ];
function pickARandomWordAndCheckTheInterval(){
var randomIndex = Math.floor(Math.random() * words.length);
var word = words[randomIndex]
var interval = Math.floor(randomIndex / 5);
console.log('The random word is:' + word);
console.log('The interval is:' + interval );
}
pickARandomWordAndCheckTheInterval();
To explain it really really simple way you just forgotten to tell the language what needs to be less than or equal 9.
You assumed it processes logic condition like humans do (we would assume that after && operator you're still thinking about i, but that's not what JS interpreter would do).
What comes after && needs to be an expression that can be evaluated. <= 9 doesn't evaluate to value (it is not treated as valid expression because <= is kind of binary operator which requires two operands, one before and one after).
For JS interpreter it just means "less than or equal to 9". But what is "less than or equal to 9"? You need to tell it "i is less than or equal to 9".
i > 4 && i <= 9 is the correct way to write that.
I am working on CodeAcademy trying to learn some JavaScript and I have encountered this interesting thing actually. Please take a look here:
for(var counter = 100; counter > 0; counter = counter - 5){
console.log(counter);
}
Here I tell the loop to loop through an print the counter number as long as counter is bigger than 0, however it only ends up printing 100..95..90 etc down to 5.
I do know how to fix this, by just adding a simple equals sign just after the bigger than sign.
Like this:
for(var counter = 100; counter >= 0; counter = counter - 5){
console.log(counter);
}
But I am interested in knowing why this doesn't work differently?? I mean it ends the output with a 5, 5 is bigger than 0, isn't it?? When I do put a equals sign before the bigger than sign, it really should output some undefined number cause it should loop even then counter is equal to 0. My head hurts from this.
Could someone please explain, thank you :)
No, it should not continue the loop once it reaches zero. The way for loops work is this:
for (initialization; condition; increment) {
body;
}
And it performs these operations in this order:
initialization
loop {
condition true? then:
body
increment
else:
stop loop
}
So when the counter reaches zero, the condition will be false, and the body will not be executed with the counter having value "0", it will simply stop. When you put >=, however, the condition is still true at that point.
The English translation of the "for" loop is:
Set counter to 100
If counter > 0 is not true, end this block
Run this code block (in this case, log counter)
Reduce counter by 5
Go back to step 2
So in this case, if counter is zero, it is not > 0 and therefore the code doesn't go back to step 2. Whereas in the second case, it is >= 0 so it runs through one last time.
Let's see what's happening here,
When you say counter > 0, then it should continue till it is strictly greater than zero. Since zero is not greater than itself, therefore the loop stops at 5.
When you change the expression to counter>=0, then, it tells the compiler to continue till counter is greater than OR equal to zero, therefore it goes on to print zero as well.
Hello there I'm finding it difficult to understand some basic JavaScript
I have written a loop that counts down from 10 to 0 and I'm using console.log to print that value to the console. Inside the loop an if statement is used to check if the number is 0, if it is then console.log prints "Blast Off!" instead of a number.
Here is my working code:
for (i=10; i>=0; i--;)
{
if (i === 0)
{
console.log("Blast Off!");
}
else
{
console.log(i);
}
}
However what I'm desperately trying to understand the is the stop of the for loop which is:
i>=0;
Is this effectively saying if i is greater than or equal to zero then progress through the loop decrementing i each time, then stop when zero is reached?
Conversely when I change the for loop code to what is shown below, is this effectively saying if i is less than or equal to zero then progress through the loop decrementing i each time until zero is reached?
What is the reason for the loop not printing, if the stop is changed? Is this because i never holds a value that is less than or equal to zero, meaning the loop will not run?
i<=0;
Any help clearing this up for me would be appreciated massively.
Your understanding sounds correct. When the for statement is executed, the first expression assigns a value to i (in this case, 10). The second expression is a comparison. It will evaluate to true if i is greater than or equal to 0 (which it is, as we just set it to 10). Because the condition evaluates to true, the loop body is executed. After that, the third expression runs, decrementing the value of i, and that process is repeated until the condition evaluates to false (when i reaches 0).
By changing the condition to i <= 0, it will evaluate to false the first time around, so the loop body will never execute.
The exact behaviour is detailed in the ECMAScript specification, in the section on "the for statement".
Imagine a set of stairs, 10 steps.
--
| i = 10
--
| i = 9
--
| i = 8
--
| i = 7
--
| i = 6
--
| i = 5
--
| i = 4
--
| i = 3
--
| i = 2
--
| i = 1
--
| i = 0
Imagine you are climbing down the stairs, in your head, you subconsciously think: "Until I get down to the bottom-most step, I'll keep stepping down".
Similar to the for loop:
for (i=10; i >= 0; i--)
This says, I start from the top-most, the 10th step as depicted in the image, then you climb down one step each time (or iteration) i--, then everytime after you step down, you check, "Am I at the bottom of the stairs already? No? Keep going", that's when you check i >= 0
Hope that helps you out of your desperation ;)
I think your problem is the semicolon extra in the loop:
this is your code:
for (i=10; i>=0; i--;)
try this:
for (i=10; i>=0; i--)
Maybe that's the reason for the loop is not printing.
for (i=10; i>=0; i--) means this:
start with i=10
if not i>=0 then execute. This is the "stop" condition.
after each loop do: i = i-1
On this example you won't enter the loop because the repeat condition fails.
Hello ok first "i=10" and
i>=0
is the condition for the loop. So everytime the i is greater or equal to zero the loop is returning continueing. Since you are using i-- so when i becomes negative less then zero the loop will stop.
if you use
i<=0
the condition for the loop is false so it won't enter the loop to execute the code inside bracket
Yes, if you were to change
for (i=10; i>=0; i--)
to
for (i=10; i<=0; i--)
the first condition check is false, as i is not smaller or equal to 0, so it will not eter the loop.
The condition is checked before entering the block, but after the incrementation. The incrementation is skipped the first interation. The first time the condition is not met, the whole loop will stop completely.
So if you use i<=0, the condition is not met, and the for will stop.
If you want to skip the zero, you should have the condition i>0.
You understand correctly, the i>=0 in your for loop tells to run the loop as long as i is greater than or equal to 0.
The i-- decrements the value of i on each iteration of the loop.