Creating and initializing arrays - javascript

I'm learning about Javascript arrays. I understand most of the code, except line 4. Can you please explain what the code in line 4 does, and how it has this output.
var fibonacci = []; //{1}
fibonacci[1] = 1; //{2}
fibonacci[2] = 1; //{3}
for(var i = 3; i < 20; i++){
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2]; ////{4}
}
for(var i = 1; i<fibonacci.length; i++){ //{5}
console.log(fibonacci[i]); //{6}
}
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
Thank you.

it's Fibonacci sequence. How it works? every number after the first two is the sum of the two preceding ones that's why you have to initialize the first two terms
fibonacci[1] = 1;
fibonacci[2] = 1;
on line 1 you create the array and after intializing the first two terms you loop, starting from the third index var i = 3 to fill the array fibonacci with all the terms of the sequence. How? it assigns the sum of the two previous terms to the current one.
ps: in javascript arrays start at index 0

At Line 2 & 3 you set the values for item 1 & 2. Since fibonacci is sum of two values before, the line 4 just sums up the two values before for each element from 3 to 19.

Related

Find the largest sequence of five numbers in a string in Javascript

HI everyone hopefully an easy one. I have split a string example below in to 5 digit blocks I now need to find the largest 5 number sequence, and not sure how to do this any help much appreciated. "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895
function solution(digits){
let output = digits.match(/.{1,5}/g);
console.log(output);
}
This approach (of splitting into chunks of 5), will not always give the optimal result, as you are not looking at every possible chunk of 5... only those that start at an index that is a multiple of 5.
So just iterate through every array index, and then take 5 characters from there, and compare...
let str = "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895";
let best = "";
for (let i = 5; i <= str.length; i++) {
let slice = str.slice(i - 5, i);
if (slice > best) best = slice;
}
console.log(best);

Not every number are shown, when their sum of the divisors are good for the conditions

I did a bit of coding in javascript and I don't understand the problem...
My goal is to get every divisor of a given number and check if the sum of them is greater than the number itself.
The divisors should include one, but not the number itself.
I made 2 functions to separate the code and make it more readable for now.
In the first 12 number, the condition apply only for the number 12 because 1+2+3+4+6=16 which is greater than 12 and it shows it correctly, but when I try the function with the first 20 number, only 18 and 20 are shown, when 12 is clearly good. It disappears when the loop reaches the number 16.
Here is my code:
function getDivisors(n){
var divisors=new Array();
for(var x=1;x<n;x++){
if(n%x==0) divisors.push(x);
}
return divisors;
}
function getNumbers(n){
var numbers=new Array(),
sum=0;
for(var x=1;x<=n;x++){
sum=getDivisors(x).reduce((a, b) => a + b, 0);
if(sum>n) numbers.push(x);
console.log("Number: "+x+" sum:"+sum);
}
return numbers;
}
console.log(getNumbers(20));
You should have if (sum>x) instead of if (sum>n) inside the for loop in getNumbers(n).

Javascript: Basic for loop?

I just completed some form of a competency exam for a programming school, and I got every question correct except this, although it appears really quite easy, yet I couldn't get it. Any ideas?
Observe the code below.
var x = [1,5,7,13];
for(i=0; i < x.length; i++)
{
x[i] = x[3-i] + 2;
}
Once the program is done, what would be in x?
a [3,7,9,15]
b [15,9,11,3]
c [15,9,7,3]
d [15,9,11,17]
The answer is d
first loop
x[0] = 13 + 2 = 15
second loop
x[1] = 7 + 2 = 9
third loop
x[2] = 9 + 2 = 11
fourth loop
x[3] = 15 + 2 = 17
x = {15, 9, 11, 17}
To figure this out, you'll have to understand that x[] is used to refer to a specific index of the array. For example:
var x = [5,6,7];
In this case, x[0] would be equal to 5, assuming a 0-index based array.
Knowing this, let's break down your loop. We'll start by filling in the variable name instead of the variable value step by step, to leave out confusion of following variables in your head.
var x = [1,5,7,13];
for(0=0; 0 < x.length; 0++)
{
x[0] = x[3-0] + 2;
}
For the first iteration, everything starts to become a little clearer as you can tell that now it's setting x[0] (the first value in the array) to equal x[3-0] (which would be x[3], which in turn would be 13 due to the 0-index array), plus 2. 13 + 2 = 15. The first number is 15.
var x = [1,5,7,13];
for(1=1; 1 < x.length; 1++)
{
x[1] = x[3-1] + 2;
}
Let's try one more! x[3-1] is the same as x[2] which is 7; 7 + 2 = 9. Your second number is 9.
Following the same logic you can see how the loop functions and understand how it's referencing the array's values.
The key here is that you're updating the same array you're reading from as you go through it. (Note: generally I'd consider this bad practice and I've seen a lot of programmers fall into this trap - it's very easy to misunderstand the code).
First thing to realize is that x[3-i] basically reads the opposite end of the current index. To be more generic, it should really have been x[(x.length-1)-i] but the 3 is hardcoded in this case.
Now, the first round is easy: 13+2 = 15. 13 because the opposite end of the first element is the last element:
x = [15,5,7,13]
▲ │ this+2
└──────┘
In the second round we replace 5 with 7+2 = 9:
x = [15,9,7,13]
▲ │ this+2
└─┘
In the third round we find ourselves doing something not initially obvious. Instead of replacing 7 with 5+2 we replace it with 9+2 instead because we've already replaced 5 with 9:
x = [15,9,11,13]
│ ▲
this+2 └─┘
Now finally we replace the last element with 15+2 using the same reasoning above:
x = [15,9,11,17]
│ ▲
└───────┘
this+2

Using a for loop and document.getElementById to populate an array in Javascript

I have been trying to populate an array using a for loop and taking such values using document.getElementById("spin " + i).value;
The ids on my html for every input tag go from spin1 to spin18.
Any suggestions on what I am doing wrong? Or what I can change?
var nums = [];
for(var i = 1; i <= 18; i++){
var num[i] = parseInt(document.getElementById("spin" + i).value);
nums.push(num[i]);
}
alert(nums.length);
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.
The js looks compilable, but here are some pointers.
The number 0 is before 1
It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
Avoid unnecessary variables
Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.
var nums = [];
for( var i = 0; i < 18; i++ ) {
nums[i] = parseInt( document.getElementById("spin" + i).value );
}
Don't push, insert
The push method has an expensive overhead so use it with caution.
Loggers
The console has a built in logger, why not use that instead of an alert box?
console.log( nums.length );
try this
var nums = [];
for(var i = 1; i <= 18; i++){
var num= parseInt(document.getElementById("spin" + i).value);
nums.push(num);
}
alert(nums.length);
A couple of things to note:
As PSR has mentioned, you use:
var num[i]
when it should be
var num
getElementById(id).value only works for form elements, you have to use .innerHTML for divs.
This works for me: http://jsfiddle.net/sbqeT/

Nested While Loop

I am having trouble getting this nested while loop to work. I am using a Javascript based program that reads from 2 table columns based on the Header of the table. I am able to read from the tables but the loop is not working. My goal is to find when the neutral size of a wire becomes larger than the phase size and print the wire size at which this occurs. The code is as follows.
CSA = 130
NeutCSA = 0
i = 0
j = 0
while (NeutCSA < CSA){
j = 0
while (NeutCSA < CSA){
NeutCSA = colWireSize[i] * colNumberWires[j]
if (colNumberWires[j] < 18){
j = j + 1
}
}
if (colWireSize[i] < 10){
i = i + 1
}
}
result = colNumberWires[j]
The tables look like this
colWireSize
2
3
4
5
6
7
8
9
10
colNumberWires
6
7
8
9
10
11
12
13
14
15
16
17
18
The program will find the condition and end the loop but not in the order I need it to. I need it to start at the first row of WireSizes and then loop through and multiple that value by NumberWires. If this value is less then CSA, go to the next WireSize and repeat the process until NeutCSA > CSA.
Thanks
Pat
Your outer loop does not loop as the inner loop will always advance NeutCSA to >= CSA.
Did you mean to set the exact same conditional for each loop?

Categories

Resources