1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
#include <cstring>
using namespace std;
void makeSpiral(int *pa, int rows, int cols)
{
int left = 0, counter = 1, right = cols - 1, dir = 0, top = 0, bot = rows - 1;
// base + (row length * rows to skip) + columns to skip
while(left<=right && top<=bot)
{
if(dir == 0)
{
for(int k = left;k<=right;k++)
{
*(pa + cols * top + k) = counter;
cout << counter << " at: " << top << '\t' << k << "\n";
counter++;
}
top++;
dir++;
}
else if(dir == 1)
{
for(int k = top;k<=bot;k++)
{
*(pa + cols * k + right) = counter;
cout << counter << " at: " << k << '\t' << right << "\n";
counter++;
}
right--;
dir++;
}
else if(dir == 2)
{
for(int k = right;k>=left;k--)
{
*(pa + cols * bot + k) = counter;
cout << counter << " at: " << bot << '\t' << k << "\n";
counter++;
}
bot--;
dir++;
}
else if(dir == 3)
{
for(int k = bot;k>=top;k--)
{
*(pa + cols * k + left) = counter;
cout << counter << " at: " << k << '\t' << left << "\n";
counter++;
}
left++;
dir++;
}
dir %= 4;
}
}
// base + (row length * rows to skip) + columns to skip
void printSpiral(ostream &out, int *pa, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
//out << *(pa + rows * i + j) << '\t' << flush;
cout << *(pa + cols * i + j) << '\t' << flush;
}
//out << endl;
cout << endl;
}
return;
}
void clearArray(int *pa, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
*(pa + cols * i + j) = 0;
}
}
return;
}
int main()
{
ofstream outFile;
int nRows, nCols, i = 1;
//char outputFile[20];
//strcpy(outputFile, argv[i]);
//cout << outputFile << endl;
//outFile.open(outputFile);
int a1[1][1] = {0}, a2[2][2] = {0}, a3[3][3] = {0}, a4[4][4] = {0}, a5[5][5] = {0}, a47[4][7] = {0}, a74[7][4] = {0},
a48[4][8] = {0}, a84[8][4] = {0}, a20[15][20] = {0};
int aSize[10][2] =
{
{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {4, 7}, {7, 4},
{4, 8}, {8, 4}, {15, 20}
};
int *arrays[] =
{
&a1[0][0], &a2[0][0], &a3[0][0], &a4[0][0], &a5[0][0],
&a47[0][0], &a74[0][0], &a48[0][0], &a84[0][0],
&a20[0][0]
};
for( int i = 0; i < 10; i++ )
{
//outFile << "Array "<< i+1 << ":\n";
cout << "rows: " << aSize[i][0] << "\tcols: " << aSize[i][1] << endl;
clearArray( arrays[i], aSize[i][0], aSize[i][1] );//nRows, nCols );
makeSpiral( arrays[i], aSize[i][0], aSize[i][1] );//nRows, nCols );
printSpiral( outFile, arrays[i], aSize[i][0], aSize[i][1] );
//outFile << "\n\n";
}
//outFile.close();
return 0;
}
|