Seeing the properties of a tree is difficult when looking at rainforest from planetary orbit.
A 2D array is one thing. A 2D array implemented with vector of vectors is one variant of it.
Modulo operator is an entirely unrelated thing. Modulo is a function that hashes (wraps) any integer into specific range of integers.
Lets say that ve have a list 'foo' with N elements. We refer to the elements with foo[0], foo[1], .. foo[N-1]. Now we take a random (non-negative) number 'x'. If x<N, we can use it as an index to the list. If we calculate the modulo
x % N
we do get a number that is always in range [0..N[, a valid index.
Lets do that again:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
std::vector<int> foo;
// fill the foo
// assert: 0 < foo.size()
// Previously, we called foo.size() "N"
size_t x; // index
// set the index to something
// access an element
std::cout << foo[x] << '\n';
// calculate the index of the previous element
size_t xp = (foo.size() + x - 1) % foo.size();
// and access
std::cout << foo[xp] << '\n';
|
Why so?
If 'x' is 0, then deducting one would create -1. We add first N, so the sum will be N-1.
If 'x' is N-1, we get 2N-2, which is then reduced by the modulo to N-2.
Now we are ready for the 2D:
1 2 3
|
// we want the tor[i-1][j-1]
vector<Spot> & row = tor[ (tor.size() + i - 1) % tor.size() ];
Spot island = row[ (row.size() + j - 1) % row.size() ];
|