-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday3.cpp
130 lines (117 loc) · 2.64 KB
/
day3.cpp
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
127
128
129
130
#include <iostream>
#include <cmath>
using namespace std;
const int MAX_SQUARES = 1000;
void getSpiralCoords(const int& n, int& x, int& y)
{
int N = 1;
//cout << "N=" << N << " [" << x << ", " << y << "]" << endl;
// counter-clockwise spiral
while (N < n)
{
if (abs(x) <= abs(y) && !(x == -y && x < 0)) // moving horizontally
{
if (y > 0) // upper
x--;
else // lower
x++;
}
else // moving vertically
{
if (x > 0) // right
y++;
else // left
y--;
}
N++;
//cout << "N=" << N << " [" << x << ", " << y << "]" << endl;
}
}
int dist(int x, int y)
{
return abs(x) + abs(y);
}
struct Square
{
int x;
int y;
int value;
};
class Spiral
{
public:
Spiral();
~Spiral();
int addSquare();
void display();
private:
Square* squares[MAX_SQUARES];
int nSquares;
int lastX;
int lastY;
int sumAdjacentSquares(const int& x, const int& y);
};
Spiral::Spiral()
{
nSquares = 1;
lastX = 0;
lastY = 0;
squares[0] = new Square;
squares[0]->x = 0;
squares[0]->y = 0;
squares[0]->value = 1;
}
Spiral::~Spiral()
{
for (int i = 0; i < nSquares; i++)
delete squares[i];
}
int Spiral::sumAdjacentSquares(const int& x, const int& y)
{
int sum = 0;
for (int i = 0; i < nSquares; i++)
{
int X = squares[i]->x;
int Y = squares[i]->y;
if ((x + 1 == X && y == Y)
|| (x + 1 == X && y + 1 == Y)
|| (x == X && y + 1 == Y)
|| (x - 1 == X && y + 1 == Y)
|| (x - 1 == X && y == Y)
|| (x - 1 == X && y - 1 == Y)
|| (x == X && y - 1 == Y)
|| (x + 1 == X && y - 1 == Y))
{
sum += squares[i]->value;
}
}
return sum;
}
int Spiral::addSquare()
{
getSpiralCoords(2, lastX, lastY);
squares[nSquares] = new Square;
squares[nSquares]->x = lastX;
squares[nSquares]->y = lastY;
squares[nSquares]->value = sumAdjacentSquares(lastX, lastY);
nSquares++;
return squares[nSquares - 1]->value;
}
void Spiral::display()
{
for (int i = 0; i < nSquares; i++)
cout << "n=" << i << " [" << squares[i]->x << ", " << squares[i]->y << "]" << endl;
}
int main()
{
int n = 265149;
int x = 0, y = 0;
getSpiralCoords(n, x, y);
cout << "n=" << n << " [" << x << ", " << y << "]" << endl;
cout << "Taxicab distance: " << dist(x, y) << endl;
Spiral sp;
int value = 0;
while (value < n)
value = sp.addSquare();
cout << value << endl;
}