Fibonacci and random
This commit is contained in:
13
snippets/fibonacci-array-generator.md
Normal file
13
snippets/fibonacci-array-generator.md
Normal file
@ -0,0 +1,13 @@
|
||||
### Fibonacci array generator
|
||||
|
||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||
Use `reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||
|
||||
```js
|
||||
var fibonacci = n =>
|
||||
Array.apply(null, [0,1].concat(Array(n-2))).reduce(
|
||||
(acc, val, i) => {
|
||||
acc.push( i>1 ? acc[i-1]+acc[i-2] : val);
|
||||
return acc;
|
||||
},[]);
|
||||
```
|
||||
7
snippets/random-number-in-range.md
Normal file
7
snippets/random-number-in-range.md
Normal file
@ -0,0 +1,7 @@
|
||||
### Random number in range
|
||||
|
||||
Use `Math.random()` to generate a random value, map it to the desired range using multiplication.
|
||||
|
||||
```js
|
||||
var randomInRange = (min, max) => Math.random() * (max - min) + min;
|
||||
```
|
||||
7
snippets/randomize-order-of-array.md
Normal file
7
snippets/randomize-order-of-array.md
Normal file
@ -0,0 +1,7 @@
|
||||
### Randomize order of array
|
||||
|
||||
Use `sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
|
||||
|
||||
```js
|
||||
var randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1)
|
||||
```
|
||||
Reference in New Issue
Block a user