C++:TornadoArray
골뱅이 배열을 출력하는 C++ 샘플 예제.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <climits>
int main(int argc, char ** argv)
{
using namespace std;
int input = 0;
if (argc >= 2) {
input = atoi(argv[1]);
} else {
cout << "Please enter the number: ";
cin >> input;
}
cout << "Number is " << input << endl;
int const REPLACE_NUMBER = INT_MAX;
int const TOTAL_COUNT = input * input;
int x = 0, y = 0;
// ALLOC!
int ** array = new int* [input];
for (y = 0; y < input; ++y) {
array[y] = new int [input];
for (x = 0; x < input; ++x) {
array[y][x] = REPLACE_NUMBER;
}
}
int weight_x = 1;
int weight_y = 0;
int state = 0;
y = 0;
x = 0;
// LOGIC!
for (int insert_number = 1; insert_number <= TOTAL_COUNT; ++insert_number) {
array[y][x] = insert_number;
if (/* * */y + weight_y < 0 || y + weight_y >= input
|| x + weight_x < 0 || x + weight_x >= input
|| array[y + weight_y][x + weight_x] != REPLACE_NUMBER) {
++state;
switch (state % 4) {
case 0: weight_x = 1; weight_y = 0; break;
case 1: weight_x = 0; weight_y = 1; break;
case 2: weight_x = -1; weight_y = 0; break;
case 3: weight_x = 0; weight_y = -1; break;
}
}
y += weight_y;
x += weight_x;
}
// PRINT!
for (y = 0; y < input; ++y) {
for (x = 0; x < input; ++x) {
cout << setw(2) << array[y][x] << ' ';
}
cout << endl;
}
// RELEASE!
for (y = 0; y < input; ++y) {
delete [] array[y];
}
delete [] array;
return 0;
}