Make Fibonacci.js file comply with standard JS rules

This commit is contained in:
Rahul Jain
2020-10-30 16:08:16 +05:30
parent 78a05970e2
commit feaca3b27a

View File

@ -72,11 +72,11 @@ const FibonacciDpWithoutRecursion = (number) => {
// Using Matrix exponentiation to find n-th fibonacci in O(log n) time // Using Matrix exponentiation to find n-th fibonacci in O(log n) time
const copyMatrix = (A) => { const copyMatrix = (A) => {
return A.map(row => row.map(cell => cell)); return A.map(row => row.map(cell => cell))
} }
const Identity = (size) => { const Identity = (size) => {
const I = Array(size).fill(null).map(() => Array(size).fill()); const I = Array(size).fill(null).map(() => Array(size).fill())
return I.map((row, rowIdx) => row.map((_col, colIdx) => { return I.map((row, rowIdx) => row.map((_col, colIdx) => {
return rowIdx === colIdx ? 1 : 0 return rowIdx === colIdx ? 1 : 0
})) }))
@ -90,12 +90,12 @@ const matrixMultiply = (A, B) => {
const l = A.length const l = A.length
const m = B.length const m = B.length
const n = B[0].length // Assuming non-empty matrices const n = B[0].length // Assuming non-empty matrices
const C = Array(l).fill(null).map(() => Array(n).fill()); const C = Array(l).fill(null).map(() => Array(n).fill())
for(let i = 0; i < l; i++) { for (let i = 0; i < l; i++) {
for(let j = 0; j < n; j++) { for (let j = 0; j < n; j++) {
C[i][j] = 0 C[i][j] = 0
for(let k = 0; k < m; k++) { for (let k = 0; k < m; k++) {
C[i][j] += A[i][k]*B[k][j] C[i][j] += A[i][k] * B[k][j]
} }
} }
} }
@ -105,15 +105,15 @@ const matrixMultiply = (A, B) => {
// A is a square matrix // A is a square matrix
const matrixExpo = (A, n) => { const matrixExpo = (A, n) => {
A = copyMatrix(A) A = copyMatrix(A)
if(n == 0) return Identity(A.length) // Identity matrix if (n === 0) return Identity(A.length) // Identity matrix
if(n == 1) return A if (n === 1) return A
// Just like Binary exponentiation mentioned in ./BinaryExponentiationIterative.js // Just like Binary exponentiation mentioned in ./BinaryExponentiationIterative.js
let result = Identity(A.length) let result = Identity(A.length)
while(n > 0) { while (n > 0) {
if(n%2 !== 0) result = matrixMultiply(result, A) if (n % 2 !== 0) result = matrixMultiply(result, A)
n = Math.floor(n/2) n = Math.floor(n / 2)
if(n > 0) A = matrixMultiply(A, A) if (n > 0) A = matrixMultiply(A, A)
} }
return result return result
} }
@ -129,13 +129,13 @@ const FibonacciMatrixExpo = (n) => {
// F(n, n-1) = pow(A, n-1) * F(1, 0) // F(n, n-1) = pow(A, n-1) * F(1, 0)
if(n === 0) return 0; if (n === 0) return 0
const A = [ const A = [
[1, 1], [1, 1],
[1, 0] [1, 0]
] ]
const poweredA = matrixExpo(A, n-1) // A raise to the power n const poweredA = matrixExpo(A, n - 1) // A raise to the power n
let F = [ let F = [
[1], [1],
[0] [0]