How to store the result of each iteration of a for loop into an array (Javascript) - javascript

This question could also be (depending on how you look at it) - How to use a for loop to do a basic math operation that adds up the sum of the multiples of 3
So I am doing Problem 1 of Project Euler.
I've (already) hit a steel-reinforced wall. I could use some help - with just a specific portion of the problem please (I am not looking for just an answer to the problem, but rather, an answer to my specific problem so I can carry on with trying to solve the remainder problem using any answer you guys provide me here)...
Anyways.
I (think I) created a for loop that will give me the multiples of 3. However, I'm trying to store the result of each iteration of the for-loop so that it adds up to the sum of those multiples i.e. I'm trying to store the result from each iteration of the loop - whether it be into an array or into a variable that takes the sum of the multiples - it doesn't matter to me - I wouldn't mind learning both methods.
I'm sure this sounds kind of confusing so let me paint my picture w/ an example...
I have a for-loop:
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i * 3);
WHAT DO I DO NEXT????
^ So I would think that this gives me x with a value of 3 upon the 1st iteration of the loop, x with a value of 9 on the 2nd loop, and x with a value of 18 on the final loop. That's correct, right? (if this were returning 18 I don't think I would need to store the values of each iteration into an array)
1st iteration:
i = 1; x = 0
Original equation...
(i * 3) + x
So...
(1 * 3) + (x = 0) = 3
So after completion of the 1st loop, x has a value of 3, right???
(Question: How would I store this value of x (which is 3) - how would I store it in an array while in this stage of the for loop?)
2nd iteration of loop:
i = 2; x = 3
(2 * 3) + (x = 3) = 9
(same question as before: how would I add this value to an array?)
3rd iteration:
i = 3; x = 9
(3 * 3) + (x = 9) = 18
Q: shouldn't this be the final value of x upon completion of the for loop??? For some reason, when I run the code, the final value of x is 9, and not 18
So, basically I am trying to add the sum of the 3 values...But what do I do next? I thought my for loop would add the result of the equation after each loop to x, but instead of ending up w/ 18 (the sum of 3 + 6 + 9), x's value was 9???
Should I use an array? If so, I'm thinking I could add the return value to an array, but I'm not sure how to add the result of each iteration of the loop to an array. Maybe the following?...
for (i = 1; i <= 3; i++) {
var array = [];
x = 0;
x += (i *3);
array.push(x);
};
^ I tried running that in jfiddle, but it would only add the last value of x (9) into the array... So how would I add the value of x to an array after each iteration of the for loop??? And I'm not seeing what's wrong with my for-loop to where it's returning a value of x as 9?
Also, I'm assuming the euler problems get significantly more difficult as we progress? If so, I've got a TON of work/practice to do....
THANKS IN ADVANCE...

Just create the array once, and push the result at each iteration to the array:
var array = [];
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i *3);
array.push(x);
}
Or for that matter, just use this:
var array = [];
for (i = 1; i <= 3; i++) {
array.push(i *3);
}
Or to simply get the sum of the factors, use this:
var x = 0;
for (i = 1; i <= 3; i++) {
x += i *3;
}

You are declaring var x = 0 and var array = [] at every step of the loop, try something like:
var array = [], x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}

You can use like this:
and you have to define X out of the loop
var array = [],
x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}

Related

How to Create a For-Loop that calculates 6Factorial

To do this you must multiply 6*5*4*3*2*1. To verify your loop is working correctly, the value you are looking for as a result is: 720
var dvDDG = document.querySelector("#ddg");
for(var i = 0; i < 7; i++) {
//remainder..
if( (i*7) == 720 ) {
dvDDG.innerHTML += i + "<br />";
}
}
I'm not entirely certain what you're trying to do with the code you have, it will simply check all numbers zero through six inclusive, and output the value which, when multiplied by seven, is equal to 720.
Since the highest value you'll get is 6 x 7 = 42 (nowhere near 720), you'll see nothing.
The pseudo-code for what you're after would be along the lines of:
fact = 1
for i = 2 to N inclusive:
fact = fact * i
print fact
Turning that into Javascript (or any procedural language for that matter) should be fairly simple, such as with:
function fact(n) {
res = 1
for (var i = 2; i <= n; i++) {
res = res * i;
}
return res
}
alert(fact(6))
It's fairly simple:
var factorial = 1;
var num = 6;
for (var i = 1; i <= num; i++){
factorial *= i;
}
There you go, your answer is the variable factorial. Just copy it into any output function you want. Be careful though, factorial can get pretty huge very fast. Try not to experiment on numbers that much larger that 6.

Perfect squares from odd numbers

In JavaScript, is there a more efficient way of calculating perfect squares working from odd numbers than this (the last perfect square stored in the array perfectSqrs is console.logged):
let n = 999,
oddNums = [],
i;
for (i = 3; i < n; i += 1) {
if (i % 2 !== 0) {
oddNums.push(i);
}
}
let oddLength = oddNums.length;
let perfectSqrs = [1],
j = 0;
while (j < oddLength - 1) {
perfectSqrs[j + 1] = perfectSqrs[j] + oddNums[j];
j += 1;
}
console.log(perfectSqrs[perfectSqrs.length - 1]);
Looks like you just want to generate an array of perfect squares? Perhaps you can do something like this:
var squares = [1];
var numSquares = 100;
for (var i=3; i<numSquares*2; i+=2) {
squares.push(squares[squares.length - 1] + i);
}
console.log(squares);
For people unclear about this algorithm, basically:
1
4 (1+3)
9 (1+3+5)
16 (1+3+5+7)
25 (1+3+5+7+9)
Perfect square is essentially the sum of odd numbers
Nothing to do with JS more with algorithms and logic. You can totally avoid the first loop and also avoid storing (memory efficiency) odd numbers. Start your second loop with 1 and iterate by incrementing by 2 instead of 1 (1,3,5,7,...).

Javascript Euler Fibonacci for loop

I'm doing the Euler project problem 2 in which the objective is to sum the even numbers of the fibonacci sequence that have a value of less than 4 million. I've searched a bit and I've seen several solutions using a while loop but nothing simple using a for loop. I'm curious why I'm returning zero with the following code:
var array = [];
array[0] = 0;
array[1] = 1;
var total = 0;
for(var i=2;total<=4000000;i++) {
array[i] = array[i-1] + array[i-2];};
for(var x=0;x<array.length;x++){
if(array[x]%2 === 0){
total += array[x]};};
alert(total);
I'm guessing the problem is in my for loop using the total variable. I couldn't get it to work using array[i]<=4000000 either and I'm really curious behind the why here. Anyone know why this is? What can I change in the for loop condition (second statement) to get a correct total here?
First of all there is an infinite loop at first for. Your condition must be array[i-1] < 4000000. After that your second for loop will find the correct result.
Also for the problem, you don't need to store all fibonacci numbers then find sum of even numbers.
You can calculate sum when calculating fibonacci.
var first = 0;
var second = 1;
var sum = 0;
for(var current=first+second; current < 4000000; current = first+second){
if(current%2 === 0){
sum+=current;
}
first = second;
second = current;
}
I fixed it for you.
var i, data = [ 0, 1 ], total = 0;
for (i = 2; i <= 4000000; i++)
{
data[i] = data[i - 1] + data[i - 2];
if (data[i] % 2 === 0)
{
total += data[i];
}
}
alert(total);
I'm not sure what you termination condition should be like, you say have a value of less than 4 million, but this is ambiguous. Maybe it should be total <= 4000000 or data[i] <= 4000000. Your phrasing is not precise enough.
Sorry but for me your code going in a dead loop. first "for" use total as check but it's never incremented. If you want This is a solution for fibonacci sequence based on dinamic programming with memoization tecnic.
var f1 = 1;
var f2 = 1;
for(var i = 2; i < 40000; i++){
console.info(i, f1, f2);
var temp = f1 + f2;
f1 = f2;
f2 = temp;
}
alert(f2);

Get index of array at equal points

Let's say you have an array of length 20. You want to access 3 equally spaced indices: 0, 9, 19.
How can you do this with any length of array and any number of sections?
I feel like there must be an elegant way of doing it, but the only way I can think of is finding the section size (var len = 20 / (3 -1)), iterating over the total number of sections (for (var i = 0; i < 3; i++) { var row = data[len * i]; }), and then subtracting one for non-zero indices.
You could try something like this (where console.log is used now you can call your array):
var amount = 3;
var total = 20;
var size = (total - 1) / (amount - 1);
for(var i = 0; i < amount; i++) {
console.log(Math.floor(size * i));
}
There isn't realy a more elegant solution.

Why am I getting NaN here when I'm just accessing an array?

var inc = .001;
var z = new Array(1.0/inc);
for (var x = 0.0; x < 1.0; x += inc) {
z.push(Math.cos(x));
}
var y = new Array(1.0/inc);
for (x = 0.0; x < 1.0; x += inc) {
y.push(1 - ((x * x) / 2) + ((x * x * x * x) / 24));
}
var sum = 0;
for (var i = 0; i < (1.0/inc); i++) {
sum += y[i] - z[i];
}
console.log(sum);
console.log(sum/(1.0/inc));
I'm pretty new to Javascript, but the arrays here are filled with floats and when I take the difference and try to print them it returns NaN. I'm stumped here. Here's a fiddle with the code (http://jsfiddle.net/2v7wu/). Thanks!
You're creating arrays that consist of 1000 empty values, and then pushing extra elements onto those. Your arrays end up 2000 elements long, of which you iterate over the first (empty) 1000.
You don't need to declare the length of arrays in Javascript, so just using
var z = []
var y = []
will be fine.
Finally, you need to change your array index in the last loop to
sum += y[i] - z[i];
Because you're using x where you mean to be using i:
for (var i = 0; i < (1.0/inc); i++) {
sum += y[x] - z[x];
// ^------^--------- these should be i, not x
}
See also Gareth's point below, which relates to my side note #2 below. By starting out with an initial length and then using push, you're not putting things where you think you are. :-)
Two side notes:
You're constantly re-evaluating 1.0/inc. I recommend doing that once and storing it in a variable.
In JavaScript, there's rarely any reason to write new Array(length). Just use var z = []; and var y = []; These arrays aren't really arrays at all and they'll "grow" as needed (but again, without lots of memory reallocations, because they're not really arrays).
In your third loop, you're trying to use the floating point value x as an index into y and z. This produces the result undefined, and undefined - undefined evaluates to NaN.
Presumably, you meant to use i as the index.

Categories