How to print values from a multidimensional array in MQL5? - arrays

In MQL4, I could use the following function to print values from a two-dimensional array:
string Arr2ToString(double& arr[][], string dlm = ",", int digits = 2) {
string res = "";
int i, j;
for (i = 0; i < ArrayRange(arr, 0); i++) {
res += "[";
for (j = 0; j < ArrayRange(arr, 1); j++) {
res += StringFormat("%g%s", NormalizeDouble(arr[i][j], digits), dlm);
}
res = StringSubstr(res, 0, StringLen(res) - StringLen(dlm));
res += "]" + dlm;
}
res = StringSubstr(res, 0, StringLen(res) - StringLen(dlm));
return res;
}
However in MQL5 (version 5.00, build 1966), above function no longer works and it errors with:
'[' - invalid index value Array.mqh
in the first line when arr[][] is passed.
I've checked and MQL5 no longer allows passing an array with no dimension sizes.
When passing multidimensional arrays to a function, dimension sizes (except for the first one) should be specified:
double var[][3][3];
void Func(double &arg[][3][3]){ // ... }
Source: MQL5 PROGRAMMING BASICS: ARRAYS.
This doesn't make sense.
Assuming I don't know the size of my array (as I want to re-use this function for multiple array types, and defining dozens of separate functions for each size is ridiculous), how it is possible now to print values from a multidimensional array storing double values (such as two-dimensional array as example)?

I know this is not ideal, but we can use ArrayPrint() to print array.
Refer here for the documentation
void ArrayPrint(
const void& array[], // printed array
uint digits=_Digits, // number of decimal places
const string separator=NULL, // separator of the structure field values
ulong start=0, // first printed element index
ulong count=WHOLE_ARRAY, // number of printed elements
ulong flags=ARRAYPRINT_HEADER|ARRAYPRINT_INDEX|ARRAYPRINT_LIMIT|ARRAYPRINT_ALIGN
);
Here is another approach to pass multi-dimentional array to a function, again it is not ideal, but it works properly.
//+------------------------------------------------------------------+
//| Struct that is used to hold multi-dimentional array |
//+------------------------------------------------------------------+
template<typename T>
struct MultiDimentionalArray
{
T index2[];
};
//+------------------------------------------------------------------+
//| Array print function that accepts MultiDimentionalArray struct |
//+------------------------------------------------------------------+
string Arr2ToString(MultiDimentionalArray<double> &arr[],string dlm=",",int digits=2)
{
string res="";
int i,j;
for(i=0; i<ArraySize(arr); i++)
{
res+="[";
for(j=0; j<ArraySize(arr[i].index2); j++)
{
res+=StringFormat("%g%s",NormalizeDouble(arr[i].index2[j],digits),dlm);
}
res = StringSubstr(res,0,StringLen(res) - StringLen(dlm));
res+= "]" + dlm;
}
res=StringSubstr(res,0,StringLen(res)-StringLen(dlm));
return res;
}
Here is an example execution
void OnStart()
{
//--- Declaring an array
MultiDimentionalArray<double> arr[];
//--- Adding values to the array
for(int i=0;i<10;i++)
{
//--- Resizing the array - 1st dimention
if(ArraySize(arr)<=i) ArrayResize(arr,ArraySize(arr)+1);
for(int j=0;j<10;j++)
{
//--- Resizing the array - 2nd dimention
if(ArraySize(arr[i].index2)<=j) ArrayResize(arr[i].index2,ArraySize(arr[i].index2)+1);
arr[i].index2[j]=i*j;
}
}
//--- Getting the result as string
string arrResult=Arr2ToString(arr);
//--- Printing the result string
Print(arrResult);
}
Here is the result I got in the experts tab, from the execution of the above code
2019.06.11 16:25:47.078 Arrays (EURUSD,H1) [0,0,0,0,0,0,0,0,0,0],[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,10,12,14,16,18],[0,3,6,9,12,15,18,21,24,27],[0,4,8,12,16,20,24,28,32,36],[0,5,10,15,20,25,30,35,40,45],[0,6,12,18,24,30,36,42,48,54],[0,7,14,21,28,35,42,49,56,63],[0,8,16,24,32,40,48,56,64,72],[0,9,18

Related

Problem accessing multidimensional array length and fields

Here is code to test a multidimensional array
public class Multiarraytest {
public int size_main = 5;
public int size_aux = 20;
Multiarraytest() {
float[][] float_mul = new float[size_main][size_aux];
}
void init_int(Multiarraytest mul) {
int i, j = 0;
while(i < mul.length) {
while(j < mul[i].length) {
mul[i][j] = (i + (j/10));
j++;
}
i++;
}
}
public static void main(String[] args) {
}
}
But
here are the results of javac Multiarraytest.java.
error: cannot find symbol While(i < mul.length)
^
symbol: variable length
location: variable mul of type Multiarraytest
error: array required, but Multiarraytest found while(j < mul[i].length
^
error: array required, but Multiarraytest found mul[i][j] = (i + (j/10));
I have not found what's going wrong.
mul is a 2 dimensional array
mul.length should give the length of the first array
mul[1] should lead to the array nested in the first case of mul
mul[1].length should give the length of the array nested in the first case of mul
mul[1][2] should give access to read/write of the second case of the array nested in the first case of mul.
Where have I made a mistake?
This is a cut down version of what I was doing but same errors are reported. I read tutorial and close copy-cut it. Except it's a float multidimensional array instead of int multidimensional array and I try to fill it in a loop instead at the initializing time.

How to print each element from array of unknown length in C

.I have a big array of coordinates that looks like this
triangle_t teapot_model[] = {
{
.x1=5,
.y1=10,
},
{
.x1=20,
.y1=30,
},
(keeps going)
How can I print all of the items in this array without knowing their position?
I want this output:
Output:
.x1=5 y1=10
.x1=20 .y1=30
Array in C always has a size although implicit in your case.
To simply print each element of your array, using the below code should suffice
int sizearray = sizeof teapot_model / sizeof *teapot_model;
for (int i = 0; i < sizearray; i++)
{
printf(".x1=%d .y1=%d\n", teapot_model[i].x1, teapot_model[i].y1);
}

function should take two arguments , an array and the size of the array

I need help with the following please:
define a function that returns the population of the smallest city
(popolation wise) in an array of cities. the function should take two
arguments: an array of cities and the length of the array.
this is my code:
struct city
{
char name[20];
int pop;
};
int func1(struct city cities[], int i) // these are the arguments
{
for(i=0; i<2; i++)
{
cities[i].pop;
}
cities[0].pop=2500;
cities[1].pop=3000;
return cities[0].pop;
}
I just want this to work, but it dosnt compile and dosnt give errors ether.
There are few errors in your code.
For instance, you can't find the array size by looping in the array. It only works for "string" because they have a end character '\0'.
The size of the array, as you mentionned is passed on the second argument of your function.
So what you want to do is, I suppose :
int func1(struct city cities[], size_t i) // these are the arguments
{
if (i == 0)
return 0;
int min = cities[0].pop;
for(size_t j=1; j < i; ++j)
{
min = cities[i].pop < min ? cities[i].pop : min;
}
return min;
}
Regards.

C-Passing an 3d array,allocation and population

let's say I have a functions below.
void function createBands(boolean option) {
int i, j;
int ***bands = (int ***)malloc((SIZE + 1) * sizeof(int **));
for (i = 0; i < SIZE; i++) {
bands[i] = (int **)malloc(HEIGHT * sizeof(int *));
for (j = 0; j < HEIGHT; j++)
bands[i][j] = (int *)malloc(WIDTH * sizeof(int));
}
iterator *it =
createIterator(params); // do not be confused it is a structure with
// methods andaeribute just like Iterator class in
// java . Methods are poniters to functions.
repare_array(bands[Size], it);
}
void prepare_array(int **band, iterator *it) { read_array(band, it); }
read_array(int **band, iterator *it) {
for (int i = 0; i < Height; i++)
band[i] = (int *)it->next();
}
// Now in Iterator.c I have the iterator structure with the methods etc I will
// write just some line form iterator.
void *next() {
byte *b =
a function that reads bytes form a file and returns byte * CORECTLY !!!;
return b == NULL ? NULL : bytetoT(b);
// this function make void form byte conversion but it doesnt work so I make
// only a cast in read_aray as you see. SUppose just return b wich is byte(i
// know in C isn't any byte but I redeclared all the types to be JAVA.)
}
the questions is where I should allocate the bands because in this situation the 1D vector return by function is ok because I see the values in the function scope. But when it is return to array[i] I got a unallocated 3dVector.
I need to recieve bands[size][i][j] with the data form b. In b the data is good then I ve gote bands null.
What I have do so far I make another allocation in prepare aray before the call to read_array where I allocate **band and then I have some results but I am not confident.
Sorry for the confusion! And every comment is good for me. Maybe what I have do is ok I do not know!.
I am not new to C I just do not work with pointers for a long time.
If it is a 2D pointer(**) you have to assign it with the address of 2D array and if it is 1D array you have to assign it with the address of 1D array.
For your read_array function
read_array(int**array...)
{
for(i=0;i<HEIGHT(the same as in allocation);i++)
`enter code here`array[i] = function();//function return an 1D array
}
Make sure that function() returns the address of the 1D array.

How to find the length of an integer array passed as an argument in c?

I need to calculate the length of passed array in monkey method. How to do so, as input decays to a pointer inside monkey method...?
int monkey(int input1[])
{
//Write code here
}
Constraints:
1) You are not allowed to change the function signature.
int monkey(int input1[], size_t arraySize)
{
}
Passing the size of the array is the most usual method.
Alternatively you can do something like C strings, and add a sentinel value to the end of your array (max value, 0, -1, etc) and count the number of elements before this sentinel value.
There are no other alternatives I can think of.
In the general case, you don't. As it's just a pointer, information about the array is not available.
So you should pass in a size, or wrap it in a struct that contains the size.
Or as it's an array of int, you could use the first value in the array as the size.
Alternatively, depending on your use-case, you could zero-terminate (or else unambiguously mark the end of) the data in the array.
There is no way to do such thing in C. The definition of your function
int monkey(int input[])
is formally equivalent to
int monkey(int *input)
so you ALWAYS need to pass the length of your array as an additional parameter
Two options:
int array[10+1];
array[0] = 10;
// fill in the rest in array[1...10]
monkey(array);
// monkey() checks input1[0] to see how many data elements there are
and
int array[10+1];
array[0] = 10;
// fill in the rest in array[1...10]
monkey(array + 1);
// monkey() checks input1[-1] to see how many data elements there are
Alternatively, you can pass the size/count via a different channel, for example, a global variable, which you may guard with a critical section or a semaphore/lock if necessary.
When you pass the array to the function, you can store the length as the first element of the array:
int monkey(int input1[])
{
int len = input1[0];
for (int i = 1; i < len; ++i) {
// do something with the array
}
}
//...
int array[20];
array[0] = 20;
monkey(array);
An alternative method is to do it using pointer arithmetics instead, so that the function can treat the array as starting from 0:
int monkey(int input1[])
{
int len = *(input1 - 1);
for (int i = 0; i < len; ++i) {
// do something with the array
}
}
//...
int array[20];
array[0] = 19;
monkey(array + 1);
But it's the same thing really. The only advantage this has is guarding against mistakes like starting from 0 instead of 1. But then this means that you could forget to pass array + 1 when you call it. So meh.
int main()
{
int arr[] = { 62,34,4,4,4,3,2,-1 };
monkey(arr);
return 0;
}
int monkey(int input1[])
{
int n = 0;
while (a[n] != -1)
{
n++;
}
printf_s("Length of input1[] is: %d", n);
return n;
}
int monkey(int input1[])
{
//Write code here
}
int len = sizeof(input1)/sizeof(input1[0]);
OR
int len = sizeof(input1)/sizeof(int);
is WRONG..
IT will always give 2..as input1 is a LONG POINTER AND so size is 8,,and sizeof(int) is 4..
if you want to find the length there is 2 ways...
1) pass the length...
( you cannot i suppose )
2) if you have idea..about the input1 array...say ( TECH GIG competition )
try to find out the number contained in the undefined parts of the array..
say here i found out for the sample ..{1,2,3,4,5} => input1[6] => contains the number -9999
so just wrote a while loop to find the length
while(input1[len]!=-9999)
len++;
to find out that
input1[6] => contains the number -9999
i use in the answer
return input1[6]..to check
that -9999 was the answer
i just submitted the answer for TECH GIG competition

Resources