Mql5 code to get random items from an array

 

I got the following array 

string days[]=  {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};

how can I get a random array of three items?

 
Chrispine Oburu:

I got the following array 

how can I get a random array of three items?

template <typename X>
void shuffle_array(X &from_array[],//your source array
                   X &to_array[],//your destination array
                   int total){//the amount of items to get from the source array to the destination array
if(total>0){
//check total
if(total>ArraySize(from_array)){total=ArraySize(from_array);}
//prepare destination
ArrayResize(to_array,total,0);
//available spots array 
  int spots[];
  ArrayResize(spots,ArraySize(from_array),0);
  int total_spots=ArraySize(from_array);
  for(int i=0;i<ArraySize(spots);i++){spots[i]=i;}
//loop and pick spots
  for(int p=0;p<total;p++)
  {
  //pick a random spot from the available spots 
    int pick=random_int(0,total_spots-1);
    to_array[p]=from_array[spots[pick]];
  //remove that spot from availability
    spots[pick]=spots[total_spots-1];
    total_spots--;
  }
//loop and pick spots   
}}

int random_int(int from,int to){
double r=((double)MathRand())/((double)32767.0);
double range=to-from;
r*=range+from;
int result=(int)r;
if(result<from){result=from;}
if(result>to){result=to;}
return(result);
}
int OnInit()
  {
//--- create timer
  string days[]=  {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
  string picks[];
  shuffle_array(days,picks,7);
  for(int i=0;i<ArraySize(picks);i++){Print(picks[i]);}   
//---
   return(INIT_SUCCEEDED);
  }

Try this 

 
Thanks its working
 
Lorentzos Roussos #:

Try this 

How can I modify the output to be one string example

"Sunday Monday Tuesday"
 
void OnInit()
  {
//-
   string days[]=  {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};;
   string chosen_days_of_week="";

   for(int i=0; i<3; i++)
     {
      swap(days[i],days[somePos(ArraySize(days),i)]);
      chosen_days_of_week+=" "+days[i];
     }
//trim
   chosen_days_of_week=StringSubstr(chosen_days_of_week,1);

   Print(chosen_days_of_week);
//Friday Sunday Tuesday
  }
//+------------------------------------------------------------------+
void swap(string &a,string &b)
  {
   string temp=a;
   a=b;
   b=temp;
  }
//+------------------------------------------------------------------+
int somePos(int size, int from)
  {
   int generated=MathRand();
//avoid double counting zero
   if(generated==0
//avoid repetition
      ||generated%size<from)
      return somePos(size,from);

   return generated%size;
  }
//+------------------------------------------------------------------+
Reason: