I'm working on an app in which, give an array of colors (exadecimal values) it generate all the possibile permutation of that array; in order to shuffle the colors; demo: https://d2hxezalm5sz4p.cloudfront.net/
so when the grandient component is load a function setPermutation is fired:
class Gradient extends Component {
componentWillMount(){
this.props.setPermutations()
console.log('[Gradient.js] componentWillMount')
}
In the App.js
async setPermutations(){
const permutations = await this.permutation(this.state.colors) // this generate an array of all permutations
const perm_gen = this.permutation_gen(permutations.slice(1)) //convert array in a generator, a button will set the next value to the gradient container
this.setState({
perm_gen,
colorPermutations: permutations
})
}
this.permutation()
code take from: JavaScript - Generating all combinations of an array, considering the order
permutation(array) {
function p(array, temp) {
let i, x;
if (!array.length) {
result.push(temp);
}
for (i = 0; i < array.length; i++) {
x = array.splice(i, 1)[0];
p(array, temp.concat(x));
array.splice(i, 0, x);
}
}
const result = [];
p(array, []);
return result
}
this.permutation_gen()
permutation_gen = function*(permutations){
for (let p of permutations){
yield p
}
}
And the shuffle()
method on the button:
shuffle(){
const value = this.state.perm_gen.next()
if (!value.done){
this.setState({
colors: value.value
})
}else{
const perm_gen = this.permutation_gen(this.state.colorPermutations)
this.setState({
perm_gen,
colors: perm_gen.next().value
})
}
Now, since permutation operation is O(n!), for n = 9 it takes 362880 steps, so for now I set a limit to the number of element to permute.
There is a way to improve this? maybe with buffer or streams (I dont know much about them yet)
Thanks!