我正在开发一个应用程序,其中给出一个颜色数组(极值),它生成该数组的所有可能排列;为了打乱颜色;演示:https://d2hxezalm5sz4p.cloudfront.net/
因此,在加载宏组件时,会触发setPermutation函数:
class Gradient extends Component {
componentWillMount(){
this.props.setPermutations()
console.log('[Gradient.js] componentWillMount')
}
在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()
代码取自: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
}
}
按钮上的shuffle()
方法:
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
})
}
现在,由于置换运算为O(n!),对于n = 9,它需要362880步,所以现在我为要置换的元素数设置一个限制。
有什么方法可以改善这一点?也许有缓冲区或流(我对它们还不了解)
谢谢!