Selecting Random Elements from a List Without Repetition

Archive of Gamsworld Google Group
Post Reply
richard
User
User
Posts: 22
Joined: 3 months ago

Selecting Random Elements from a List Without Repetition

Post by richard » 3 months ago

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?

User avatar
bussieck
Moderator
Moderator
Posts: 208
Joined: 2 years ago

Re: Selecting Random Elements from a List Without Repetition

Post by bussieck » 3 months ago

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
User
Posts: 22
Joined: 3 months ago

Re: Selecting Random Elements from a List Without Repetition

Post by richard » 3 months ago

:D , thank you very much Michael .

Best wishes

richard
User
User
Posts: 22
Joined: 3 months ago

Re: Selecting Random Elements from a List Without Repetition

Post by richard » 3 months ago

i use your solution but i have error!!


why i get this error ? unknown option
Last edited by richard on Mon Aug 27, 2018 2:08 pm, edited 2 times in total.

User avatar
bussieck
Moderator
Moderator
Posts: 208
Joined: 2 years ago

Re: Selecting Random Elements from a List Without Repetition

Post by bussieck » 3 months ago

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
User
Posts: 22
Joined: 3 months ago

Re: Selecting Random Elements from a List Without Repetition

Post by richard » 3 months ago

I have GAMS 24.1.2

Is there any way that I use this option?

Post Reply