Topic
1 reply Latest Post - ‏2014-03-07T09:49:15Z by davidoff
davidoff
davidoff
51 Posts
ACCEPTED ANSWER

Pinned topic how to build a set with a recursion ? Faces the error "immutable collection"

‏2014-03-06T17:55:24Z |

In the following model, I try to build recursively the collection ypos.

I have the error

The collection "ypos" is immutable because it is referenced by another element.  
note that this error disappears if I set W to 27.

Any workaround for that problem ?

Thanks

David

int W=30;
{int} widths = { 9, 12};
int minWidth = min(w in widths) w;

sorted {int} ypos; 

//given widths w1, w2, ... , wN, , compute any integer combination sum(alpha_i*wi) <=  W -  minWidth
// a recursion is a natural way : given a new element, it will combine either alone or with all the previous combinations
execute ENUM_YPOS{
  function addNew(w){
    //1. recursion
    for(var y0 in ypos){
        var y=w;
        while(y+y0<=W-minWidth){
                ypos.add(y);
                y = y + w;
        }
    }      

   //2. add w alone
    var y=w;
    while(y<=W-minWidth){
        ypos.add(y);
        y = y + w;
    }   
        
   }
   
  for(var w in widths)
        addNew(w);
  ypos.add(0);  
}   
execute{
  writeln(ypos);
} 

 

  • davidoff
    davidoff
    51 Posts
    ACCEPTED ANSWER

    Re: how to build a set with a recursion ? Faces the error "immutable collection"

    ‏2014-03-07T09:49:15Z  in response to davidoff

    All right, the error is in the loop from line 12, where we iterate on ypos and adding in ypos in the same time.

    A solution is to store all ypos values in an intermediate collection, and then iterate on this collection to increment ypos

    int W=30;
    {int} widths = { 9, 12};
    int minWidth = min(w in widths : w>0) w;
    
    
    sorted {int} ypos; 
    {int} tmp;
    //given widths w1, w2, ... , wN, , compute any integer combination sum(alpha_i*wi) <=  W -  minWidth
    // a recursion is a natural way : given a new element, it will combine either alone or with all the previous combinations
    execute ENUM_YPOS{
      function addNew(w){
        //1. recursion
        writeln(Opl.card(tmp)," elems in tmp before");
        tmp.clear();
        writeln(Opl.card(tmp)," elems in tmp after");
        for(var y0 in ypos)
            tmp.add(y0);
        for(var y0 in tmp){
            var y=w;
            while(y+y0<=W-minWidth){
                    ypos.add(y+y0);
                    y = y + w;
            }
        }      
    
       //2. add w alone
        var y=w;
        while(y<=W-minWidth){
            ypos.add(y);
            y = y + w;
        }   
            
       }
       
      ypos.add(0);  
      for(var w in widths)
            addNew(w);
    }  
     
    execute{
      writeln("Finding all ypos with widths ",widths," and W=",W);
      writeln(ypos);
    }