2

I want to choose index from list, so the element[index] complies my condition. MyList[index].num==0

I tried the code bellow:

gen DescIdx2Choose keeping {
    it < MyList.size();
    MyList[it].num==0;//I tried a few way of read_only
};

How can I do it without using all_indices? Thanks

esty
  • 21
  • 1

3 Answers3

1

Since you generating DescIdx2Choose then MyList will be input to the problem. Therefore,

If seeking for the first index (if exists) then using random generation isn't required. Use the procedural code "first_index" as user3467290 suggested which is much more efficient:

var fidx := MyList.first_index(.num == 0);
if ( fidx != UNDEF ) {
   DescIdx2Choose = fidx;
} else {
   // error handling
};

If there are multiple indices and it is required to choose a random one, the most efficient way would be using "all_indices" as Thorsten suggested:

gen DescIdx2Choose keeping {
  it in read_only( MyList.all_indices(.num == 0) );
};

The reason is the random generator doesn't need to read all possible values of "MyList.num" only a shorter list of valid indices.

Amit M.
  • 208
  • 1
  • 3
0

This should do it, but MyList must fulfill the condition otherwise you get a contradiction. Pseudo-method first_index() is not bi-directional which is what we need here.

gen DescIdx2Choose keeping {
  MyList.first_index(.num == 0) == it;
};
Thorsten
  • 710
  • 8
  • 17
0

Maybe i missed something in the question, but If you always want the index of the first element that its num == 0, then why use constraints? can assign DescIdx2Choose == MyList.first_index(.num == 0). To ensure that there is at least one such element, can constrain MyList.has(.num == 0). Do you have additional constraints on DescIdx2Choose ?

user3467290
  • 706
  • 3
  • 4