MQL4 array creating variables - arrays

I'm trying to make this function create X number of variables using an array. I know that this is technically wrong because I need a constant as my array's value (currently 'x'), but excluding that, what am I missing? Looked at so many code samples and can't figure it out, but I know it's got to be simple...
void variables()
{
int i;
int bars = 10;
int x = 1;
for (i = 1; i <= bars+1; i++)
{
int variables[bars] = { x };
x++;
if (i >= bars+1)
{
break;
}
}

void variables()
{
int bars = 10;
if(bars >= Bars) bars = Bars - 1;
// to be able to set array size based on variable,
// make a dynamically sized array
double highvalues[];
ArrayResize(highvalues, bars);
for (int i = 0 /*Note: Array index is zero-based, 0 is first*/; i <= bars; i++)
{
highvalues[i] = iHigh(NULL, 0, i);
// or
highvalues[i] = High[i];
}
}

It is hard to tell what do you want to achieve.
If you want to fill an array with a value ArrayFill() fill help you.

Related

cocos2dx : Change Array to Vector

I need to change Array to Vector as it is being depracted in cocos2dx.
Earlier it was running but after deprecation its giving error.
As I am quite new to cocos2dx I am not able to resolve this issue.
Here is my code:
int BaseScene::generateRandom()
{
//int rn = arc4random()%6+1;
int rn = rand() % 6 + 1;
Array * balls = (Array*)this->getChildren();
Array * ballsTypeLeft = Array::create();
// if(balls->count() <= 7)
{
for (int j=0; j<balls->count(); j++)
{
Node * a = (Node*)balls->objectAtIndex(j);
if(a->getTag() >= Tag_Ball_Start)
{
Ball * currentBall = (Ball*)balls->objectAtIndex(j);
bool alreadyHas = false;
for(int k=0;k<ballsTypeLeft->count();k++)
{
if(strcmp(((String*)ballsTypeLeft->objectAtIndex(k))->getCString(), (String::createWithFormat("%d",currentBall->type))->getCString()) == 0)
{
alreadyHas = true;
}
}
if(alreadyHas)
{
}
else
{
ballsTypeLeft->addObject(String::createWithFormat("%d",currentBall->type));
}
}
}
}
// CCLog("%d",ballsTypeLeft->count());
if(ballsTypeLeft->count() <=2)
{
// int tmp = arc4random()%ballsTypeLeft->count();
int tmp = rand() % ballsTypeLeft->count();
return ((String*)ballsTypeLeft->objectAtIndex(tmp))->intValue();
}
return rn;
}
How can I make this method working?
Please convert this method using Vector.
Thanks
To change cocos2d::Array to cocos2d::Vector, you must first understand it. cocos2d::Vector is implemented to mimick std::vector. std::vector is part of the STL in c++. cocos2d::Vector is built specifically to handle cocos2d::Ref. Whenever you add a Ref type to Vector it automatically retained and then released on cleanup.
Now to change Array to Vector in your code:
Store children this way:
Vector <Node*> balls = this->getChildren();
Access ball at index i this way:
Ball* ball = (Ball*)balls.at (i);
Add elements to vector this way:
balls.pushBack (myNewBall);
EDIT -
From what I understand, you want to get a random ball from the scene/layer. You can perform this by simply returning the Ball object:
Ball* BaseScene::generateRandom()
{
Vector <Node*> nodeList = this->getChildren();
Vector <Ball*> ballList;
for (int i = 0; i<nodeList.size(); i++)
{
if (ball->getTag() >= Tag_Ball_Start)
{
Ball * ball = (Ball*)nodeList.at(i);
ballList.pushBack(ball);
}
}
if (ballList.size() > 0)
{
return ballList[rand() % ballList.size()];
}
return nullptr;
}
If there is no ball it will return NULL which you can check when you call the function. The code you have linked below seems to make use of Arrays outside the function. You need to make the changes to accommodate that. I suggest studying the documentation for Vector.

Out of bounds 2D array error in C

Im stuck on this one part and I was hoping to get some help. I have a project that is basically a word search. The program reads in a file that contains the Rows and columns followed by the word search puzzle itself. You are required to create possible combinations of strings from the word search and check those combinations with a dictionary that is provided as another text document.
Here's an example of the file read in 1st is Rows and 2nd is Cols followed by the word search puzzle:
4 4
syrt
gtrp
faaq
pmrc
So I have been able to get most of the code to work except for the function that creates strings for the above file. Basically It needs to search the wordsearch and create strings, each created string gets passed on to another function to check if it's in the dictionary. However my code keeps going out of bounds when creating the strings, and it's continuing to cause Seg faults which is really frustrating.
Theses are the constants that are declared, its every possible direction to go while searching the word search puzzle for possible string combinations
const int DX_SIZE = 8;
const int DX[] = {-1,-1,-1,0,0,1,1,1};
const int DY[] = {-1,0,1,-1,1,-1,0,1};
This is the function I have to create the strings:
int strCreate(char** puzzle, char** dictionary, int n, int rows, int col){
int x, y;
int nextX, nextY, i;
char str[20] = {0};
int length = 1;
for(x = 0; x < rows; x++)
{
for(y = 0; y < col; y++)
{
//Grabs the base letter
str[0] = puzzle[x][y];
length = 1;
for(i = 0; i < DX_SIZE; i++)
{
while(length < MAX_WORD_SIZE)
{
nextX = x + DX[i]*length;
nextY = y + DY[i]*length;
// Checking bounds of next array
//This is where I'm having trouble.
if((x + nextX) < 0 || (nextX + x) > (col-1)){
printf("Out of bounds\n");
break;
}
if((y + nextY) < 0 || (nextY + y) > (rows-1)){
printf("Out of bounds\n");
break;
}
str[length] = puzzle[nextX][nextY];
//search for str in dictionary
checkStr(str, dictionary, n);
length++;
}
memset(&str[1], '\0', 19);
}
}
}
return 0;
}
I know i'm not checking the bounds properly I just can't figure out how to. When X = 1 and nextX = -1, that passes the bounds check, however say the array is at puzzle[0][0] nextX would put puzzle[-1][0] which is out of bounds causing the seg fault.
Thank you for taking the time to read, and I appreciate any help at all.
nextX and nextY are the indices used to access the array puzzle. Then the array bound check should also include the same. But the array bound check includes for example x+nextX.
// Checking bounds of next array
//This is where I'm having trouble.
if((x + nextX) < 0 || (nextX + x) > (col-1)){
printf("Out of bounds\n");
break;
}
Example:
if( nextX < 0)
printf("Out of bounds...\n");

Need help understanding logic of function

monthly->maxTemperature = yearData[i].high;
monthly->minTemperature = yearData[i].low;
I just can't seem to understand the logic of what the iterations will look like or how to access the proper elements in the array of data to get the proper data for each month.... without corrupting data. Thanks!
You're on the right track:
void stats(int mth, const struct Data yearData[], int size, struct Monthly* monthStats)
{
// These are used to calc averages
int highSum = 0;
int lowSum = 0;
int days = 0;
// Initialize data
monthly->maxTemperature = INT_MIN;
monthly->minTemperature = INT_MAX;
monthly->totalPrecip = 0;
for (int i = 0; i < size; ++i) {
// Only use data from given month
if (yearData[i].month == mth) {
days += 1;
if (yearData[i].high > monthly->maxTemperature) monthly->maxTemperature = yearData[i].high;
if (yearData[i].low < monthly->minTemperature) monthly->minTemperature = yearData[i].low;
highSum += yearData[i].high;
lowSum + yearData[i].low;
monthly->totalPrecip += yearData[i].precip;
}
}
if (0 != days) {
monthly->avgHigh = highSum / days;
monthly->avgLow = lowSum / days;
}
}
Before working on the assignment it's a good idea to examine the API that you need to implement for clues. First thing to notice is that the reason the struct Monthly is passed to your function by pointer is so that you could set the result into it. This is different from the reason for passing struct Data as a pointer*, which is to pass an array using the only mechanism for passing arrays available in C. const qualifier is a strong indication that you must not be trying to modify anything off of the yearData, only the monthStats.
This tells you what to do with the min, max, average, and total that you are going to find in your function: these need to be assigned to fields of monthStats, like this:
monthStats->maxTemperature = maxTemperature;
monthStats->minTemperature = minTemperature;
...
where maxTemperature, minTemperature, and so on are local variables that you declare before entering the for loop.
As far as the for loop goes, your problem is that you ignore the mth variable completely. You need to use its value to decide if an element of yearData should be considered for your computations or not. The simplest way is to add an if to your for loop:
int maxTemperature = INT_MIN; // you need to include <limits.h>
int minTemperature = INT_MAX; // to get definitions of INT_MIN and INT_MAX
for(int i = 0; i<size; ++i) {
if (yearData[i].month < mth) continue;
if (yearData[i].month > mth) break;
... // Do your computations here
}
* Even though it looks like an array, it is still passed as a pointer

Initialize an "eye" (identity) matrix array in C

int eye[3][3] = {
{ 1,0,0 },
{ 0,1,0 },
{ 0,0,1 }
};
Is there a shorter way to initialize it? It's so regular that there must be a smarter way to initialize it, especially if it's more than 3x3, say 10x10 or more.
In c99 you can write:
int eye[][3] = { [0][0] = 1, [1][1] = 1, [2][2] = 1 };
all other elements are zeroed, moreover the compiler figures out the size of the array for you. Just don't skip the second size (3).
Btw. in your code you don't have to use the double braces, this would be fine too:
int eye[3][3] = {
1,0,0,
0,1,0,
1,0,1,
};
In c99 you can also leave the trailing comma, just for symmetry and future refactorings
Other solutions probably require you to write some code, which may indeed save you some time/space in file. But note that this way you're splitting declaration and "initialization", which in case of e.g. globals can make a difference.
You can use designated initializers:
int eye[3][3] = { [0][0]=1, [1][1]=1, [2][2]=1};
All the other elements will be initialized to 0 as per C standard's guarantee.
You may try the following:
#define SIZE 3
int eye[SIZE][SIZE] = {0};
for (int i = 0; i < SIZE ; ++i)
{
eye[i][i] = 1;
}
If you want to store {{ 1,0,0 }, { 0,1,0 }, ...} this style of values in square matrix means, you can write a simple logic as below.
#define SIZE 3
int eye[SIZE][SIZE] = {0};
int *p = (int *)eye;
for (i = 0; i < (SIZE * SIZE); i = i + (SIZE + 1))
{
p[i] = 1;
}
or
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (i == j)
{
eye[i][j] = 1;
}
else
{
eye[i][j] = 0;
}
}
}
Note : Above logic is only for the sample value you have given. So try to find similar logic if your values are having some relation. If not so, then no other way to initialize it directly even if size of matrix is 1000x1000.

const argument changes after array definition

I have what I consider a really strange problem. I have a function with the following prototype:
void generateNodes(const int maxX, const int maxY, node nodes[]);
As one of the first things in this function I define a 2d array of shorts, which i use as boolean values. But when I call this function the value of maxY changes to a large value. The code in question is below:
void generateNodes(const int maxX, const int maxY, node nodes[]){
int i, currentX, currentY;
short used[MAX_NODES][MAX_NODES];
//Generate the nodes
for(i = 0; i < MAX_NODES; i++){
currentX = randomNumber(0,maxX);
currentY = randomNumber(0,maxY);
nodes[i].color = 0;
nodes[i].numberOfConnections = 0;
nodes[i].id = i;
nodes[i].distanceFromStart = NOT_SET;
nodes[i].parent = NULL;
if(!used[currentX][currentY]){
nodes[i].x = currentX;
nodes[i].y = currentY;
used[currentX][currentY] = 1;
} else {
i--;
}
}
int numberOfConnections, j, currentNeighbor;
//Generate the connections
for(i = 0; i < MAX_NODES; i++){
numberOfConnections = randomNumber(1,5); //Between one and five outgoing connections
for(j = 0; j < numberOfConnections; j++){
currentNeighbor = randomNumber(0,19); //Select the neighbor
while(currentNeighbor == i){
currentNeighbor = randomNumber(0,19); //Try again while the selected is self
}
nodes[i].canReach[++(nodes[i].numberOfConnections)] = &nodes[currentNeighbor];
nodes[currentNeighbor].canReach[++(nodes[currentNeighbor].numberOfConnections)] = &nodes[i];
}
}
}
MAX_NODES is defined to 20.
Does anyone know why this might happen?
Very probably the code in ... is accessing beyond the end of used, causing arguments to be smashed. Without the code, it's of course impossible to say.
Since you do not seem to initialize the array used, it may well be that some elements are considered used (!= 0), since an array on stack is not initialized to zero, but takes whatever was in that memory area before.
An if an X,Y pair is considered used, you decrement the loop counter, possibly beyond zero into the negative realm, possibly overwriting - on the next iteration - part of the stack. This may also change the parameters, since they also reside on the same stack, before the local array.
Start with initializing used, and consider rewriting the loop to not change the loop variable except in the for statement.

Resources