Click button to get the sum of the first 12 Fibonacci numbers - javascript

I want to get and add the first 12 even fibonacci numbers and have it appear on my page when I click the button. Right now my code gets and adds the even numbers. How do I limit it to the first 12 even numbers?
Thank you in advance. http://jsfiddle.net/lakenney/oryygn4y/
// first we get the HTML for the button
var getFibSum = document.getElementById("sumFib");
//then we set the event handler for when the button is clicked
getFibSum.onclick = function(){
document.getElementById("sumFibResult").innerHTML = twelveEvenFibonacciSum();
}
/*
* twelveEvenFibonacciSum - calulates the sum of the first 12 even fibonacci numbers, with 0, 1 being the first two numbers of the sequence
*/
function twelveEvenFibonacciSum(){
/// WRITE YOUR CODE HERE
// Loop that generates Fibonacci numbers.
console.clear();
var fib = [0, 1]; //Initialize array
var sum = 0;
for (var i= 2; i <= 50; i++) {
fib[i] = fib[i-1] + fib[i-2];
var integer = fib[i];
if(integer % 2 == 0) {
// console.log("my current even fib is " + fib[i]);
var sumFibResult = sum += fib[i];
console.log("my current even fib added to sum " + sumFibResult);
}
// Loop until we have 12 even numbers
}
//console.log(fib);
return sumFibResult;
}

Add a variable to the outer scope which gets incremented each time your function is called. Return when this equals 12.
for (var i= 2; i <= 50; i++) {
fib[i] = fib[i-1] + fib[i-2];
var integer = fib[i];
if(integer % 2 == 0) {
// console.log("my current even fib is " + fib[i]);
var sumFibResult = sum += fib[i];
console.log("my current even fib added to sum " + sumFibResult);
timesIncremented++;
}
// Loop until we have 12 even numbers
if(timesIncremented >= 12) {
return;
}
}

Related

Function for happy algorithm not recurring properly

I am having trouble with my happy algorithm. The algorithm takes an input which came from my html input box. It squares the digits and adds them up. If the sum is 1, then the number is happy but if not, it checks against all of the previous sums to see if it is the same as one of them. If so, the number is unhappy. If neither then the algorithm is repeated with the new number.
//takes input value and then receives the output
function start() {
var int = document.getElementById('inp').value;
numbersChecked = [];
var value = happy(int);
console.log(int.toString() + " is " + value);
}
//recurs the funtion it doesn't work with it in the function
function unhappy(n) {
happy(n)
}
//the main function. Takes the value, adds up the squares of their digits and then checks
//to see if it is equal to one (happy) or repeats a numbers (unhappy)
function happy(n) {
n.toString();
//create|reset variables
sum = 0;
//loop through digits in string
for (var i = 0; i < n.length; i++) {
num = parseInt(n[i]);
square = num**2;
sum+=square;
}
//check numbers for repeats or return "Happy"
if (sum == 1) {
return "Happy";
} else {
for (var i = 0; i < numbersChecked.length; i++) {
if (sum == numbersChecked[i]) {
return "Unhappy";
}
}
numbersChecked.push(sum);
console.log(numbersChecked);
unhappy(sum);
}
}

Ideas for how to catch the last index in a jscript for loop, where lengh of index is is unknown?

Consider the following for loop (and assuming we don't know 3 times table - i.e. how many results might occur).
<script summary>
function myFunction() {
var output_text = "";
var i;
for (i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if ("e.g. this is the last index?") {"e.g.then do this?"
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
}
</script>
Trying to 'output_text' as something like:
The number is 0
The number is 3
The number is 6
The number is 9
The number is 12
The number is 15
The number is the last 18
Any ideas for how to catch that last loop iteration.
This is just an example as actual application is a bit wordy - but the concept is the same.
I could run a count first to get index length, but wondered if there is an easier way.
Many thanks for anyone's time. Also first go at posting - any advice welcome.
Just add 3 to the current index and check if it exceeds 19.
function myFunction() {
var output_text = "";
var i;
const max = 19;
const factor = 3;
for (i = 0; i <= max; i++) {
if (i % factor === 0){
if (i + factor > max) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
return output_text;
}
document.write(myFunction());
If you have a number divisible by 3, perform a second check to see if 20 minus i < 3 and you'll know if it's the last number.
function myFunction() {
var output_text = "";
for (var i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if (20 - i < 3) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
document.getElementById("out").innerHTML = output_text;
}
myFunction();
<div id="out"></div>
The better approach is to show result of current iteration in the next iteration. In this case, last iteration will not be handled in the loop. So, you can handle it after easily.

Push numbers into an Array, then push that Array into another Array - JavaScript

I am creating a program which takes two variables as user prompts. The first one is a starting number, the next is a number to determine a range. The program then spits out how many steps it takes for the original number entered to reach zero using the collatz function and then displays this information to the screen. It should then increment the starting number by 1 and repeat the process until starting number reaches the second inputted number
Currently i only have this working for one number, which is the original starting number. I am unsure of how to code the collatz function to run through all the numbers between the start number (first input) and the range number(second input) my guess is i will need some sort of for loop and push an array of the values (steps it takes for number to reach 0) as its own array within another array (which holds all the steps for all the numbers the program ran through)
if anyone can help with this i'd really appreciate it, thanks
var numArray = [];
function getStartNum(){
startNum = parseInt(prompt('Please enter a starting number greater than 0.'));
if(!isPosNum(startNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getStartNum();
} else {
numArray.push(startNum);
getRangeNum();
}
}
function getRangeNum(){
rangeNum = parseInt(prompt('Please enter a range value greater than 0.'));
if(!isPosNum(rangeNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getRangeNum();
} else {
collatz();
}
}
function isPosNum( number ) {
if (isNaN( number )) {
return false;
} else if (number < 0) {
return false;
} else if (number == 0) {
return false;
} else {
return true;
}
}
function collatz() {
//sets x to always be the value of the last element in the array
x = numArray[numArray.length-1];
//Sets y to the remainder of x
y = x % 2;
//if the value of y of 0, then the number is even and these calculations will be performed
if (x == 1) {
console.log('X has reached a value of 1');
createBar();
} else if ( y == 0) {
console.log('Number is even.');
z = x/2;
console.log('Value of z is equal to ' + z);
numArray.push(z);
console.log(numArray);
collatz();
} else if ( y !== 0) {
//If y is not equal to 0 then it is odd, and these calculations will be performed
console.log('Number is odd.');
z = (3 * x) + 1;
console.log('Value of z is equal to ' + z);
numArray.push(z);
console.log(numArray);
collatz();
}
}
function maxValueIndex() {
}
function createBar() {
var steps = numArray.length-1;
console.log('Number of steps taken to get to 1 is: ' + steps);
var p = document.createElement("p");
document.body.appendChild(p);
var first = numArray[0];
var output = document.getElementsByTagName("p")[0];
output.innerHTML = 'Number of steps taken for ' + first + ' to reach 1 is: ' + steps;
var g = document.createElement("div");
g.id = "graph";
document.body.appendChild(g);
for ( var i=0, n=numArray.length-1; i < n; i++) {
var line = document.createElement("p");
line.className = "line";
line.innerHTML = "|";
document.body.appendChild(line);
}
}
getStartNum();
You only need to add a function that iterate between startNum and startNum+rangeNum. In this iteration you can restart numArray with each increment of startNum and call the collatz function to calculate all the steps.
You can see the modification of your code running on:
https://jsfiddle.net/kqcebswv/
I hope this helps you.
If you need to do this generating an array of arrays you can do this:
collatzArray = [];
for (var i = startNum; i <= startNum + rangeNum; i++) {
collatzArray.push([i]);
}
then you can access each numArray iterating the collatzArray:
for (var i = 0; i < collatzArray.length; i++) {
numArray = collatzArray[i];
collatz();
}
but I think this solution si more complex.

Repeated Number count result in Ascending order

i was trying to get counted result in Ascending order
The following is my code
var NewArray = [1,4,5,2,1,3,4,2,4,5,6,4,2,1,7];
var SortNewArray = NewArray.sort();
var SortNewArrayLength = SortNewArray.length;
var prev = SortNewArray[0];
var count = 1;
for(var i =0; i<SortNewArrayLength; i++)
{
if(SortNewArray[i] == prev)
{
count++;
}
else
{
console.log(SortNewArray[i] + " comes " + count + " times ");
prev = SortNewArray[i];
count = 1;
}
}
this is output i am getting
whatever i marked in red color. i want those count in ascending order
Please anyone can help me out?
var NewArray = [1,4,5,2,1,3,4,2,4,5,6,4,2,1,7];
var counts = {};
// first collect the count of each number
NewArray.forEach( function(n){
if( counts[n] ){
counts[n] += 1;
}
else {
counts[n] = 1;
}
});
// now counts = { 1:3, 2:3, 3:1, 4:4, 5:2, 6:1, 7:1 }
// get the keys (unique numbers from NewArray) and sort them by their values (count)
var keys = Object.keys( counts ).sort( function(a, b){
return counts[a] > counts[b];
})
// print key:value pairs sorted by value
keys.forEach( function( n ){
console.log("%s comes %d times", n, counts[n] );
})
/*
3 comes 1 times
6 comes 1 times
7 comes 1 times
5 comes 2 times
1 comes 3 times
2 comes 3 times
4 comes 4 times
*/
http://jsfiddle.net/s384qq66/
Change var count = 1; to var count = 0; and change
console.log(SortNewArray[i] + " comes " + count + " times ");
to
console.log(SortNewArray[i-1] + " comes " + count + " times ");

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Categories

Resources