I have an array with the numbers 1,2,3,2. I want to swap each integer with its mod12 complement (1 swaps with 11, 2 swaps with 10, 3 swaps with 9), to create a list of 16 possibilities:
See the pattern? Keep the first three numbers the same, and swap the last one. Then keep the first two numbers the same, swap the third one, and then the last one...etc...
The code I have written only displays the last one, 11 10 9 10.
[code=c++]
#include <iostream>
using namespace std;
int main()
{
int i, j, k, l;
int array[4] = {1,2,3,2};
for (i=0; i<2; i++)
{
if (i = 0)
{
array[0] = array[0];
}
if (i = 1)
{
array[0] = 12-array[0];
}
for (j=0; j<2; j++)
{
if (j = 0)
{
array[1] = array[1];
}
if (j = 1)
{
array[1] = 12-array[1];
}
for (k=0; k<2; k++)
{
if (k = 0)
{
array[2] = array[2];
}
if (k = 1)
{
array[2] = 12-array[2];
}
for (l=0; l<2; l++)
{
if (l = 0)
{
cout << array[0] << " " << array[1] << " " << array[2] << " " << array[3] << endl;
}
if (l = 1)
{
cout << array[0] << " " << array[1] << " " << array[2] << " " << 12-array[3] << endl;
}
}
}
}
}
return(0);
}
[/code]
I'm sure there's something elementary that I'm missing.
Two part question:
1) Can you help alter my existing code so that it prints out all 16 possibilities?
2) Can you suggest a better way of going about this process?
I think the sorting might defeat the purpose of what I need to do. I need to work from 1 2 3 2, as opposed to 1 2 2 3. (Did I misunderstand what you were suggesting?)
Hmm, ok, since your code works with the == instead of =.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
template< typename T, int N >
int ArraySize( T (&)[ N ] )
{ return N; }
int main() {
int a[] = { 1, 2, 3, 2 };
for( int i = 0; i < ( 1 << ArraySize( a ) ); ++i ) {
for( int j = 0; j < ArraySize( a ); ++j )
std::cout << ( i & ( 1 << ( ArraySize( a ) - j - 1 ) ) ? 12 - a[ j ] : a[ j ] ) << ' ';
std::cout << std::endl;
}
}
EDIT: this code works for any array size from 1 to 31 inclusive. All you have to do is add or remove elements from the array; the rest of the code is unchanged. I could have added a BOOST_STATIC_ASSERT to guarantee the array size isn't too big, but that would've been 2 more lines of code.
I think I understand most of this (my brain is still digesting...). But I don't understand what line 3 is. I haven't done anything with templates before...