1

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!

Giacomo Ciampoli
  • 821
  • 3
  • 16
  • 33
  • 1
    check [this](https://stackoverflow.com/questions/39927452/recursively-print-all-permutations-of-a-string-javascript) question, the last answer is the best IMHO with [this algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm) with the last algorithm it takes few milliseconds to generate the permutations. One note: limit the amout of max permutations, otherwise it'll crash – Margon Jul 16 '18 at 09:09
  • thanks, my mistake was generating all the permutation in one time – Giacomo Ciampoli Jul 16 '18 at 10:56

0 Answers0