Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How does the 2d to 1d conversion work #3

Open
vnyapathi opened this issue Jan 28, 2019 · 3 comments
Open

How does the 2d to 1d conversion work #3

vnyapathi opened this issue Jan 28, 2019 · 3 comments

Comments

@vnyapathi
Copy link

N * (y - 1) + x - 1; Can you explain how this works for 0,0 and a 5by5 grid. Won't it be something like -6.

@alexilyenko
Copy link
Owner

@vnyapathi what problem are you referring to?

@vnyapathi
Copy link
Author

vnyapathi commented Jan 28, 2019 via email

@alexilyenko
Copy link
Owner

I'm a bit out of context over here, since I was working on this 4 years ago, but let's see what we can figure out.

Basically, you're referring to the function which transforms two-dimensional array into the one-dimensional one.

So if you have something like that:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]

it means N = 4 and this array should be transformed into:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Let's move row by row.
First row (y = 1, N = 4):
4 * (1 - 1) + 1 - 1 = 0
4 * (1 - 1) + 2 - 1 = 1
4 * (1 - 1) + 3 - 1 = 2
4 * (1 - 1) + 4 - 1 = 3

Second row (y = 2, N = 4):
4 * (2 - 1) + 1 - 1 = 4
4 * (2 - 1) + 2 - 1 = 5
4 * (2 - 1) + 3 - 1 = 6
4 * (2 - 1) + 4 - 1 = 7

Third row (y = 3, N = 4):
4 * (3 - 1) + 1 - 1 = 8
4 * (3 - 1) + 2 - 1 = 9
4 * (3 - 1) + 3 - 1 = 10
4 * (3 - 1) + 4 - 1 = 11

Fourth row (y = 4, N = 4):
4 * (4 - 1) + 1 - 1 = 12
4 * (4 - 1) + 2 - 1 = 13
4 * (4 - 1) + 3 - 1 = 14
4 * (4 - 1) + 4 - 1 = 15

I think the confusing part for any Java engineer over here would be that we start counting from 1, and not from 0 in two-dimensional array and doing exactly the opposite in the regular one (starting from 0). And it's not clear for me as well :)
I guess that was specified in the task given by Mr. Sedgewick (The Algorithms lecturer), but this should be double-checked.

Without that condition you could use the corrected formula as follows:
N * y + x

Hope that helps!

@alexilyenko alexilyenko pinned this issue Feb 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants