Factorial and powerset
This commit is contained in:
8
snippets/factorial.md
Normal file
8
snippets/factorial.md
Normal file
@ -0,0 +1,8 @@
|
||||
### Factorial
|
||||
|
||||
Create an array of length `n+1`, use `reduce()` to get the product of every value in the given range, utilizing the index of each element.
|
||||
|
||||
```js
|
||||
var factorial = n =>
|
||||
Array.apply(null, [1].concat(Array(n))).reduce( (a, _, i) => a * i || 1 , 1);
|
||||
```
|
||||
8
snippets/powerset.md
Normal file
8
snippets/powerset.md
Normal file
@ -0,0 +1,8 @@
|
||||
### Powerset
|
||||
|
||||
Use `reduce()` combined with `map()` to iterate over elements and combine into an array containing all combinations.
|
||||
|
||||
```js
|
||||
var powerset = arr =>
|
||||
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
|
||||
```
|
||||
Reference in New Issue
Block a user