13 Sept 2010

Array Indexing by Separators

In the case of arrays and strings one often needs to extract a sub part of them.

If one uses the indices of the virtual separators between and at the "edges" of the array elements in stead of the indices of the array elements themselves, one can eliminate conditional statements that check indices for critical values at the "edges" of the array.

Explanation by an example:

# Array indices:       0   1   2   3   4
               array=["H","e","l","l","o"]
# Separator indices: 0   1   2   3   4   5


#           0   1   2
GetSubarray(["H","e"],0,0)==[]         # 0-0=0
GetSubarray(["H","e"],0,1)==["H"]      # 1-0=1
GetSubarray(["H","e"],1,1)==[]         # 1-1=0
GetSubarray(["H","e"],1,2)==["e"]      # 2-1=1
GetSubarray(["H","e"],2,2)==[]         # 2-2=0
GetSubarray(["H","e"],0,2)==["H","e"]  # 2-0=2
GetSubarray(["H","e"],2,2)==[]         # 2-2=0


GetSubarray([],0,0)==[]          # 0-0=0

The thing to notice is, how it is possible to mark empty intervals, including the start edge of the string and the end edge of the string, by using the very same 2 indices that describe a substring start and end positions.

A more permanent version of this post resides here.

No comments: