How can I find all of the permutations consisting of 1 element from a variable number of arrays of variable length?

后端 未结 4 1376
名媛妹妹
名媛妹妹 2020-12-12 02:36

I have an array U of arrays D that vary in length. I need to be able to return all permutations of array indices that would select a different perm

4条回答
  •  天命终不由人
    2020-12-12 03:20

    To tack on to what Anon said, you don't just loop over them. You maintain state in your class so that you know what your last index was for each array. The logic is the same, but you don't run in a continuous loop. The pseudo-code logic would be:

    get_next()
    {
      oldn3 = this.n3;
      oldn2 = this.n2;
      oldn1 = this.n1;
    
      if(this.n3 == this.a3.Count)
         this.n3 = 0;
      else
         this.n3++;
    
      if(oldn3 > this.n3)
        if(this.n2 == this.a2.Count)
          this.n2 = 0;
        else
          this.n2++;
    
      if(oldn2 > this.n2)
        if(this.n1 == this.a1.Count)
          this.n1 = 0;
        else
          this.n1++;
    
      if(oldn1 > this.n1)
        return NO_MORE_PERMS;
    
      return [n1,n2,n3];  
    }
    
    getCurrent()
    {
      return [n1,n2,n3];
    }
    

提交回复
热议问题