Last active
September 5, 2023 10:55
-
-
Save tripolskypetr/f1e7038becdee1e5dd0b46c67a9e77af to your computer and use it in GitHub Desktop.
fibonacci sequence memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useState } from "react"; | |
import "./styles.css"; | |
const fib = (numbersQuantity) => { | |
var fibonacciNumbers = [1, 1]; | |
for (var i = fibonacciNumbers.length; numbersQuantity > i; i++) { | |
console.log("Iter"); | |
fibonacciNumbers.push(fibonacciNumbers[i - 1] + fibonacciNumbers[i - 2]); | |
} | |
return [fibonacciNumbers, fibonacciNumbers[numbersQuantity - 1]]; | |
}; | |
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987 | |
export default function App() { | |
const [value, setValue] = useState(0); | |
const handleClick = useCallback(() => { | |
const iters = parseInt(prompt("Enter number"), 10); | |
let result = -1; | |
for (let i = 3; i !== iters; i++) { | |
console.log("Begin"); | |
result = fib(i); | |
} | |
setValue(result); | |
}, []); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<p>{JSON.stringify(value, null, 2)}</p> | |
<button onClick={handleClick}>Calculate</button> | |
</div> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useState } from "react"; | |
import "./styles.css"; | |
const fib = (() => { | |
var fibonacciNumbers = [1, 1]; | |
console.log("Begin"); | |
return (numbersQuantity) => { | |
for (var i = fibonacciNumbers.length; numbersQuantity >= i; i++) { | |
console.log("Iter"); | |
fibonacciNumbers.push(fibonacciNumbers[i - 1] + fibonacciNumbers[i - 2]); | |
} | |
return [fibonacciNumbers, fibonacciNumbers[numbersQuantity - 1]]; | |
}; | |
})(); | |
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987 | |
export default function App() { | |
const [value, setValue] = useState(0); | |
const handleClick = useCallback(() => { | |
const iters = parseInt(prompt("Enter number"), 10); | |
let result = -1; | |
for (let i = 3; i !== iters; i++) { | |
console.log("Begin"); | |
result = fib(i); | |
} | |
setValue(result); | |
}, []); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<p>{JSON.stringify(value, null, 2)}</p> | |
<button onClick={handleClick}>Calculate</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment