Permutations/combinations_demo.mq5

92 lines
6.1 KiB
MQL5
Raw Permalink Normal View History

2025-09-19 20:23:18 +00:00
<EFBFBD><EFBFBD>//+------------------------------------------------------------------+
//| demo_combinations.mq5 |
//| Copyright <EFBFBD> 2018, Amr Ali |
//| https://www.mql5.com/en/users/amrali |
//+------------------------------------------------------------------+
#property copyright "Copyright <00> 2018, Amr Ali"
#property link "https://www.mql5.com/en/users/amrali"
#property version "1.000"
#property description "A demo for combinations in MQL."
#property strict
#property script_show_inputs
#include <Permut_library.mqh>
sinput string s; //different ways to choose a committee of K out of N candidates
input int N = 5;
input int K = 3;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
/**
* Convert the input array into a string and returns the result.
* The returned string will separate the elements in the array
* with commas like "[1,5,3,4]".
*/
template<typename T>
string arrayToString(const T &arr[])
{
int size=ArraySize(arr);
if(!size) return "[]";
string str= "["+(string)arr[0];
for(int i = 1; i<size;++i)
str+=", "+(string)arr[i];
str+="]";
return (str);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnStart()
{
// dynamically allocate and intialize the candidates array
int candidates[];
ArrayResize(candidates,N);
for(int i=0; i<N; i++)
{
candidates[i]=i+1;
}
printf("The candidates array: %s",arrayToString(candidates));
printf("The possible combinations of %i persons chosen from %i should be: %I64i",K,N,nCk(N,K));
// 5C3 = 5 * 4 * 3 / (3 * 2 * 1) = 10
// store number of combinations generated
int counter=0;
// array to receive combinations one by one
int result[];
// choose "k out of n items"
CombinationsIterator<int>comboIt(candidates,K,result);
do
{
// output this combination
printf("%i: %s",counter++,arrayToString(result));
}
while(comboIt.next(result));
}
//+------------------------------------------------------------------+
/* sample output
combinations_demo (GBPUSD,M1) The candidates array: [1, 2, 3, 4, 5]
combinations_demo (GBPUSD,M1) The possible combinations of 3 persons chosen from 5 should be: 10
combinations_demo (GBPUSD,M1) 0: [1, 2, 3]
combinations_demo (GBPUSD,M1) 1: [1, 2, 4]
combinations_demo (GBPUSD,M1) 2: [1, 2, 5]
combinations_demo (GBPUSD,M1) 3: [1, 3, 4]
combinations_demo (GBPUSD,M1) 4: [1, 3, 5]
combinations_demo (GBPUSD,M1) 5: [1, 4, 5]
combinations_demo (GBPUSD,M1) 6: [2, 3, 4]
combinations_demo (GBPUSD,M1) 7: [2, 3, 5]
combinations_demo (GBPUSD,M1) 8: [2, 4, 5]
combinations_demo (GBPUSD,M1) 9: [3, 4, 5]
*/