Reputation: 5520
Problem: I need to generate the following sequence. I have the order of the matrix as input.
Example:
I need to generate the sequence of position of its elements.
(0,0),(0,1),(1,0),(1,1) ->for order 2
(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2) -> for order 3.
I need to have function which does this for me. When I call this function it should calculate for me on the fly. I don't want to store the sequence in the memory.
Eg:
first_call - > return value (0,0)
second_call to function - > return value ( 0,1)
...and so on...
You can store these values in some global variables.
PS:
The function has to be thread-safe as the application is multi-threaded. I know this condition doesn't make difference. Just wanted to convey the entire problem.
Precision:
I have tried my solution but I think its in efficient. I am looking for an efficient method to do that. You can just mention the steps. I don't need implementation in any particular language. Please let me know if more info is required for the question.
Upvotes: 2
Views: 104
Reputation: 4772
Here's a Python solution using a generator:
def sequence_gen(order=2):
for i in range(order*order):
yield divmod(i, order)
for val in sequence_gen(2):
print(val)
#(0, 0)
#(0, 1)
#(1, 0)
#(1, 1)
for val in sequence_gen(3):
print(val)
#(0, 0)
#(0, 1)
#(0, 2)
#(1, 0)
#(1, 1)
#(1, 2)
#(2, 0)
#(2, 1)
#(2, 2)
Upvotes: 0
Reputation: 9278
#define MATRIX_ORDER 3
void NextPosition(int aIndex, int& aRow, int& aColumn)
{
if (aColumn == MATRIX_ORDER - 1)
{
aRow++;
aColumn = 0;
} else {
aColumn++;
}
}
void SomeFunction()
{
int index = 0;
int row = 0;
int column = -1;
while (index < (MATRIX_ORDER * MATRIX_ORDER))
{
NextPosition(index, row, column);
printf("index: %d, row: %d, column: %d\n", index, row, column);
index++;
}
}
Output:
index: 0, row: 0, column: 0
index: 1, row: 0, column: 1
index: 2, row: 0, column: 2
index: 3, row: 1, column: 0
index: 4, row: 1, column: 1
index: 5, row: 1, column: 2
index: 6, row: 2, column: 0
index: 7, row: 2, column: 1
index: 8, row: 2, column: 2
Upvotes: 0
Reputation: 21902
Use a global variable to store the number of times you have called the function. Call it t
. If order is order
, then
f = (t
div order
, t
mod order
)
Where div
is the integer division (e.g. 5 div
3 = 1) and mod
is the modulus (i.e. remainder of the division). (e.g. 5 mod
3 = 2).
So in Java for example:
public class MyCounter {
private static int t = 0;
public static int[] myFunction(int order) {
return new int[] { t / order , t++ % order };
}
public static void main(String[] args) {
int order = 3;
for(int i=0; i<order*order; i++) {
int[] k = myFunction(order);
System.out.println("("+k[0]+", "+k[1]+")");
}
}
}
Upvotes: 2