Calculate and push fibonacci numbers in an array - javascript

let result = [];
function recurseFivonaci(n){
if(n < 2){
return n;
}
return recurseFivonaci(n - 2) + recurseFivonaci(n - 1);
}
console.log(recurseFivonaci(10).map(r => result.push(r)))
TypeError: recurseFivonaci(...).map is not a function
at <anonymous>:16:33
at dn (<anonymous>:16:5449)
How can I push in the result of fibonacci function into an array?
I expect this to work but doesn't:
result = [0,1,1,2,...];

Here's a possible solution
let result=[];
function fibonacci_series(n)
{
if(n === 0){
return [0];
}
if (n===1)
{
return [0, 1];
}
else
{
result = fibonacci_series(n - 1);
result.push(result[result.length - 1] + result[result.length - 2]);
return result;
}
};
console.log(fibonacci_series(10))

Map() is a function available on an Array type in JavaScript and since you're returning a number from your function, it is throwing this error. What you need instead is something like:
let result=[];
function recurseFibonaci (n) {
if(n < 2){
return n;
}
return recurseFibonaci(n-2) + recurseFibonaci(n-1);
}
result.push(recurseFibonaci(10));
console.log(result)

There may be some neato means to achieve it but a basic iteration seems fine?
const arr = [0,1]
for (let i = 0; i < 10; i++) {
arr.push(arr[i] + arr[i + 1]);
}
console.log(arr);

Related

Javascript/ variable place/ what is wrong with the code

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
}

How to write a function generating Fibonacci series smaller than a given number (javascript)?

Here's my code:
function fibs(num) {
//generate Fibonacci numbers:
let arr = [1,1]
let i = 2;
function fibsRange(i) {
arr[i] = arr[i-1] + arr[i-2]
if (arr[i] < num) {
fibsRange(i+1);//call function one more time;
}
return arr
}
return fibsRange();
}
console.log(fibs(5));
Assume that given number (num) is bigger than 2. Where do I get wrong?
Note: I edited my code.
first :as mentionned by Phil your function (the first one) needs to return something.
second: you don't need 2 functions, one will do the job.
here's a working version of your code (I also modified some unnecessary code.
Edit: I added the case when you need to parse just one parameter
function fibsRange(i,arr,num) {
if(arr[i-1]+arr[i-2] > num) return arr
else{
arr[i] = arr[i - 1] + arr[i - 2]
return fibsRange(i + 1,arr,num);
}
}
//in case you need just one parameter
function fib(num){
let arr = [1, 1];
let i = 2;
return fibsRange(i,arr,num);
}
//those(declaration of arr and i) are unnecessary in case you use fib
let arr = [1, 1]
let i = 2;
console.log(fibsRange(i,arr,5));
console.log(fib(5));
You never called your fibsRange() function and never returned anything from fibs().
The following version works.
function fibs(num) {
//generate Fibonacci numbers:
let arr = [1, 1]
if (num>1) fibsRange(2);
function fibsRange(i) {
arr[i] = arr[i - 1] + arr[i - 2]
if (arr[i] < num) {
fibsRange(i + 1); //call function one more time;
}
}
return arr;
}
console.log(fibs(5)); //undified;
Your code is checking if arr[i] < num, then invoke the fibsRange(i+1). This is a wrong logic, you will always get the fibbonacci number just higher than the num because you are already setting it at arr[i] and then checking the condition. However, you should first check if arr[i] < num, and then push it into arr.
function fibs(num) {
//generate Fibonacci numbers:
let arr = [1, 1];
let i = 2;
function fibsRange(i) {
const lastFibNumber = arr[i - 1] + arr[i - 2];
if (lastFibNumber < num) {
arr.push(lastFibNumber);
fibsRange(i + 1); //call function one more time;
}
return arr;
}
return fibsRange(i);
}
console.log(fibs(5));
function fibs(num) {
//generate Fibonacci numbers:
let arr = [1, 1];
while(arr[arr.length-1] <= num){
let y = arr[arr.length-1] + arr[arr.length-2];
if(y > num){
break; // break if new y is greater than num
}
arr.push(y); // add y to the serie
}
return arr; //// return the serie
}
console.log(fibs(50));

two for loops in js. cannot work on nested for loop

I'm working on a problem below, but not sure why my second for loop does console.log anything. I currently get a result, [], and when I work on loops I sometimes confused because the output returns empty result. So why my second for loop is not executed and why I'm not able to push the result to result array?
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
function a(nums, target) {
let result = [];
for (let i = 0; i < nums.length -1; i++){
let firstNum = nums[i];
console.log(i)
for (let j = i + 1; j < nums.length -1; j++){
console.log(j)
let secondNum = nums[j];
let sum = firstNum + secondNum;
if (sum === target) {
return result.push(i, j);
}
}
}
return result;
};
a([2,7,11,15], 9)
Push return only the length of the array, try like below,
function a(nums, target) {
let result = [];
for (let i = 0; i < nums.length; i++){
let firstNum = nums[i];
console.log("i", i)
for (let j = i + 1; j < nums.length; j++){
console.log("j", j)
let secondNum = nums[j];
let sum = firstNum + secondNum;
if (sum === target) {
result.push(i, j);
return result;
}
}
}
return result;
};
let result = a([2,7,11,15], 9);
console.log(result);
Your code is actually correct except for the fact that you are returning the result of result.push(i, j) which returns the length of the array.
Use result.push(i, j); and then return result;
Instead of just return result.push(i, j);
Consider breaking the problem down into smaller parts -
t generates unique combinations of numbers
a steps thru the generator searching for the first valid solution
function* t(n, i = 0, p = [])
{ if (p.length >= 2)
yield p
else if (i >= n.length)
return
else
( yield* t(n, i + 1, [...p, n[i]])
, yield* t(n, i + 1, p)
)
}
function a(n, q)
{ for (const [a, b] of t(n)) // <- step thru t
if (a + b == q) // <- simple condition
return [a, b] // <- solution
}
const result =
a([2,7,11,15], 9)
console.log(result)
Output -
[2, 7]
a will return undefined if the answer cannot be reached

Array Left Rotation in Javascript will log to console but not return

I'm working on the array left rotation on Hackerrank. The solution that I have will console.log the array containing the correct result, but will not work using return. Here's the detail from their site - "Print a single line of n space-separated integers denoting the final state of the array after performing d left rotations." I've read that the issue might be with asynchronous functions running in node.js, but I'm not sure how to work around that.
// sample input - 1 2 3 4 5
// sample output - 5 1 2 3 4
function rotLeft(a, d) {
var arr = [];
for (var i = 1; i <= a; i++){
arr.push(i)
};
for (var j = 1; j <= d; j++){
arr.shift(arr.push(j))
}
console.log(arr.toString()); // <-- this will print the desired output.
return arr.toString(); // <-- no return from this.
}
rotLeft(5, 4)
I have also been trying to solve this problem. There are some issues in your current solution. See you have to create an array and store the array passed from parameters in it.
What you have done is just creating a new array and adding the sequence of numbers of elements that should be in it e.g a.length=5 you are doing arr.push 1 2 3 4 5. But the question wants an array of user's choice. Second thing is that you should return an array not the string.
So this is the solution of this problem:
function rotLeft(a, d) {
var arr = [];
for (var i = 0; i < a.length; i++) {
arr.push(a[i]);
};
for (var j = 1; j <= d; j++) {
arr.shift(arr.push(arr[0]));
}
return arr;
}
I'll give my solution to this problem for future visitors.
you can do this in one line as follows :
function rotLeft(a, d)
{
let rslt = a.slice(d).concat(a.slice(0,d));
return rslt
}
You need to split the initial array at the d'th position in two parts, and simply swap those two.
The slice() method returns a shallow copy of a portion of an array
into a new array object selected from begin to end (end not included).
The original array will not be modified.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
try this
function rotLeft(a, d){
let arr=a
for(let j=0;j<=d-1;j++){
arr.push(arr[0])
arr.shift()
}
return arr
}
function rotLeft(a, d) {
return [...a.slice(d - a.length), ...a.slice(0, d - a.length)]
}
You really don't need two loops. To rotate left n places:
function RotateLeft(arr, n) {
return arr.map(() => {
if (n === arr.length) {
n = 0;
}
return arr[n++];
});
}
var array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var places = 4;
console.log(RotateLeft(array, places));
//[4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3]
The main issue here is that hackerrank expects the return value from rotLeft to be an array, not a string of space-separated numbers. The instructions don't make that clear, unfortunately. As you can see in the pre-defined main function that you aren't supposed to alter:
// ...
const a = readLine().split(' ').map(aTemp => parseInt(aTemp, 10));
const result = rotLeft(a, d);
ws.write(result.join(' ') + '\n'); // <--- result must be an array for .join to work
ws.end();
}
Your code also has some bugs. (Arrays are zero-indexed, for one - they're not 1-indexed. Also, i <= a isn't the right condition - a is the array, so you'd need to use a.length.) Try this function instead, it's a lot simpler and seems to pass all the test cases:
function rotLeft(a, d) {
return [...a.slice(d), ...a.slice(0, d - a.length)]
}
Without using any extra loop and function
function rotLeft(a, d) {
var arr = [];
var l = 0;
for(let i=0;i<a.length;i++){
if(i >= d){
arr[i-d] = a[i]
}else{
arr[a.length-d+l] = a[i];
l = i+1;
}
}
return arr
}
Check my solution and explained in this article
https://medium.com/#aamirafridi/how-to-solve-hackerranks-left-rotation-array-challenge-javascript-c032527802a7
function rotLeft(a, d) {
d = d % a.length;
if (d === 0) return a;
return a.concat(a.splice(0, d));
}
console.log(rotLeft([1,2,3,4,5],1));
console.log(rotLeft([1,2,3,4,5],2));
console.log(rotLeft([1,2,3,4,5],3));
console.log(rotLeft([1,2,3,4,5],4));
console.log(rotLeft([1,2,3,4,5],5));
console.log(rotLeft([1,2,3,4,5,6,7,8,9,10],5));
Here is my solution
function rotLeft(a, d) {
let arr = [...a];
for(let i = 1; i <= d; i++){
arr.push(arr.shift())
}
return arr
}
I answered it like this and it is pretty simple
function rotLeft(a, d) {
for(var i = 1; i <= d; i++) {
a.push(a.shift());
}
return a;
}
I tried all the above scenarios. Nothing is working for me. But I resolved the issue myself. Hackers in rotation program.
First check d assign the value is '4' or not
ex:- const d = parseInt(nd[1], 10); instead of const d = parseInt(nd[2], 10)
goto rotation method:
function rotLeft(a, d) {
let i = 0;
while (i < d) {
a.push(a.shift());
i++;
}
console.log(a);
return a;
}
It's working fine.
You can try this algo:
For example, given the inputs as:
var xArray = [1, 2, 3, 4, 5];
var numberOfLeftRotations = 4;
var newArray = [];
for (var i = 0; i < xArray.length; i++) {
var newIndex = (i + numberOfLeftRotations) % xArray.length;
newArray[i] = xArray[newIndex];
}
console.log(newArray);
If you are not using any built-in method you can write your own javascript function.
try this.
function swap(arr,idx1,idx2){
let temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
function rotation(arr,n){
let j = 0;
while(j<n){
for(let i = 0; i<arr.length-1; i++){
swap(arr,i,i+1);
}
j++;
}
console.log(arr);
return arr;
}
let arr = [1,2,3,4,5,6,7];
rotation(arr,2)
function rotLeft(a, d) {
const result = []
const l = a.length
for (let i = 0; i < a.length; i++) {
const dt = i - d < 0
? l + i - d
: i + d >= l ? i - d : i + d
console.log("i=" + i + ", dt=" + dt)
result[dt] = a[i]
}
return result
}
function rotLeft (a, d) {
if(d === 0) {
return a
}
return a.concat(a.splice(0, d))
}
console.log(rotLeft([1,2,3,4,5], 4))
the simplest one. You don't have to read above all smart boy's bunch of extra unnecessary sentences.
In a real coding interview, you won't be able to use any helper functions from Javascript (100% interviewer will ask you to solve the problem with simple for loops or recursion) so you should use only basics: for loops or recursion
One line solution which will do the job but the interviewer won't accept this solution:
function rotLeft(a,d){
return [...a.slice(d, a.length), ...a.slice(0, d)]
}
Solution with for loops:
function rotLeft(a, d) {
let l = a.length;
let temp = [];
for(let i = 0; i < l; i++){
temp[i] = a[i];
}
for (let i = 0; i < l - d; i++ ){
a[i] = temp[d + i]
}
for (let i = 0; i < d; i++){
a[i + (l - d)] = temp[i]
}
return a
}
function rotLeft(a, d) {
let array = [];
for(let i=0; i<a.length; i++){
if(i>=d){
array[i-d] = a[i]
} else {
array[i-d+a.length] = a[i];
}
}
return array;
}
It is what I did, without loop
function rotLeft(a, d) {
const splited = a.slice(0,d)
const restOfSplit = a.slice(d, a.length)
return (restOfSplit.concat(splited))
}
This one passes all the test as well:
function rotLeft(a, d) {
// Write your code here
return (a.splice(d, a.length)).concat(a.splice(0, d));
}
This would pass all the test cases as array value might be different than [1,2,3,5,5]
function rotLeft(a, d) {
var arr = [];
for (var i = 1; i <= a; i++){
arr.push(a[i])
};
for (var j = 1; j < d; j++){
arr.shift(arr.push(a[j]))
}
console.log(arr); // <-- this will print the desired output.
return arr; // <-- no return from this.
}
This is my answer :
function rotLeft(a, d) {
for(var i=d; i<a.length; i++){
a.unshift(a.pop());
}
return a;
}
function rotLeft (a, d) {
if(d === 0) {
return a
}
return a.concat(a.splice(0, d))
}
console.log(rotLeft([1,2,3,4], 1))
This works good!

Fibonacci series in JavaScript

function fib(n) {
const result = [0, 1];
for (var i = 2; i <= n; i++) {
const a = (i - 1);
const b = (i - 2);
result.push(a + b);
}
return result[n];
}
console.log(fib(8));
The output of the code above is 13. I don't understand the for loop part. In very first iteration i = 2, but after second iteration i = 3 so a = 2 and b = 1 and third iteration i = 4 so a = 3, b = 2, and so on... If it's going on final sequence will be :
[0, 1, 1, 3, 5, 7, 9, 11], which is incorrect. The correct sequence will be [0, 1, 1, 2, 3, 5, 8, 13]
You were not using the previous two numbers that are already in the array to > generate the new fibonacci number to be inserted into the array.
https://www.mathsisfun.com/numbers/fibonacci-sequence.html
Here I have used the sum of result[i-2] and result[i-1] to generate the new fibonacci number and pushed it into the array.
Also to generate n number of terms you need the condition to be i < n and not i <= n.
function fib(n) {
const result = [0, 1];
for (var i = 2; i < n; i++) {
result.push(result[i-2] + result[i-1]);
}
return result; // or result[n-1] if you want to get the nth term
}
console.log(fib(8));
Return result[n-1] if you want to get the nth term.
My solution for Fibonacci series:
const fibonacci = n =>
[...Array(n)].reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
)
This function is incorrect. It cat be checked by just adding the console.log call just before the function return:
function fib(n) {
const result = [0, 1];
for (var i = 2; i <= n; i++) {
const a = (i - 1);
const b = (i - 2);
result.push(a + b);
}
console.log(result);
return result[n];
}
console.log(fib(7));
As you can see, the sequence is wrong and (for n = 7) the return value is too.
The possible change would be as following:
function fib(n) {
const result = [0, 1];
for (var i = 2; i <= n; i++) {
const a = result[i - 1];
const b = result[i - 2];
result.push(a + b);
}
console.log(result);
return result[n];
}
console.log(fib(8));
This is the "classical" Fibonacci numbers; if you really want to use the first number of 0, not 1, then you should return result[n-1], since array indexes start from zero.
One approach you could take for fibonacci sequence is recursion:
var fibonacci = {
getSequenceNumber: function(n) {
//base case to end recursive calls
if (n === 0 || n === 1) {
return this.cache[n];
}
//if we already have it in the cache, use it
if (this.cache[n]) {
return this.cache[n];
}
//calculate and store in the cache for future use
else {
//since the function calls itself it's called 'recursive'
this.cache[n] = this.getSequenceNumber(n - 2) + this.getSequenceNumber(n - 1);
}
return this.cache[n];
},
cache: {
0: 0,
1: 1
}
}
//find the 7th number in the fibbonacci function
console.log(fibonacci.getSequenceNumber(7));
//see all the values we cached (preventing extra work)
console.log(fibonacci.cache);
//if you want to output the entire sequence as an array:
console.log(Object.values(fibonacci.cache));
The code above is also an example of a dynamic programming approach. You can see that I am storing each result in a cache object the first time it is calculated by the getSequenceNumber method. This way, the second time that getSequenceNumber is asked to find a given input, it doesn't have to do any actual work - just grab the value from cache and return it! This is an optimization technique that can be applied to functions like this where you may have to find the value of a particular input multiple times.
const fib = n => {
const array = Array(n);
for (i = 0; i < array.length; i++) {
if (i > 1) {
array[i] = array[i - 1] + array[i - 2];
} else {
array[i] = 1;
}
}
return array;
}
console.log(fib(5))
What you are doing wrong is adding the iterator index (i), whereas what you need to do is add the element in the result at that index.
function fib(n) {
const result = [0, 1];
for (let i = 2; i <= n; i++) {
const a = result[(i - 1)];
const b = result[(i - 2)];
result.push(a + b);
}
console.log("Result Array: " + result);
return result[n];
}
console.log("Fibonacci Series element at 8: " + fib(8));
There are two issues with the logic:
Variables a and b currently refer to i - 1 and i - 2. Instead they should refer to the elements of result array, i.e. result[i - 1] and result[i - 2].
If you need 8th element of the array, you need to call result[7]. So the returned value should be result[n - 1] instead of result[n].
function fib(n) {
const result = [0, 1];
for (var i = 2; i < n; i++) {
const a = result[i - 1];
const b = result[i - 2];
result.push(a + b);
}
console.log(result);
return result[n - 1];
}
console.log(fib(8));
simple solution for Fibonacci series:
function fib(n){
var arr = [];
for(var i = 0; i <n; i++ ){
if(i == 0 || i == 1){
arr.push(i);
} else {
var a = arr[i - 1];
var b = arr[i - 2];
arr.push(a + b);
}
}
return arr
}
console.log(fib(8))
This is certainly one of those "more than one way to clean chicken" type situations, this JavaScript method below works for me.
function fibCalc(n) {
var myArr = [];
for (var i = 0; i < n; i++) {
if(i < 2) {
myArr.push(i);
} else {
myArr.push(myArr[i-2] + myArr[i-1]);
}
}
return myArr;
}
fibCalc(8);
When called as above, this produces [0,1,1,2,3,5,8,13]
It allows me to have a sequence of fib numbers based on n.
function fib(n) {
const result = [0];
if (n > 1) {
result.push(1);
for (var i = 2; i < n; i++) {
const a = result[result.length - 1]
const b = result[result.length - 2];
result.push(a + b);
}
}
console.log(result);
}
i came up with this solution to get the n index 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));
Here, you have it, with few argument check, without using exception handling
function fibonacci(limit){
if(typeof limit != "number"){return "Please enter a natural number";}
if(limit <=0){
return "limit should be at least 1";
}
else if(limit == 1){
return [0];
}
else{
var series = [0, 1];
for(var num=1; num<=limit-2; num++){
series.push(series[series.length-1]+series[series.length-2]);
}
return series;
}
}
I came up with this solution.
function fibonacci(n) {
if (n == 0) {
return [0];
}
if ( n == 1) {
return [0, 1];
} else {
let fibo = fibonacci(n-1);
let nextElement = fibo [n-1] + fibo [n-2];
fibo.push(nextElement);
return fibo;
}
}
console.log(fibonacci(10));
function fibonacciGenerator (n) {
var output = [];
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(output[output.length-2] + output[output.length-1]);
}
}
return output;
}
output = fibonacciGenerator();
console.log(output);
function fibonacci(end) {
if (isNaN(end) === false && typeof (end) === "number") {
var one = 0, res, two = 1;
for (var i = 0; i < end; ++i) {
res = one + two;
one = two;
two = res;
console.log(res);
}
} else {
console.error("One of the parameters is not correct!")
}
}
fibonacci(5);
var input = parseInt(prompt(""));
var a =0;
var b=1;
var x;
for(i=0;i<=input;i++){
document.write(a+"<br>")
x = a+b;
a =b;
b= x;
}

Categories