Moving all elements up one place in an array

Post Reply
skinner36

Moving all elements up one place in an array

Post by skinner36 »

Hi,

Moving array elements up one value to insert a new value at the beginning of the array can be a bit tedious to code. If the array has been switched around so that element 0 is the right most element then an extra degree of frustration is added to the issue.

This is how I solved the problem for my current project.

Let’s assume we have a dynamic array of 100 structures elements and the rightmost element is 0.

Code: Select all

struct TestStruct
{
   int     value1;
   double value2;
   string value3;
};

TestStruct Test[]

ArrayResize(Test, 100);      // Give it a size of 100

ArraySetAsSeries(Test, true); // Turn the array around so the element 0 is the far right one
Now, your program has been working as you intended but the array is now full of data and you want to add the new element to the beginning of the array at element 0 (farthest right element) and move all of the other element values up one and drop the old 100th element off.

The easiest way to do this that I have found is as follows.

Code: Select all

   // Set the array to read from left to right as a normal array does
    ArraySetAsSeries(Test, false);

     // Add a new empty element to the end 
    ArrayResize(Test, 101);

    // Set the array to read from right to left similar to the bars on a chart
    ArraySetAsSeries(Test, true);

    // Now the array has been turned around delete the last element    
    ArrayResize(Test, 100);

Done
User avatar
SteveHopwood
Owner
Posts: 9754
Joined: Tue Nov 15, 2011 8:43 am
Location: Misterton - an insignificant village in England. Very pleasant to live in.

Moving all elements up one place in an array

Post by SteveHopwood »

Done indeed. :clap: :clap: :clap: :clap:

There is an easier way and that is to use a circular array. Trouble is, I have forgotten how to code one, so I am hoping to attract the attention of one of our resident Coding Genius'. Do one of you have a spare moment?

:xm: :rocket:
Read the effing manual, ok?

Afterprime is the official SHF broker. Read about them at https://www.stevehopwoodforex.com/phpBB3/viewtopic.php?p=175790#p175790.

I still suffer from OCCD. Good thing, really.

Anyone here feeling generous? My paypal account is always in the market for a tiny donation. [email protected] is the account.

To see The Weekly Roundup of stuff you guys might have missed Click here

My special thanks to Thomas (tomele) for all the incredible work he does here.
User avatar
renexxxx
Trader
Posts: 860
Joined: Sat Dec 31, 2011 3:48 am

Moving all elements up one place in an array

Post by renexxxx »

If you only ever want to insert a new element at the beginning of the array, John's (skinner36) method is probably the most efficient, as ArraySetAsSeries() is very quick.

But, if you need to insert new elements at any given position, you might want to have a look at Ding Li's LinkedList class, which is an implementation of the abstract List class.
skinner36

Moving all elements up one place in an array

Post by skinner36 »

This is only designed to move all of the elements up one to be able to add the new data at the beginning.
PeterT

Moving all elements up one place in an array

Post by PeterT »

This is a blueprint how it can be done just with logic. It assumes, that the size of the array doesn't change at runtime. But I think this was the intention of the OP. It can be written shorter, but it's harder to read then.

Code: Select all

int Array[5];
int SizeOfArray=5;
int InsertPointer=0;

void OnStart()
{
   for(int i=1; i<10; i++)
      AddNew(i);
}

void AddNew(int val)
{
   Array[InsertPointer]=val;
   InsertPointer++;
   if(InsertPointer==SizeOfArray)
      InsertPointer=0;
   PrintArray();
}

int GetIndexInternalByLogicalIndex(int LogicalIndex)
{
   int IndexInternal=(InsertPointer-1)-LogicalIndex;
   if(IndexInternal<0)
      IndexInternal=SizeOfArray+IndexInternal;
   return IndexInternal;
}

void PrintArray()
{
   string text;
   for(int i=SizeOfArray-1; i>=0; i--)
      text+=Array[GetIndexInternalByLogicalIndex(i)]+"|";
   Print(text);
}
You do not have the required permissions to view the files attached to this post.
User avatar
KingHigh
Posts: 6
Joined: Sun Nov 27, 2011 5:52 am
Location: The Left Coast Of America

Moving all elements up one place in an array

Post by KingHigh »

Hi All,

Here is example code for circular queue which I use in a multipair EA typically 10-14 pairs where all data for trading and indies go thru these queues. Once you get the hang of it, its easy. I believe it is about as fast as it can be but would appreciate any better ideas.

KingHigh

Code: Select all

//+------------------------------------------------------------------+
//|                                        KHbar_ArrayShift_TEST.mq4 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window

extern int LkBk=15;
int InPtr[]={0};
int symidx = 3;
int Price[][28];

void OnDeinit(const int cause)
{
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
{
   ArrayResize( Price, LkBk ); ArrayInitialize(Price,0);
   ArrayResize( InPtr, LkBk ); ArrayInitialize(InPtr,0);
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   int i;
   for(  i=0; i < LkBk; i++ ){ UpdateData(i,symidx); PrintArray(i); }
   
   UpdateData(i,symidx);
   PrintArray(i); i++;
   UpdateData(i,symidx);
   PrintArray(i); i++;
   UpdateData(i,symidx);
   PrintArray(i); i++;
   UpdateData(i,symidx);
   PrintArray(i); i++;
   UpdateData(i,symidx);
   PrintArray(i); i++;
   UpdateData(i,symidx);
   PrintArray(i); i++;
   UpdateData(i,symidx);
   PrintArray(i); i++;
   return(rates_total);
}

void UpdateData( int val, int symidx )
{
   //Alert("Price idx= "+InPtr[symidx]);
   Price[InPtr[symidx]][symidx] = val; InPtr[symidx]++; if(InPtr[symidx] == LkBk) InPtr[symidx]=0;
}

int CalcOutPtr(int OutPtr, int symidx )
{
   int idx=(InPtr[symidx]-1)-OutPtr;
   //idx = ((idx<0)? LkBk+idx:idx);
   return( ((idx<0)? LkBk+idx:idx) );
}

void PrintArray(int line)
{
   string text;
   for(int i=0; i<=LkBk-1; i++) {  /*Alert("OutPtr= "+CalcOutPtr(i,symidx) );*/ text += (string)Price[CalcOutPtr(i,symidx)][symidx]+"|";}
   Alert("Line= "+line+"|||"+text);
   return;
}
Post Reply

Return to “Coders Hangout”