Created
November 10, 2019 20:13
-
-
Save gkucmierz/94d3b6a6055077ccf3abfd2cb1a4a223 to your computer and use it in GitHub Desktop.
fibonacci bf generate code
This file contains hidden or 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
| // code that generates BF (hardcoded) solution using js | |
| // https://www.codewars.com/kata/bf-n-th-fibonacci-number/train/bf | |
| const MAX = 100; | |
| const flag = '+>'; | |
| const inp = ','; | |
| const nestedLoop = n => { | |
| if (n > MAX) return ''; | |
| return `-[ | |
| ${nestedLoop(n+1)} | |
| ] | |
| < [[-] > ${int2bf(fib(n))} [-] <] > | |
| `; | |
| }; | |
| const int2bf = i => { | |
| return (i+'').split``.reduce(([mem, res], d) => { | |
| const code = d.charCodeAt(); | |
| const dist = code - mem; | |
| const sign = dist < 0 ? '-' : '+'; | |
| return [code, [...res, sign.repeat(Math.abs(dist)) + '.']]; | |
| }, [0, []])[1].join``; | |
| }; | |
| const fib = (() => { | |
| const map = new Map(); | |
| return n => { | |
| if (n in map) return map[n]; | |
| if (n === 1) return 1n; | |
| if (n === 2) return 1n; | |
| return map[n] = fib(n-1) + fib(n-2); | |
| }; | |
| })(); | |
| console.log([ | |
| flag, inp, | |
| '[', nestedLoop(1), ']' | |
| ].join`\n`.replace(/[^\+\-\<\>\[\]\,\.]/g, '')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment