To make a simple periodic-boundary-condition-like access to an array, you can do
size_t size = 5;
double array[ size ];
// ... Fill the array with data
std::cout << "enter index:" << std::endl;
int index;
std::cin >> index;
double value = array[ ( size + ( index % size ) ) % size ];
std::cout << "array[ " << index << "] = " << value << std::endl;
This is pretty ugly, so it's probably best to encapsulate it in a function:
size_t GetPeriodicIndex( int index, unsigned size )
{
return static_cast< unsigned >( size + ( index % size ) ) % size;
}
Using this method, you can do a python-like array access of using -1 to get the last element of the array. Since you have to do a bunch of extra calculations at each access though, it will be slower than just accessing the elements directly.
ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9
Sorry, missed the ongoing discussion. You don't really need any branching logic or loops for this. It's a one-liner (albeit a slightly confusing one):
int boundary1d( int position, int step , int size )
{
return ( size + ( ( position + step + (size/2) ) % size ) ) % size - (size/2);
}
The position + step part generates the new position (in terms of the problem reference frame, not array indices). The problem reference frame is off-set by size/2 from array indices, so position + step - (size/2) moves us into an array index frame. Say
i_array = position + step - (size/2)
then doing i_array % size gives us a number in the range [-size - 1,size - 1], since i_array could, and will often, be negative. We can't have a negative array index, so we add size to this number, giving a number in the range [0, 2*size - 1]. Lets say that
i_array_2 = size + ( i_array % size )
So, a final i_array_2 % size gives us a value in the range [0, size - 1]. The final thing is to move back into the problem reference frame by subtracting the size/2 that we added at the start, giving the final
( size + ( ( position + step + (size/2) ) % size ) ) % size - (size/2)
I hope that makes some sense.
I also changed the return-type of your function to int, since that makes more sense than a double.
ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9
Question Answered as of 10 Months Ago by
ravenous
and
sfuo