In javascript I came across this code from a tutorial website and the answer that was given was 900 but I have 109 for the answer. Please explain how do you get the answer and what are the steps taken.
var amount = 0;
var i = 1;
while (I<10) {
amount = amount + 100;
I++;
}
alert("The value is:" + amount);
it is indeed 900. btw, your I should be lowercase i in the while loop.
so amount=0 at the start and i=1.
then you enter the while loop if i < 10, which it is cause i=1 at this point.
then the inside of the loop gets executed: amount becomes 100 because 0+100 = 100
then i gets incremented, so i is now 2 and the loop happens again and again til i becomes 10 in which it exits the loop since 10 is not less than 10.
you'll find that this loops "insides" executes 9 times, (adding 100 to the value of amount each time) giving the final total of amount = 900
var amount = 0;
var i = 1;
while (i<10) {
amount = amount + 100;
i++;
}
alert("The value is:" + amount);
You can analyze this by walking through it line by line and listing out the values at each line.
(I'm assuming s/I/i/ - JavaScript is case-sensitive. If it wasn't just a typo or copy/paste error, you will likely get an error.)
Line 1: amount = 0
Line 2: i = 1
Line 3: i<10, so go to line 4.
Line 4: amount = 100, i = 1
Line 5: amount = 100, i = 2
Line 6: i<10, so go to line 4
Line 4: amount = 200, i = 2
Line 5: amount = 200, i = 3
etc., which is how you end up at amount = 900.
Related
This is what I need to do:
The snail climbs up 7 feet each day and slips back 2 feet each night.
How many days will it take the snail to get out of a well with the given depth?
Sample Input:
31
Sample Output:
6
Explanation: Let's break down the distance the snail covers each day:
Day 1: 7-2=5
Day 2: 5+7-2=10
Day 3: 10+7-2=15
Day 4: 15+7-2=20
Day 5: 20+7-2=25
Day 6: 25+7=32
So, on Day 6 the snail will reach 32 feet and get out of the well at day, without slipping back that night.
This is the code I have written so far:
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
}
Please help me, I'm like really stuck.
This is a pretty simple question,
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
i = 0;
for (; depth > 0;) {
i++;
depth -= 7
if (depth > 0) {
depth += 2
}
}
console.log(i);
}
What this code basically does is:
It sets a i variable which is 0, than when the depth is bigger than 0, 1 is post incremented by 1 -which means 1 is added to it- this will count the days it will take. But we must consider the nights as well, as it says, it will not fall down the night if it climbs it all in the day. Thus, we put another + 2 if the -7 doesn't make it 0.
You can read about for loops here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
I have noticed you're new to stack overflow, so please for the next time you ask, do some coding and research on your own. You mentioned you coded some bits but you just stated a function which is just same as writing nothing and asking for an answer -stack overflow is not your homework solving site!-
In a day and a night, a snail gains a total of 5 feet. The catch here is that this gain is made up of gaining 7 feet, and then slipping back 2. Another way to think about it is that the goal is 2 less than the actual goal, but advances 7-2=5 feet per day.
To formulate this to Javascript, you need to subtract 2 from the distance, divide it by 5, and ceil the result to get the number of days as an integer:
function numDays(distance) {
return Math.ceil((distance - 2) / 5);
}
function main(distance) {
var depth = parseInt(distance);
//your code goes here
var day = 0;
var total = 0;
while(total<depth){
day = day + 1;
total = total + 7;
if(total >= depth){
console.log(day);
break;
}
total = total - 2;
}
}
main(32)
main(51)
This question pretty simple but tricky ;
The depth is already defined which is " var depth = parseInt(readLine(), 10);"
So you don't have to worry declaring depth again depth.
So we need to declare variable for day and total distance at start which is
var day = 0 ; and var total = 0 ; .So here the solution :
function main() {
var depth = parseInt(readLine(), 10); //defining depth
//your code goes here
var day = 0; //defining day
var total = 0; // distance which is at zero
while(total<depth){
day += 1;
total += 7; // if the total distance is less than depth of the well the day is added by one and distance is added by 7
if(total >= depth){
break; // but if the total is equal to or greater than depth the loop will break
}
total -= 2; // 2 is deducted from every step in loop except when the loop is about to ends(where the loop breaks when total=depth).
}
}
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
var result = depth / 5;
console.log(Math.round(result));
}
well this is problem number 12 on projecteuler website:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
and here's my code (I'm new to Javascript)
let num = 1;
let add= 1;
let divisors = [];
while (divisors.length < 500){
divisors = []
for(let i = 1; i <= num; i++){
if(num % i == 0){
divisors.push(i);
}
}
add ++;
num += add;
}
console.log(num - add)
this code run fine when I change the while loop condition to 300 or less.
and this code running on Intel i7 Q740 1.75GHz.
when I try it nothing shows up on console and my question is that's because of my CPU and lack of power or my code has issue? I wait about 20 mins and still nothing as result.
This code is not very efficient as #Vasil Dininski pointed out but you won't reach the max Integer you just have to wait a while for your program to calculate.
I would recommend to optimize your code e.g. by writing a simple function which returns your number of divisors for your current number.
This could look similar to this:
function numberOfDivisors(num) {
var numOfDivisors = 0;
var sqrtOfNum = Math.sqrt(num);
for(var i = 1; i <= sqrtOfNum; i++) {
if(num % i == 0) {
numOfDivisors += 2;
}
}
// if your number is a perfect square you have to reduce it by one
if(sqrtOfNum * sqrtOfNum == num) {
numOfDivisors--;
}
return numOfDivisors;
}
Then you could use this method in your while loop like this:
var maxNumOfDivisors = 500;
var num = 0;
var i = 1;
while(numberOfDivisors(num) < maxNumOfDivisors) {
num += i;
i++;
}
which would return you the correct triangular number.
Please also note that triangular numbers start at 0 which is why my num is 0.
As you might have noticed, this algorithm might be a bit brute-force. A better one would be combine a few things. Let's assume the number we're looking for is "n":
Find all prime numbers in the range [1, square root of n]. You will
be iterating over n, so the sieve of
eratosthenes
will help in terms of efficiency (you can memoize primes you've already found)
Given that any number can be expressed as a prime number to some power, multiplied by a prime number to some power, etc. you can find all the combinations of those primes to a power, which are divisors of n.
This would be a more efficient, albeit a more complicated way to find them. You can take a look at this quora answer for more details: https://www.quora.com/What-is-an-efficient-algorithm-to-find-divisors-of-any-number
If my calculation is not wrong, you add one more to each next divisor from previous divisor and you get final result.
let prev = 0;
for(let i=0; i < 500; i++) {
prev = prev + i;
}
console.log("AA ", prev);
I want to assign a level to a number as below:
If a number lies between 3 and 3+3^2 Level should be 2.
If a number lies between 3+3^2 and 3+3^2+3^3 Level should be 3.
If a number lies between 3+3^2+3^3 and 3+3^2+3^3+3^4 Level should be 4.
....
And so on...
I am trying this..
var level = (next_slot>3 && next_slot < 3+3**2)?1:(
(next_slot>3+3**2 && next_slot < 3+3**2+3+3**3)?2:(
next_slot>3+3**2+3**3 && next_slot < 3+3**2+3+3**3)?3:(
4
))
Which seems complex and also there is no limit to it.
Is there any better way to solve this in javascript?
Use logarithm, Luke:
level = Math.ceil(Math.log(x) / Math.log(3))
One solution would be to make a for loop with some max constant and then exit when you find that you're in between the values
const checkLevel = function(number) {
if (number <= 0) {
return 0 // failsafe since 3^0 is 1
}
const max = 10
for (let i = 0; i < max; i++) {
let low = Math.pow(3,i)
let high = Math.pow(3,(i+1))
console.log('our low is ' + low + ' and our high is ' + high)
console.log('lets check if ' + number + ' is between')
if (number >= low && number < high) {
console.log('it matches')
return i+1
} else {
console.log('no match, lets continue')
}
}
}
const level = checkLevel(4)
console.log('level',level)
What we are doing here is:
Start from 0
Create our low value 3^0
Create our high value 3^1
Check if our number is between
Return it if that's the case
Otherwise continue
Next it will check 3^1 and 3^2 and so forth
From your latest edit it looks like this is no longer possible to do with logarithms, so you will need to count up instead:
function findLevel(input) {
let level = 1;
let limit = 3;
let increment = 3*3;
while (input > limit) {
++level;
limit += increment;
increment *= 3;
}
return level;
}
You didn't specify the behaviour for the limits themselves, i.e. whether 3 belongs to level 1 (the 0-3 range) or 2 (the 3-12 range). This assumes that it belongs to the lower level, i.e. 3 is on level 1 not 2. Change input > limit to input >= limit if that's incorrect, i.e. 3 is on level 2.
// Print the inclusive integer ranges for each level
let lastLevelStart = 0;
let lastLevel = findLevel(lastLevelStart);
for (let i = 1; i <= 10000; ++i) {
let level = findLevel(i);
if (level != lastLevel) {
console.log(`level ${lastLevel}: ${lastLevelStart} to ${i-1} inclusive`);
lastLevel = level;
lastLevelStart = i;
}
}
level 1: 0 to 3 inclusive
level 2: 4 to 12 inclusive
level 3: 13 to 39 inclusive
level 4: 40 to 120 inclusive
level 5: 121 to 363 inclusive
level 6: 364 to 1092 inclusive
level 7: 1093 to 3279 inclusive
level 8: 3280 to 9840 inclusive
This obviously takes the output level number of loops to compute, and when reused will end up repeatedly computing the same limit values over and over again (albeit using integer maths only, so relatively cheaply). So if you call this a very large number of times or need to deal with more than a small number of levels then you may want to compute the upper bounds for the first 1000 levels (say) into an array and then just scan that to find the level, or even binary search that array to find the answer in a more constant time (checking first that the input is <= the top precomputed value, and falling back to this method if not).
When running the code below, the text inside the document.write runs 8 times and not 7 times as I was expected.
If I understand correctly, increment by 2 should display the positions:
20+2, 22+2, 24+2, 26+2, 28+2, 30+2 and 32+2.
Based on the results I get I assume it also displays the 34+2, which is 36. What I am missing? Thank you.
x = 20;
for (x = 20; x < 35; x += 2) {
document.write("How many times will this loop execute?" + "<br/>");
};
As noted in the comments above, The loop is correct in running 8 times. Since no one stated the reason, it is this: the x+=2 happens at the end of the loop, not at the beginning. So the loop will run for 20, 22, 24, 26, 28, 30, 32, and 34.
You are misunderstanding how the for loop works.
for ([initialization]; [condition]; [final-expression])
final-expression: An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
So your counter gets incremented at the end of the loop and the observed behaviour is correct. The loop gets executed for 20, 22, 24, 26, 28, 30, 32, and 34.
When start loop add +2 to x like below:
x = 20;
for (x = 20+2; x<35; x+=2) {
document.write("How many times will this loop execute?" + "<br/>");
};
fiddle
Script:
x = 20;
count = 1;
for (x = 20; x < 35; x += 2){
document.write("Execution: "+ (count++)+ "<br/>");
};
Output
The loop executes total 8 times.
Execution: 1
Execution: 2
Execution: 3
Execution: 4
Execution: 5
Execution: 6
Execution: 7
Execution: 8
jsfiddle link to checkout.
Yes, is executing 8 times, because is from 20 to 35 in 2 x 2
x = 20;
for (x = 20; x < 35; x += 2) {
document.write("Execute for " + x + " " + "<br/>");
};
/*
OUTPUT:
Execute for 20
Execute for 22
Execute for 24
Execute for 26
Execute for 28
Execute for 30
Execute for 32
Execute for 34
*/
If you want 7 times, you can change to 34
x = 20;
for (x = 20; x < 34; x += 2) {
document.write("Execute for " + x + " " + "<br/>");
};
It will run eight times, x iterating through every even number between 20 and 34 inclusive. You can write it like this if it helps:
var x = 20;
while (x <= 34) {
// do something
x += 2;
}
However, it is important to note that after the loop has run (whether you're using the for or while version), x will equal 36, since it is incremented to that before it finally fails the test; inside the loop, x will never equal 36. In terms of best practice, you should only really use a counter variable like x within the loop; this can be enforced by using the ES6 let keyword (which is block-scoped) like so (the example just prints out a list of the x values as DOM elements):
function appendSpanCounter(i, end) {
let el = document.createElement("span"),
content = i.toString(10);
if (i < end) content += ", ";
(typeof el.textContent === "string") // ternary operator
? el.textContent = content
: el.innerText = content;
(document.body || document.querySelector("body")).appendChild(el);
}
for (let x = 20; x <= 34; x += 2) {
appendSpanCounter(x, 34);
}
// x is now undefined here
Purpose: A user can choose a Product Type and variation of that Product Type. I need to track every Product Type added and how many variations were added. For Example,
item 1: Shirt > Long Sleeve (1)
item 2: Shirt > V neck (3)
item 3: Pants > Jeans (1)
The total amount pertains to the variation of the product. I'd like to have something happen whenever a user selects 4th variation of the same type. For this example, I want something to happen to the Product type Shirt, as currently long sleeve + v neck = 4
I have two nested loops. First one is looping through each product type, and inner loop should loop through each variation and get the sum.
This is a good starting point but I can't seem to get passed the for loop to check for every nth value of the total # of variations.
jQuery('.product').each(function(i, objP){
var sum = 0,
min = 4,
max = 5;
jQuery(objP).find('.product-variation-quantity').each(function(ii, objC){
sum += parseInt(jQuery(objC).text());
return sum;
for ( var x = 0; x < min * max; x += min) {
if ( sum == x ) {
var sum_id = jQuery(objP).attr('id');
console.log(sum_id);
//product quantity has reached min to pass
}
else {
//has not reached min
}
}
});
});
Any help?
note: objP and objC are used to track the contextual this
note2: to clarify: on every 4th, 8th, 12th etc value, something will happen, not every 4th, 5th, 6th
First of all, you have a bug in your code, it's where you return sum; in the nested loop. The for loop after this will never execute.
I suggest this code:
jQuery('.product').each(function(i, objP){
var sum = 0,
min = 4,
max = 5;
var ind = 1;
jQuery(objP).find('.product-variation-quantity').each(function(ii, objC){
sum = parseInt(jQuery(objC).text());
if (sum > 0 && sum % 4 == 0) {
// Do something
}
});
});
Here's codepen sample.
What about this: in case 8 items of the same variation are selected, the console will read
[id] has crossed 2x4 items
Code:
jQuery('.product').each(function(i, objP){
var min = 4,
max = 5,
sum_id;
jQuery(objP).find('.product-variation-quantity').each(function(ii, objC){
var count = parseInt(jQuery(objC).text());
if ( count < min ) {
//product quantity has not reached min
}
else {
// product quantity has reached min to pass
sum_id = jQuery(objP).attr('id');
console.log(sum_id + ' has crossed ' + min + 'x'
+ Math.floor(count/min) + ' items');
}
});
});