Periodic Arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jim Barrett
    New Member
    • Feb 2012
    • 1

    Periodic Arrays

    Hi there, I'm relatively new to c++ and I'm trying to write a fairly simple simulation.

    The simulation involves updating values in a grid based on the values of neighbouring nodes, and I'm working with polar coordinates.

    Say I have an array A[200] and I iterate using an update equation of say;

    A[i] = (A[i+1] + A[i-1])/2;

    This is fine except at the boundaries, where asking for A[i-1] at i=0 will give a segmentation fault. Due to the periodicity of angles A[i-1] should in fact be A[199] at this boundary.

    Obviously I can overcome this with some simple conditionals, but I can't help but feel this must be a fairly common problem and since this is a simulation I want things as concise and quick as possible.

    Is there any object already out there which works like an array but loops around at the ends? Or if not does anyone have any ideas of how to elegantly tackle the problem?

    Thanks
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    It looks like you want a circular linked list. There is a linked list in the C++ Standard library but it is not circular. However, you could write your own functions to manage the standard list as though it was circular. For example, your advance function when it encounters the end f the list could continue on by positioning to te beginning of the list before returning.

    A C++ developer would define a class with a standard library linked list as a member so that creating an object of this class would also create the list. Then all of the member functions would operate on this list to make it appear circular.

    At least, the ls code is done and debugged leaving you to write only your handling functions.

    Comment

    • therockon7throw
      New Member
      • Feb 2012
      • 2

      #3
      Hi

      Is it clear to you that each time you compute an element, the array is automatically updated, if you do the assigment at the same time ? So, if it is not what you wish, you may use a temporary array.


      it is easy to compute A[i] = (A[i+1] + A[i-1])/2;

      so have an array of size n, either defined statically or dynamicall.

      to compute it do it like following

      A[0] = A[ 1 ] + A[ n-1 ] ) / 2;
      A[ n -1 ] = A[ 0 ] + A[ n - 2 ] ) / 2;

      for(int i = 1 ; i < n - 1 ; i++){

      A[i] = A[ i + 1 ] + A[ i - 1 ] ) / 2;
      }

      hope it helps

      Comment

      Working...