Fibonacci calculator steps - javascript

Everything work but I have a question on this Fibonacci calculator (see in-code comment). Could I skip the console.debug step? Why is it needed?
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function(){
document.getElementById("sumFibResult").innerHTML = fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum(){
/// WRITE YOUR CODE HERE
var first,second,add;
for(var i=0;i<50;i++){
if(i === 0){
first = 1;
second = 2;
}
/** Why do I have to do the following to make it work?:*/
if(first+second > Number.MAX_VALUE){
console.debug(i, first, second);
return;
}
add = first + second;
first = second;
second = add;
}
return(add);
}
Or would this other way be the most efficient way to write the Fibonacci function to calculate the sum of first 50 numbers:
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function(){
document.getElementById("sumFibResult").innerHTML = fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum(){
/// WRITE YOUR CODE HERE
var first,second,add;
for(var i=0;i<50;i++){
if(i === 0){
first = 1;
second = 2;
add = first + second;
first = second;
second = add;
}
return(add);
}

Number.MAX_VALUE is the maximum value your system can address and that part of code actually stops the script and outputs the last numbers in case you go over that max value.
Since you're doing only 50 iterations, it's highly unlikely you'll even come close to that number, so you can freely remove the whole if-clause if it bothers you.

console.debug just prints some debug information, it can be removed safely.

Related

How to get a new random number in javascript

I am very new to JavaScript and I'm sure this question has been answered quite a bit, but when I search my question I don't seem to find an answer (or one that I actually understand :D)
Currently, I'm trying to create a tool to help kids with there multiplication facts and I'm having trouble getting the program to generate new random numbers.
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
function start() {
println("Welcome to the multipilcation helper! ");
var num = readLine("Pick a number you want to practice or type 'random'!");
var ques = readLine("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var answer = r1 * r2;
println(r1 + "*" + r2);
var check = readLine("what is the answer");
if (check == answer) {
println("thats correct!");
} else {
println("thats wrong! ");
}
}
}
}
The problem is that my variables seem to pick a random number as soon as the script starts and stick with it instead of giving me a new random number.
Can anyone help me out and tell me how to get a new random number every time the variable is called?
Simply create yourself a method like the one below and use it like r() to get a new random number every call.
function r() {
return Math.floor(Math.random() * 13);
}
console.log(r());
console.log(r());
console.log(r());
In your loop you should be reassigning the random numbers so that they are reassigned every iteration of the loop. Otherwise they stay static to the value you give them at the top.
Also, you should use triple equals in Javascript when checking for equality as it is best practice.
function start() {
console.log("Welcome to the multipilcation helper! ");
var num = prompt("Pick a number you want to practice or type 'random'!");
var ques = prompt("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
var answer = r1 * r2;
console.log(r1 + "*" + r2);
var check = prompt("what is the answer");
if (check == answer) {
console.log("thats correct!");
} else {
console.log("thats wrong! ");
}
}
}
}
start()
You random numbers are being static at the moment. They need to be called again. Move your r1 and r2 assignments inside the for.
I don't have enough reputation to comment, but will update the answer
if you explain it with more details.
You need to put the random call in a function in order for it to create a new number each time. When you assign it directly to a variable as you have, it only runs once and stores that value in the variable.
// pick a number between 0 and 13
var random = function() {
return Math.floor(Math.random() * 13);
}
function start(){
for(var i = 0; i < 15; i++){
// call random function for each number and store in a var
var number1 = random();
var number2 = random();
var answer = number1 * number2;
console.log('equation:', number1 + '*' + number2);
console.log('answer:', answer);
}
}
// call the start function
start()

Evaluating Terminating Condition

I am learning javascript to enhance some of my daily work, and so I am learning the basics.
I am still pretty green with the syntax, but am picking up on the language pretty quickly.
What I am trying to understand is how i can create a terminating condition that is evaluating a function.
I know the coding is wrong here, which is what I am trying to fix - I attempted a bunch of different things, but I am having trouble evaluating the loop based on my product.
I tried using return to store the value each iteration, but every attempt resulted in the script flat out failing.
What I want the script to do is to stop the loop when my product reaches <=100.
The problem is, my research suggests that the loop criteria can ONLY be referencing the variable, i.
I'm stuck in terms of how to look at the resulting product as the terminating condition.
var one = 5;
var two = 10;
var end = 100;
function mult (one, two) {
var product = one * two;
document.writeln(product + "<br>");
}
for (var i = 1; i <= end; i++)
mult(i, two);
If you want your loop to terminate when the product is <= 100, use an if statement to decide whether you want to write a line.
I've changed some variable names to make it easier to understand.
/*var one = 5;*/ /*This is never being used*/
var ten = 10;
var end = 100;
function mult (a, b){
var product = a * b;
if (product <= 100){
document.writeln(product + "<br>");
}
}
for (var i = 1; i <= end; i++){
mult(i, ten);
}
"the loop criteria can ONLY be referencing the variable, i." that's false!
You can define multiple conditions in a for loop.
To access the 'product' variable after loop execution you can declare it in the outer scope of the mult() function (or you can rewrite the mult() function to returns the product variable).
Like this:
var two = 10;
var end = 100;
var someNumberGtThan100 = 100000;
var lastProduct = 0;
var product = 0;
function mult (one, two) {
lastProduct = product;
product = one * two;
document.writeln(product + "<br>");
}
for (var i = 1; i <= someNumberGtThan100 && product <= 100; i++) {
mult(i, two);
}
console.log(lastProduct); // 100
By using this condition you have to store the previous value in an auxiliary variable, because when 'product' reach the value of 100 the loop condition is still true, so the loop will be executed one time more.

Iterating GCD function in JavaScript

I am using this JavaScript function to determine the GCD of two values obtained from input fields:
Math.GCD = function(first,second) {
if (first < 0) first = -first;
if (second < 0) second = -second;
if (second > first) {var temp = first; first = second; second = temp;}
while (true) {
first %= second;
if (first == 0) return second;
second %= first;
if (second == 0) return first;
}
};
I would like to extend this to compute the GCD of three numbers, if the user enters a number into a third input field (otherwise, the user will input two and calculate as per this function). Being relatively new to JavaScript, I am not sure how to extend this function for three values. Can anyone help?
Fiddle: https://jsfiddle.net/tjj7won4/1/
Also, I would like to determine the LCM in a likewise fashion, as observed in the fiddle, but, again, I am unsure how to extend the given function. Please, help.
To extend the function for any number of parameters n, just loop n-1 times over an array of parameters.
This is because mathematically gcd(a,b,c) = gcd(a,gcd(b,c))
Usage: var GCDresult = Math.GCD([16,222,70]); // result: 2.
// numbers is an array of numbers: ex. [15,20,35,170]
Math.GCD = function(numbers) {
for (var i = 1 ; i < numbers.length ; i++){
// take the next number for GCD with the first,
// and store the result back in the first.
numbers[0] = twogcd(numbers[0], numbers[i]);
}
return numbers[0];
// following is your original GCD function
function twogcd(first, second) {
if (first < 0) first = -first;
if (second < 0) second = -second;
if (second > first) {var temp = first; first = second; second = temp;}
while (true) {
first %= second;
if (first == 0) return second;
second %= first;
if (second == 0) return first;
}
}
};
Your JSFiddle, updated for GCD case is here.
You can have something that can accept any number of arguments by using the same function.
And you may extend it too : fiddle
Math.GCDe = function() {
var result = arguments[0];
for (var i=1;i<arguments.length;i++)
result = this.GCD(result,arguments[i]);
return result;
}

JS crashes sometimes with Timer scramble

My Javascript timer is for people with a rubiks cube with generates a scramble (nevermind all this, but just to tell you I'm generating after each solve a new scramble will be generated) and my scrambles do actually have a while (true) statement. So that does crash my script, but it 95/100 times stops just before the script crashes but I don't wanna have any times.
Let me explain a bit more detailed about the problem.
Problem: javascript crashes because my script takes too long to generate a scramble.
Below you have 3 functions I use.
This function generates a scramble with the Fisher-Yates shuffle.
Timer.prototype.generateScramble = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
This function validates the input e.g. I receive an array as the following:
Here I only have to check the first character. That's why I use the seconds [ ] notation. I don't want people get an F with an F2 e.g.
var scr = ["F","R","U","B","L","D","F2","R2","U2","B2","L2","D2","F'","R'","U'","B'","L'","D'"]
Timer.prototype.validateScramble2 = function(array) {
var last = array.length-1;
for (var i = 0; i < array.length-1; i++) {
if (array[i][0] == array[i+1][0]) {
return false;
}
}
for (var i = 0; i < array.length-2; i++) {
if (array[i][0] == array[i+2][0]) {
return false;
}
}
if (array[0][0] == [last][0]) {
return false;
}
return true;
};
The above functions are just waiting to be called. Well in the function below I use them.
Timer.prototype.updateScramble2 = function(scrambleArr, len, type) {
var self = this;
var scramble = '', j, updatedArr = [];
while (updatedArr.length < len) {
j = (Math.floor(Math.random() * scrambleArr.length));
updatedArr.push(scrambleArr[j]);
}
while (!self.validateScramble2(updatedArr)) {
updatedArr = self.generateScramble(updatedArr);
}
for (var i = 0; i < updatedArr.length; i++) {
scramble += updatedArr[i] + ' ';
}
scrambleDiv.innerHTML = scramble;
};
I assume you guys understand it but let me explain it briefly.
The first while-loop adds a random value from the given array(scrambleArr) into a new array called updatedArr.
The next while-loop calls the validateScramble2() function if there isn't in an array F next to an F2.
The for-loop adds them into a new variable added with a whitespace and then later we show the scramble in the div: scrambleDiv.innerHTML = scramble;
What do I need know after all this information?
Well I wanna know why my updateScramble2() functions lets my browser crash every time and what I do wrong and how I should do it.
I'm not entirely sure I understand the question, but from the way your code looks, I think you have an infinite loop going on. It appears as if validateScramble2 always returns false which causes your second loop in updateScramble2 to perpetually run.
I suggest you insert a breakpoint in your code and inspect the values. You could also insert debugger; statements in your code, works the same way. Open dev tools prior to doing these.
A suggestion is instead of using loops, use a timer. This breaks up your loop into asynchronous iterations rather than synchronous. This allows the browser breathing space for other operations. Here's an example of a forEachAsync:
function forEachAsync(array, callback){
var i = 0;
var timer = setInterval(function(){
callback.call(null, array[i]);
if(++i >= array.length) clearInterval(timer);
}, 0);
}
forEachAsync([1,2,4], function(item){
console.log(item);
});
You can take this further and use Promises instead of callbacks.

How would I get it where every time it generates a random number it adds it onto a variable in javascript?

How would I make it where every time it generates a random number it adds it on to a variable called Num my code is below.
function Generate() {
var Num;
var RanN = Math.floor((Math.random()*10)+1);
for (var i=0;i<4;i++) {
Num += RanN;
}
}
If you're trying to generate a random number i amount of times and add it to a pre-existing number, you'll want something like this:
function Generate(startNum, iterations) {
for (var i=0; i<iterations; i++) {
startNum += Math.floor((Math.random()*10)+1);
}
return startNum;
}
And you would use it like this (if you want to add ten randomly generated numbers):
var num = 0;
num = Generate(num, 10);
Here's a fiddle.
Here is what I think the OP want:
function Generate(Num) {
for (var i=0;i<4;i++) {
Num += Math.floor((Math.random()*10)+1);
}
return Num;
}
The answers are slightly different in structure to your function. If you want to fix what you have (seeing that you have moved the random function into the loop), just change var Num; to var Num=0;, which will fix the NaN error (because you can't add a number to something that is not defined, because it is Not a Number)
If what you want is a random int you could use:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1111, 9999));
You can find more info here.

Categories