I am trying to write a script that will create numbers in Fibonacci order, I don't understand why this is not working.
var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];
function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
if (n>1){
output.push(nextNum);
console.log(output);
}
else if (n<2)
{output.push(1);
console.log(output);}
}
}
In your original code your n never changes as you only assigned it on start.
var output = [];
function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
var n = output.length;
var nextNum = output[n-1] + output[n-2];
if (n>1){
output.push(nextNum);
console.log(output);
}
else if (n<2)
{
output.push(1);
console.log(output);
}
}
}
fibo(10)
In Javascript numbers are passed by value not reference so they are not the same object in memory. So when the array length changes your n value stays at 0 because they are not the same object.
function fibo(numQuantity) {
let output = [0, 1];
if(numQuantity < 2) {
return output.slice(0, numQuantity);
}
for(let i = 2; i < numQuantity ; i++) {
const n = output.length
output.push(output[n - 1] + output[n - 2])
}
return output;
}
console.log(fibo(1))
console.log(fibo(2))
console.log(fibo(3))
console.log(fibo(4))
Check this fiddle: https://jsfiddle.net/37a4burz/
You need to add n++ to end of your code and change end condition.
Here is full code:
var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];
function fibo (numQuantity) {
for (var i=1; i<= numQuantity ; i++)
{
if (n==0) {
output.push(0);
console.log(output);
}
else if (n==1) {
output.push(1);
console.log(output);
}
else if (n>1) {
output.push(output[n-1] + output[n-2]);
console.log(output);
}
n++;
}
}
fibo(7);
Related
I want to write a Generator for Fibonacci numbers in Javascript;
0,1,1,2,5,7,12..... (to make the sequence you have to add the last two numbers)
But I have this problem when I assign the the output.length to a variable the code is not working, if I write it down straight instead of "newNumber" the code down is however working, but I don't understand what is wrong with the first one. Is it something wrong with the place of the variables?
function fibonacciGenerator(n) {
var output = [];
var lastNumber = output[output.length - 1];
var nPrev = output[output.length - 2];
var newNumber = lastNumber + nPrev;
if (n === 1) {
output = [0];
} else if (n === 2) {
output = [0, 1];
} else {
output = [0, 1];
for (var i = 2; i < n; i++) {
output.push(newNumber);
}
}
return output
}
console.log(fibonacciGenerator(5));
function fibonacciGen(n) {
const output = [0, 1];
// Return an empty array if n is less than 1
if (n < 1) {
return [];
}
// If n is 1 or 2, we can return the array now
if (n <2) {
return output;
}
// Loop through the remaining numbers in the sequence
for (let i = 2; i < n; i++) {
// Calculate the next number in the sequence
let lastNumber = output[output.length - 1];
let nPrev = output[output.length - 2];
let newNumber = lastNumber + nPrev;
// Add the new number to the output array
output.push(newNumber);
}
// Return the output array
return output;
}
console.log(fibonacciGen(5));
you have to declare your logic of next term in loop because first time length of output is zero
function fibonacciGenerator (n) {
var output =[];
if (n < 1) {
return [];
}
if (n===1){
output=[0];
}
else if (n===2){
output=[0,1];
}
else{
output=[0,1];
for( var i = 2; i < n; i++){
var lastNumber=output[output.length-1];
var nPrev=output[output.length-2];
var newNumber=lastNumber+nPrev;
output.push(newNumber);
}
}
return output
}
before going to problem, i want to generate dynamically like
temp = word[i] for 2,
temp = word[i-1] + word [i] for 3,
temp = word[i-2] + word[i-1] + word [i] for 4
I explained with code and what i have tried
function produceTwoChArray(word) {
var temp = "";
var tempArr = [];
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === 2) {
tempArr.push(temp);
}
temp = word[i];
}
return tempArr;
}
produceTwoChArray("breaking")
above code will produce result as :
["br", "re", "ea", "ak", "ki", "in", "ng"]
So inside the for loop if i change to below codes to produce three letters then
if (temp.length === 3) {
tempArr.push(temp);
}
temp = word[i-1] + word[i];
Result:
["bre", "rea", "eak", "aki", "kin", "ing"]
so adding word[i-1], word[i-2] with temp length 3, 4 and so on..
For dynamically creating the temp statement, i created these Function
1)
function generateWordSequence(n) {
var n = n - 2;
var temp1 = [];
for (var j = n; j >= 0; j--) {
temp1.push("word[i - " + j + "]");
}
temp1 = temp1.join('+').toString();
return temp1;
}
2)
function generateWordSequence(n, word) {
var n = n - 2;
var temp1 = "";
for (var j = n; j >= 0; j--) {
temp1 = temp1 + word[i - j];
}
return temp1;
}
But both above try's are returning as string so it didnt work. When i invoke above fn in produceTwoChArray fn like this
function produceTwoChArray(word, n) {
var temp = "";
var tempArr = [];
var retVar = generateWordSequence(n, word);
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === n) {
tempArr.push(temp);
}
temp = retVar;
}
return tempArr;
}
When i tried those all logic inside produceTwochArray itself , i also didnt work.
Please help me out here.
You could take a double slice with mapping part strings.
function part(string, count) {
return [...string.slice(count - 1)].map((_, i) => string.slice(i, i + count));
}
console.log(part("breaking", 2));
console.log(part("breaking", 3));
console.log(part("breaking", 4));
You can use slice method in order to obtain a more easy solution.
function produceArray(str,n){
return str=str.split('').map(function(item,i,str){
return str.slice(i,i+n).join('');
}).filter(a => a.length == n);
}
console.log(produceArray("breaking",2));
console.log(produceArray("breaking",3));
console.log(produceArray("breaking",4));
console.log(produceArray("breaking",5));
console.log(produceArray("breaking",6));
Why is it that the following works fine:
var howMany = prompt("How many numbers?");
var myArray = [];
for(var i = 0; i < howMany; i++){
myArray.push(prompt("Enter a number"));
}
alert(myArray);
The code above is intended to ask user how many numbers are they going to put into an array, and it displays the array.
This chunks of code below seems to be fine too.
There is a provided array.
Then the code checks whether the numbers are actually numbers.
After that it adds all the numbers together.
var myArray = [1,2,3,4,5];
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i=0; i<length; i++){
if(typeof array[i]!== typeof first){
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true){
add(myArray);
} else {
console.log("cant do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i=0; i<length; i++){
f+= array[i];
}
alert("The result of addition of this set: " + myArray + " is: " + f);
}
but when i combine the two it does not work. It does not add the numbers.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(prompt("Enter a number"));
}
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i = 0; i < length; i++) {
if (typeof array[i] !== typeof first) {
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
Can you be so kind to correct me?
The return value from prompt is a string, not a number.
var n = prompt("Enter a number");
alert("typeof(n) = " + typeof(n));
Even if you enter a numeric value, the code above will display "typeof(n) = string".
You must convert the string into a number.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"), 10));
}
The prompt function saves strings, so the problem here is that you are trying to make a sum of strings. Just add a typecast in the add function and the script will work correctly:
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += parseInt(array[i]);
}
}
var howMany = prompt("How many numbers?"),
myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"),10));
}
function isDataUniform(array) {
for (i = 0; i < array.length; i++) {
if (typeof array[i] !== "number") {
return false;
}
}
return true;
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}
I'm having trouble with a function returning the original array as opposed to the sorted array. I tried to slice the array and return the sorted but it is not working. Any ideas on how to fix this?
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
return newArray;
}
I fixed the function:
function sortArr( comparator, array ){
/*your code here*/
var i, x;
var min;
var newArray = array.slice();
for(i = 0; i < newArray.length - 1; i++)
{
min = i;
for(x = i + 1; x < newArray.length; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
if(min != i){
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
}
return newArray;
}
Copy the array with slice and then use native sort:
function sortArr(comparator, array) {
return array.slice().sort(function(a,b) {
return comparator(a,b) * 2 - 1;
});
}
Your sorting algorithm doesn't look quite right. For a start the swapping of values should be inside the if statement. I would also advise to look at #Oriol's solution which is far more elegant.
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
min = x;
}
}
}
return newArray;
}
{"index.js":"var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let newArr = globalArray.slice();\n let emptyArr = [];
return emptyArr.concat(newArr).sort();
}
nonMutatingSort(globalArray);"}
I have the following code to find the prime numbers from 2 to 1000:
#!/usr/bin/env node
var primesarray = function(n) {
var nums = [];
for (var i = 0; i < n; i++) {
nums.push("1");
}
return nums;
};
var primes = function(arr) {
var i = 2;
var primes = [];
for (i = 2; i < arr.length - 1; i++) {
if (arr[i] === "1")
primes.push(i);
for (j = 2; Math.pow(i, j) < arr.length - 1; j++ ) {
arr[Math.pow(i,j)] = "0";
}
}
return primes;
};
// Print to console
var fmt = function(arr) {
return arr.join(",");
};
var k = 1000;
console.log("primes(" + k + ")");
console.log(fmt(primes(k)));
When I run the file, it just prints the first console.log line. I'm not seeing what's wrong here.
The function primes is written to expect an array, but you're passing it an integer.
Did you mean fmt(primes(primesarray(k)))?
(That does at least print a list of numbers, but I'm afraid many of them are not primes!)
You need to prime you array ;)
var arr = primesarray(k)
like this
var k = 1000;
var arr = primesarray(k)
console.log(primes(arr));
console.log(fmt(primes(arr)));
DEMO
Some actual solutions: http://www.codecademy.com/forum_questions/5033d10f77955e0002004142