Created
August 2, 2017 18:35
-
-
Save b-adams/261d07159fde6e145b8d3e55bb2144b3 to your computer and use it in GitHub Desktop.
Linearizing 2-d indexing to 1-d indexing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})') | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)