I'm not sure how to title the question I have so I can't be certain this hasn't been answered before. That said, following is a description of my programming question.
I have a class R containing 2 integer elements, say X and Y. I then have two 24 element arrays named A and B where each element contains an instance of class R. I would like to iterate through the arrays to determine how to use R.Y to populate a third array C as follows:
If R.Y at index i of A is larger than R.Y at index i of B then put R from A in开发者_开发百科to index i of C.
If R.Y at index i of B is larger than R.Y at index i of A then put R from B into index i of C.
If R.Y at index i of A is equal to R.Y at index i of B then put either R into index i of C.
It's the third of these conditions that has me perplexed. For example, if indexes 7, 15, and 19 of arrays A and B have R.Y equal to each other, then I want to try each element of both A and B at those indexes in C to determine which one is required based on a CRC check of C. So I could put the following R values into the same index values of C:
A[7], A[15], A[19]
A[7], A[15], B[19]
A[7], B[15], A[19]
A[7], B[15], B[19]
B[7], A[15], A[19]
B[7], A[15], B[19]
B[7], B[15], A[19]
B[7], B[15], B[19]
These 8 combinations come from 2^3 (2 arrays to the power of the number of times R.Y are the same), so if I have 4 indexes in A and B where R.Y are equal, then there would be 16 combinations, 5 indexes = 32 combinations, 6 = 64, etc.
The issue is I'll never know how many times R.Y will be identical in A and B for all the indexes; it could be 0 to 24. So to make a long description short, I need an algorithm to populate C with all the possible R classes from A and B where R.Y are equal in both arrays, iterate through all the possible combinations of C and stop when that first instance of C passes the CRC check.
Sound simple? I hope so. Let me know if you need any further clarification or point me to a thread that has something similar to this already answered. TIA
I think you came close to an answer in your own question. Make an array listing all the indices which you must try A or B. L={7,15,19} in the example. n=3. Then you'll loop from 0 to 2^n-1 inclusive. In each iteration of the loop, you'll test each bit b=0, bit 1, ... all the way to bit n-1. L[b] tells you which index you need to set, and depending on if the bit is clear, set it to the corresponding A or B value.
Worst case though you are going to have to perform 2^24 combinations with 24 bit tests each. Are you sure you have to try them all?
Pseudocode:
start with empty L;
for(i=0 to 23) put A[i] or B[i] in C[i] (whichever has larger Y) *or* add i to L (if A.y and B.y match)
let n=length of L;
for (x=0 to (1<<n)-1)
for(b=0 to n-1)
test x&(1<<b), if clear put A[L[b]] in C[L[b]], or put B[L[b]] in C[L[b]]
endloop
test this array C
endloop
精彩评论