## Selecting Random Elements from a List Without Repetition

richard
User
Posts: 23
Joined: 7 months ago

### Selecting Random Elements from a List Without Repetition

An example: I have a set i /1*750/;
and I want to choose 10 of them but without repetition, so

[10 ,14,2,8,25,100,68,95,225,603,741]
is a correct subset and

[42,58,69,153,284,652,453,362,269,153]
is incorrect.

how can Select 10 random element of a given set , without repetition, by GAMS?

bussieck
Moderator
Posts: 271
Joined: 2 years ago

### Re: Selecting Random Elements from a List Without Repetition

Here are two solutions: The first uses the new embedded code facility (https://www.gams.com/latest/docs/UG_EmbeddedCode.html) to execute Python code. In Python, the random selection is a one liner. The second solution is pure GAMS using the somewhat obscure "option shuffle" functionality (https://www.gams.com/latest/docs/UG_Opt ... ch=shuffle):

Code: Select all

``````set i /1*750/, ii(i); scalar k;

for (k=1 to 5,
embeddedCode Python:
import random
gams.set('ii',random.sample(list(gams.get('i')), 10))
endEmbeddedCode ii
display 'Python:',ii;
)

Parameter A(i);
for (k=1 to 5,
option shuffle=A, clear=ii;
ii(i) = A(i)<=10;
display 'GAMS:', ii;
)
``````
-Michael

richard
User
Posts: 23
Joined: 7 months ago

### Re: Selecting Random Elements from a List Without Repetition

, thank you very much Michael .

Best wishes

richard
User
Posts: 23
Joined: 7 months ago

### Re: Selecting Random Elements from a List Without Repetition

i use your solution but i have error!!

why i get this error ? unknown option
Last edited by richard 7 months ago, edited 2 times in total.

bussieck
Moderator
Posts: 271
Joined: 2 years ago

### Re: Selecting Random Elements from a List Without Repetition

What version of GAMS do you use? shuffle was introduced in 24.6 (https://www.gams.com/latest/docs/RN_246.htm#g2461_GAMS) embedded code even later.
-Michael

richard
User
Posts: 23
Joined: 7 months ago

### Re: Selecting Random Elements from a List Without Repetition

I have GAMS 24.1.2

Is there any way that I use this option?