Skip to content

Instantly share code, notes, and snippets.

@b-adams
Created August 2, 2017 18:35
Show Gist options
  • Save b-adams/261d07159fde6e145b8d3e55bb2144b3 to your computer and use it in GitHub Desktop.
Save b-adams/261d07159fde6e145b8d3e55bb2144b3 to your computer and use it in GitHub Desktop.
Linearizing 2-d indexing to 1-d indexing
xvals = [1,2,3]
yvals = [1,2,3,4]
for x in xvals:
for y in yvals:
# First, 0-indexing is better for the soul
i = x-1
j = y-1
# Next, the formula to linearize the 2-d indexing to 1-d indexing
x_extent = len(xvals)
k = x_extent*j + i
# Finally, because 1-indexing is what you're asking for
z = k+1
print(f'The boxed number in location ({y},{x}) is {z})')
The boxed number in location (1,1) is 1)
The boxed number in location (2,1) is 4)
The boxed number in location (3,1) is 7)
The boxed number in location (4,1) is 10)
The boxed number in location (1,2) is 2)
The boxed number in location (2,2) is 5)
The boxed number in location (3,2) is 8)
The boxed number in location (4,2) is 11)
The boxed number in location (1,3) is 3)
The boxed number in location (2,3) is 6)
The boxed number in location (3,3) is 9)
The boxed number in location (4,3) is 12)
@jplcny
Copy link

jplcny commented Aug 3, 2017

xvals = [1, 2, 3]
yvals = [1, 2, 3, 4]
for y in yvals:
    for x in xvals:
        # First, 0-indexing is better for the soul
        i = x - 1
        j = y - 1
        # Next, the formula to linearize the 2-d indexing to 1-d indexing
        x_extent = len(xvals)
        k = x_extent * j + i
        # Finally, because 1-indexing is what you're asking for
        z = k + 1
        print(f'The boxed number in location ({y},{x}) is {z})')

Outputs:

The boxed number in location (1,1) is 1)
The boxed number in location (1,2) is 2)
The boxed number in location (1,3) is 3)
The boxed number in location (2,1) is 4)
The boxed number in location (2,2) is 5)
The boxed number in location (2,3) is 6)
The boxed number in location (3,1) is 7)
The boxed number in location (3,2) is 8)
The boxed number in location (3,3) is 9)
The boxed number in location (4,1) is 10)
The boxed number in location (4,2) is 11)
The boxed number in location (4,3) is 12)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment