How to display the numbers in console, without for loop? - javascript

the task is to create a recursion, displaying Fibonacci numbers. I need to display the number chain of Fibonacci numbers in the console, without (for) loop.
I have optimised the recursion and displayed the numbers with a (for) loop.
"use strict";
var arr = []
let skkak = function(n)
{
if (n <= 1)
{
return n;
}
if(!isNaN(arr[n])){
return arr[n];
}
else
{
let result = skkak(n - 1) + skkak(n - 2)
arr[n] = result;
return result;
}
}
for(let i=12; i > 0; i--)
{
console.log(skkak(i));
}
no errors

This version is using while (not recursive)
"use strict";
var arr = []
let skkak = function(n)
{
if (n <= 1)
{
return n;
}
if(!isNaN(arr[n])){
return arr[n];
}
else
{
let result = skkak(n - 1) + skkak(n - 2)
arr[n] = result;
return result;
}
}
let i = 12;
while(i > 0)
{
console.log(skkak(i));
i--;
}
Recursive approach
fibonacci = (n) =>
{
if (n===1)
{
return [0, 1];
}
else
{
let s = fibonacci(n - 1);
s.push(s[s.length - 1] + s[s.length - 2]);
return s;
}
};
console.log(fibonacci(5)); // [0,1,1,2,3,5]

Related

Finding Fibonacci bugs keep returning undefined

I am trying to solve the fibonacci in recrusive way and I think i got a bug in my code.I can't figurer out where it is.
Example:
fib(4) === 3
function fib(n, array = [0, 1], count = 0) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
array.push(array[count] + array[count + 1]);
console.log(array)
if (n === array.length-1) {
return array.pop()
}
fib(n, array, count + 1);
}
let ans=fib(2)
console.log(ans)
you can do by this way using recursion
var i = 0, a = 0, b = 1, c = 0;
var out = "";
function fibonacci(n){
i = 0;
if(i < n){
out += a + ",";
c = a + b;
a = b;
b = c;
i++;
console.log(out);
fibonacci(n - i);
}
}
fibonacci(10);

NodeJS script running but logging nothing

so I am writing a function to get biggest divisor,
and I am running it in VScode using command
$ -node script.js
it is logging nothing, what am I missing?
here is the content of script.js :
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
return result;
}
if (!i) {
return result;
}
}
console.log(result);
};
LFfinder(15);
You are writing console.log() at the place where control is not reaching as per your logic. Try writing before you return the value
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
console.log(result);
return result;
}
if (!i) {
console.log(result);
return result;
}
}
};
LFfinder(15)
You don't need to return in the loop. Because of return the console.log statement is never reached. And the else part is not required. This will work:
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
break;
}
}
console.log(result);
};
LFfinder(15);
LFfinder(19);
LFfinder(200);
Note that you don't need to loop through till end. The first instance you find is the greatest, so save further iteration with break.
Also, it's better that the function returns a value instead of logging the answer.
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
break;
}
}
return result;
};
console.log(LFfinder(15));
console.log(LFfinder(19));
console.log(LFfinder(200));
its working fine, please check the link, i've tried
https://repl.it/#HarshSrivastav1/playgroundams

How to make this fib sequence faster?

var fibonacci = function(n) {
let cache = {};
let value;
if (n in cache) {
value = cache[n];
} else {
if (n == 0 || n == 1) {
value = n;
} else {
value = fibonacci(n - 1) + fibonacci(n - 2);
cache[n] = value;
}enter code here
}
return value;
};
fibonacci(60)
codewar wont accept this fib sequence its too slow how to make it faster
Put the cache outside of the function, otherwise it won't do anything (subsequent calls of fibonacci, including the recursive calls, won't be able to see prior cached numbers):
let cache = {};
var fibonacci = function(n) {
let value;
if (n in cache) {
value = cache[n];
} else {
if (n == 0 || n == 1) {
value = n;
} else {
value = fibonacci(n - 1) + fibonacci(n - 2);
cache[n] = value;
}
}
return value;
};
console.log(fibonacci(60))
To clean up the code some more, you can immediately return instead, to cut down on indentation and to avoid unnecessary reassignment:
const cache = {};
const fibonacci = function(n) {
if (n in cache) {
return cache[n];
}
if (n <= 1) {
return n;
}
const value = fibonacci(n - 1) + fibonacci(n - 2);
cache[n] = value;
return value;
};
console.log(fibonacci(60))
Keep in mind that this fibonacci will still only be accurate up to a certain point. Once the return value is larger than Number.MAX_SAFE_INTEGER (9007199254740991), it will be inaccurate. If that's a possibility, use and return BigInts instead.
Using two recursion results in very bad perofrmance (good for understanding recursion). You need to use loops and array beside memoization for good performance. After all heavy computation blocks main thread in JavaScript hence not a good choice for heavy computation applications.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
const cache = [1, 1]
function fibonacci(n) {
if (n <= cache.length) {
return cache[n - 1]
}
for (let i = cache.length; i < n; i++) {
cache[i] = cache[i - 1] + cache[i - 2]
}
return cache[n - 1]
}
To avoid using global you can use closure:
function fibonacci(m) {
const cache = [1, 1]
return (function (n) {
if (n <= cache.length) {
return cache[n - 1]
}
for (let i = cache.length; i < n; i++) {
cache[i] = cache[i - 1] + cache[i - 2]
}
return cache[n - 1]
})(m)
}
This is an example of dynamic programming using recursion and memoization.
Using a loop instead of recursion is faster, and if you use array destructuring it's more readable.
a = fn-1 and b = fn-2
function fibonacci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let [a, b] = [0, 1];
for (var i = 2; i <= n; i++) {
[a, b] = [b, a + b];
}
return b;
}

heap's algorithm - JavaScript

I have an alright understanding of how Heap's Algorithm works, but I can't figure out how to add each unique permutation into an array and return it based on the recursive nature of the algo.
why is it only adding the same permutation but the console log prints out the different ones?
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var heapsPermute = function (array, n, results = []) {
n = n || array.length;
if (n === 1) {
results.push(array);
console.log(array);
} else {
for (var i = 1; i <= n; i += 1) {
heapsPermute(array, n - 1, results);
if (n % 2) {
var j = 1;
} else {
var j = i;
}
swap(array, j - 1, n - 1);
}
}
return results;
};
console.log(heapsPermute(['a', 'b', 'c', 'd']));
You need to add a copy of the array, instead of the array and it's object reference.
results.push(array.slice());
// ^^^^^^^^
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var heapsPermute = function (array, n, results = []) {
n = n || array.length;
if (n === 1) {
results.push(array.slice());
} else {
for (var i = 1; i <= n; i += 1) {
heapsPermute(array, n - 1, results);
if (n % 2) {
var j = 1;
} else {
var j = i;
}
swap(array, j - 1, n - 1);
}
}
return results;
};
console.log(heapsPermute(['a', 'b', 'c', 'd']).map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Return array with factorial number from another array

This function will receive an array of positive integers and it should return a new array with the factorial of each number.
So far I came up with this but it doesn't work and I don't know where is the problem, any ideas?
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
if(nums[i] <= 1) {
return 1;
} else {
arr.push(nums[i] * getFactorials(nums[i] - 1));
}
}
return arr;
}
try this use map
var a = [1, 2, 3, 4, 5];
function fact(x) {
return (x == 0) ? 1 : x * fact(x-1);
}
console.log(a.map(fact));
Try the following:
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
let j, fact;
fact=1;
for(let j=1; j<=nums[i]; j++)
{
fact= fact*j;
}
arr.push(fact);
}
return arr;
}
let res = getFactorials([5,9])
console.log(res);
Try this way:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
arr.push(factorial(nums[i]));
}
return arr;
}
getFactorials([6,5,3])
const factorial = (n) => {
let res = [];
while(n != 0){
//get all integers less than or equal to n
res.push(n);
n--;
}
return res.reduce((x, y) => {
return x * y;
//reduce the array of integers into a single number via multiplication
});
}
const nums = [1, 2, 3, 4, 5];
const factorialArr = (arr) => {
return arr.map(n => {
//iterate through a list of numbers and return the factorial of each
return factorial(n);
});
}
const result = factorialArr(nums);
console.log(result) -> // Array [ 1, 2, 6, 24, 120 ]
function getFactorials(nums) {
const factNums = nums.map(
function factorial (num) {
return (num == 0 ? 1 : num * factorial(num -1));
}
)
return factNums;
}
#include <stdio.h>
int iFactorial(int iCount)
{
int iProduct = 1;
int iNumber = 1;
while (iNumber <= iCount)
{
iProduct *= iNumber;
iNumber++;
}
return iProduct;
}
int main(void)
{
int iFac[10] = {0};
int iCount = 0;
for (iCount = 0; iCount < 9; iCount++)
iFac[iCount] = iFactorial(iCount);
for (iCount = 0; iCount < 9; iCount++)
printf("\nThe value of the factorial is %d\n", iFac[iCount]);
return 0;
}

Categories

Resources