Fibonacci Series with JavaScript - javascript

var var1 = 0;
var var2 = 1;
var var3;
var num = 20;
document.write(var1 + "<br />");
document.write(var2 + "<br />");
for (var i = 3; i <= num; i++) {
var3 = var1 + var2;
var1 = var2;
var2 = var3;
document.write(var3 + "<br />");
}
Best, I'm doing a Fibonacci Series, but I want to see a message with prompt comes up, so you can fill in a number, then the returns with the Fibonacci Series. Who would be able to help me? Above I have now.

I have created demo, hope it will help you.
var i;
var fib = [0, 1];
var limit = window.prompt('Enter the limit for your series:', '');
for (i = 2; i < parseInt(limit); i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
console.log(fib);
Demo Link

function myFunction() {
var n = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = fibonacciGenerator (n);
}
var sequence = [0]; // sequence = []; if you want sequence [1] = 1;
var previousNumber = 1;
var presentNumber = 0;
var sum = 0;
function fibonacciGenerator (n) {
while (sequence.length < n) {
sum = previousNumber + presentNumber;
previousNumber = presentNumber;
presentNumber = sum;
sequence.push(sum);
}
return (sequence);
}
<!DOCTYPE html>
<html>
<body>
<h1>Fibonacci Generator </h1>
<input type="number" id="myNumber" value="0">
<p>Enter a number to generate Fibonacci array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>

Using ES6 generator
function* fiboGen(len, current = 0, next = 1) {
if (len === 0) {
return current;
}
yield current;
yield* fiboGen(len - 1, next, current + next);
}
const fibo = [...fiboGen(10)];
console.log(fibo);
//[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

you need to use a prompt box to get the number:
window.prompt("sometext","defaultText");
http://www.w3schools.com/js/js_popup.asp

I hope that this is what you are looking for.
HTML:
Which sequence of the Fibonacci pattern do you want to find?
<br><br>
<input type="text" id="inputtext">
<br><br>
<input type="button" value="Find out" id="btn">
<br><br>
<b id="ID"></b>
JS:
function add(a, b) {
while (a.length < b.length) a.unshift(0);
while (a.length > b.length) b.unshift(0);
var carry = 0,
sum = [];
for (var i = a.length - 1; i >= 0; i--) {
var s = a[i] + b[i] + carry;
if (s >= 10) {
s = s - 10;
carry = 1;
} else {
carry = 0;
}
sum.unshift(s);
}
if (carry) sum.unshift(carry);
return sum;
}
function fib(n) {
var f1 = [0];
var f2 = [1];
while (n--) {
var f3 = add(f1, f2);
f1 = f2;
f2 = f3;
}
return f1.join("");
}
document.getElementById("btn").onclick = function () {
var inputnum = parseFloat(document.getElementById("inputtext").value);
document.getElementById("ID").innerHTML = fib(inputnum).toString();
};
Fiddle.

var number = prompt("Enter number ");
....... your code ....

You can do the following:
var var1 = 0;
var var2 = 1;
var var3;
var num = window.prompt("Enter the limit for your series:","");
//var num = 20;
var str = '';
str+=var1+','+var2;
for(var i=3; i <= parseInt(num);i++)
{
var3 = var1 + var2;
var1 = var2;
var2 = var3;
str+=','+var3;
}
document.write(str);

<!doctype html>
<html lang="en">
<head>
<body>
<script type="text/javascript">
var f1=0,f2=1,f3;
var i;
alert("enter a text"+n);
var n=prompt("enter the number");
document.write("the fibonacci series is "+"<br/>");
for(i=2;i<=n;i++)
{
f3=f1+f2;
f1=f2;
f2=f3;
document.write(f3+"<br/>");
}
</script>
<style>
body {background-color:#66ff66}
</style>
</head>
</body>

i came up with this solution to get the n index Fibonacci value. you can use the findFac0(); to pass the index you need to get the Fibonacci value.
function findFac(n){
if (n===1)
{
return [0, 1];
}
else
{
var s = findFac(n - 1);
s.push(s[s.length - 1] + s[s.length - 2]);
return s;
}
}
function findFac0(n){
var vv1 = findFac(n);
return vv1[n-1];
}
console.log(findFac0(10));

I've tried this: it might work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci</title>
<style>
* {
outline: 0px;
margin: 0px;
}
input[type="number"] {
color: blue;
border: 2px solid black;
width: 99.58vw;
}
</style>
</head>
<body>
<div id="myDiv" style="color: white;background-color: blue;">Numbers Here</div>
<input type="number" id="input1" oninput="fibonacciProgram(this.value)" placeholder="Type Some Numbers Here">
<script>
function fibonacciProgram(numberCount) {
let resultElement = document.getElementById("myDiv");
resultElement.innerHTML = " ";
if (isNaN(numberCount) || numberCount <= 0) {
resultElement.innerHTML = "please enter a number";
return;
}
let firstBox = 0;
let secondBox = 1;
let swichBox;
let entries = [];
entries.push(secondBox);
while (numberCount > 1) {
swichBox = firstBox + secondBox;
entries.push(swichBox);
firstBox = secondBox;
secondBox = swichBox;
numberCount--;
}
resultElement.innerHTML = entries.join(', ');
}
</script>
</body>
</html>

Related

How do I use a parameter for the users input rather than connecting it with document.getElementById, while using a button?

let score = 0;
var myArray = [1, 2, 3, 4, 5];
let randomNumber;
function GuessNumber() {
var userGuess = document.getElementById("userInput").value;
var i;
for (i = 0; i < 1; i++) {
var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
}
var userGuess = document.getElementById("userInput").value;
if (userGuess == randomNumber) {
alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
score++;
} else {
alert("SORRY, The correct number was " + randomNumber);
score = score - 1;
}
document.getElementById("GameScore").innerHTML = "Score: " + score;
}
<!doctype HTML>
<html>
<body>
<p id="GameScore">Score: 0</p>
<button onclick="GuessNumber()">Start Game!</button>
<input id="userInput" type="text">
</body>
</html>
So the whole point is that instead of writing
var userGuess = document.getElementById("userInput").value
I want the user's input to be a parameter for the function.
The problem however is that i'm using a button to start the function so i'm not sure what to do since the users input is with a textbox.
Just pass the value of the input to the function.
Consider using addEventListener instead of inline event handlers.
let score = 0;
var myArray = [1, 2, 3, 4, 5];
function GuessNumber(userGuess) {
var i;
for (i = 0; i < 1; i++) {
var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
}
if (userGuess == randomNumber) {
alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
score++;
} else {
alert("SORRY, The correct number was " + randomNumber);
score = score - 1;
}
document.getElementById("GameScore").innerHTML = "Score: " + score;
}
document.querySelector('button').addEventListener('click', e=>{
GuessNumber(document.getElementById("userInput").value);
});
<!doctype HTML>
<html>
<body>
<p id="GameScore">Score: 0</p>
<button>Start Game!</button>
<input id="userInput" type="text">
</body>
</html>
You mean something like this?
<!doctype HTML>
<html>
<body>
<p id="GameScore">Score: 0</p>
<button onclick="GuessNumber(document.getElementById('userInput').value)">Start Game!</button>
<input id="userInput" type="text">
</body>
</html>
let score = 0;
var myArray = [2, 3];
let randomNumber;
function GuessNumber(userGuess) {
var i;
for (i = 0; i < 1; i++) {
var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
}
if (userGuess == randomNumber) {
alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
score++;
} else {
alert("SORRY, The correct number was " + randomNumber);
score = score - 1;
}
document.getElementById("GameScore").innerHTML = "Score: " + score;
}

js Page Freezing on from .length?

This function is freezing my page.
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
}
However, when I remove this it runs just fine.
modeArr.length = array.length;
modeCounter.length = array.length;
Here is all of my code:
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br><p>
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "mean"></p>
<p id = "median"></p>
<p id = "count"></p>
<p id = "summation"></p>
<p id = "mode"></p>
<p id = "variance"></p>
<p id = "sd"></p>
<script type = "text/javascript">
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard_deviation = 0;
var meanOutput = document.getElementById('mean');
var medianOutput = document.getElementById('median');
var modeOutput = document.getElementById('mode');
var countOutput = document.getElementById('count');
var summationOutput = document.getElementById('summation');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var sum = findSum(arrayOfLines);
findMean(arrayOfLines, sum);
findMedian(arrayOfLines);
findMode(arrayOfLines);
findVariance(arrayOfLines);
findStandardDeviation(arrayOfLines);
findVariance(arrayOfLines);
}
function findSum (array)
{
var count = array.length;
var sum = 0;
for (var a = 0; a < array.length; a++)
{
sum += parseInt(array[a]);
}
countOutput.innerHTML = "Count: " + array.length;
summationOutput.innerHTML = "Sum: " + JSON.stringify(sum);
return sum;
}
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
for (var a = 0; a < array.length; a++)
{
for (var b = 0; b < modeArr.length; b++)
{
if (modeArr[a] == modeArr[b])
{
modeCounter[a]++;
}
if (a == 0)
{
b--;
}
}
modeArr[a] = array[a];
}
modeOutput.innerHTML = "Mode: ";
}
function findMean (array, sum)
{
mean = sum/array.length;
meanOutput.innerHTML = "Mean: " + mean.toPrecision(2);
}
function findMedian (array)
{
for(var i=0; i < array.length; i++)
{
array[i] = +array[i];
}
var sortedArrayOfLines = array.sort(function(a, b){return a - b});
if (array.length % 2 == 1)
{
median = sortedArrayOfLines[((array.length - 1)/2)]
}
else
{
median = (sortedArrayOfLines[array.length/2] + sortedArrayOfLines[(array.length/2)+1])/2
}
medianOutput.innerHTML = "Median: " + median;
}
function findVariance (array)
{
var mean = mean(array);
return mean(array.map(function(num)
{
varianceOutput.innerHTML = Math.pow(num - mean, 2);
}));
}
function findStandardDeviation (array)
{
medianOutput.innerHTML = Math.sqrt(variance(array));
}
</script>
</body>
</html>
So the issue isn't the length it's a infinite loop.
The problem is this bit of code
if (a == 0)
{
b--;
}
This is inside the following loop with b as the iterator. See below.
for (var b = 0; b < modeArr.length; b++)
a is set to zero by the outer loop. Thus a==0 is always true inside the inner loop. b will never increase only decrease. Thus this is a infinite loop because b will never be greater than modeArr.length.
So I would consider revising the function, below is a example of a possible candidate for a mode function:
Get the element with the highest occurrence in an array

print 1 to 5 and even and odd in HTML and JavaScript

I have to create a html page which satisfy below requirement-
1. print 1 to 5 with another array
2. take number input from textbox then print on page whether it is Even or Odd.
I have create a page but it is not working as desired.
<HTML>
<HEAD>
</HEAD>
<BODY>
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly="true"/>
<SCRIPT>
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = if((value % 2) == 0) {"Even"} else {"Odd"}*/
//if(value % 2 == 0) document.write("Even")
//document.write(value);
//document.getElementById("demo").innerHTML = res;
readonly.value=res;
}
//document.write("Hello World!");
</SCRIPT>
</BODY>
</HTML>
Could someone please help me with the code.
please see the updated solution
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").value=res;
}
//document.write("Hello World!");
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly/>
Updated code
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").innerHTML=res;
}
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<p id="result"></p>
Update2
Replace
<p id="result"></p>
with
<span id="result"></span>
There is a problem with the way you are assigning res, it should be as follows:
var res = value % 2 == 0 ? "Even" : "Odd";
Alternatively you can use an if statement if you want like so:
var res = "Odd";
if(value % 2 == 0) {
res = "Even";
}
In addition, there is also an issue with this line:
readonly.value=res;
In this case, readonly does not exist. You probably mean to do this:
document.getElementById("result").value = res;

Converting form text in HTML into an array in JS

I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview

Generate color palette using JavaScript

I want to generate a color palette of every 5th, 15th,17th or 51th RGB-value.
Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Color Palette</title>
<style type="text/css">
div{margin:0;width:20px;height:20px;float:left}
.clear{clear:both}
</style>
</head>
<body>
<script>
var r = 0,
g = 0,
b = 0;
function createBr() {
var b = document.createElement('br');
b.style.clear = 'both';
document.body.appendChild(b);
}
function createDiv(r,g,b) {
var a = document.createElement('div');
a.style.background = 'rgb(' + r + ',' + g + ',' + b + ')';
document.body.appendChild(a);
}
function createColorPalette(value) {
var v = 255/value;
for(i = 0; i < v; i++) {
r = r + value;
g = g + value;
b = b + value;
createDiv(r,g,b);
}
createBr();
}
// put in 5,15,17 or 51 as value below
window.onload = createColorPalette(17);
</script>
</body>
</html>
I'm not smart enough to figure out how to generate all the 3375 colors with a small script. Any ideas how to do that?
Cycle through the fractions for each color like so:
function createColorPalette(value) {
var v = 255/value;
for( var rStep = 0, r = 0; rStep < v; rStep++) {
for( var gStep = 0, g = 0; gStep < v; gStep++ ) {
for( var bStep = 0, b = 0; bStep < v; bStep++ ) {
createDiv(r,g,b);
b += value;
}
g += value;
}
r += value;
}
createBr();
}

Categories