-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiral-write.sh
executable file
·169 lines (137 loc) · 2.54 KB
/
spiral-write.sh
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/bin/bash
NUMBERS=()
function coords_to_pos() {
X=$1
Y=$2
if [ $X -gt 0 ]; then
((D_X = X))
else
((D_X = -X))
fi
if [ $Y -gt 0 ]; then
((D_Y = Y))
else
((D_Y = -Y))
fi
if [ $D_X -gt $D_Y ]; then
((SIZE_PLUS = D_X))
((SIZE_MINUS = 0 - D_X))
else
((SIZE_PLUS = D_Y))
((SIZE_MINUS = 0 - D_Y))
fi
((SIDE = SIZE_PLUS + SIZE_PLUS))
((SQUARE = (SIDE + 1) * (SIDE + 1)))
# Check if we're on highest Y (bottom border)
if [ $Y -eq $SIZE_PLUS ]; then
((RESULT = SQUARE - (SIZE_PLUS - X)))
echo $RESULT
exit
fi
# Check if we're on lowest X (left border)
if [ $X -eq $SIZE_MINUS ]; then
((RESULT = SQUARE - SIDE - (SIZE_PLUS - Y)))
echo $RESULT
exit
fi
# Check if we're on lowest Y (top border)
if [ $Y -eq $SIZE_MINUS ]; then
((RESULT = SQUARE - SIDE - SIDE + (SIZE_MINUS - X)))
echo $RESULT
exit
fi
# Check if we're on highest X (right border)
if [ $X -eq $SIZE_PLUS ]; then
((RESULT = SQUARE - SIDE - SIDE - SIDE + (SIZE_MINUS - Y)))
echo $RESULT
exit
fi
}
function get_number_from_array() {
POS=$1
if [ $POS -lt ${#NUMBERS[@]} ]; then
echo ${NUMBERS[$POS]}
else
echo 0
fi
exit
}
function calculate_new_number() {
X=$1
Y=$2
SUM=0
for ((iy = -1; iy <= 1; iy++)); do
for ((ix = -1; ix <= 1; ix++)); do
if [ $ix -eq 0 ] && [ $iy -eq 0 ]; then
continue
fi
((XPOS = X + ix))
((YPOS = Y + iy))
POS=`coords_to_pos $XPOS $YPOS`
echo "coords to pos: $XPOS:$YPOS = $POS" >&2
NUMBER=`get_number_from_array $POS`
((SUM = SUM + NUMBER))
done
done
echo $SUM
exit
}
function fill_numbers() {
SEARCH=$1
((POS = ${#NUMBERS[@]} - 1))
((CURRENT = ${NUMBERS[$POS]}))
DIR="S"
SIZE_PLUS=1
SIZE_MINUS=-1
X=0
Y=0
while [ $CURRENT -le $SEARCH ]; do
case $DIR in
S)
((X = X+1))
DIR="U"
;;
U)
((Y = Y-1))
if [ $Y -eq $SIZE_MINUS ]; then
DIR="L"
fi
;;
L)
((X = X-1))
if [ $X -eq $SIZE_MINUS ]; then
DIR="D"
fi
;;
D)
((Y = Y+1))
if [ $Y -eq $SIZE_PLUS ]; then
DIR="R"
fi
;;
R)
((X = X+1))
if [ $X -eq $SIZE_PLUS ]; then
DIR="S"
((SIZE_PLUS = SIZE_PLUS + 1))
((SIZE_MINUS = SIZE_MINUS - 1))
fi
;;
*)
echo "watafugg" >&2
exit
;;
esac
CURRENT=`calculate_new_number $X $Y`
echo "new number at pos $X:$Y = $CURRENT" >&2
((POS = POS + 1))
(( NUMBERS[POS] = CURRENT ))
done
echo $CURRENT
exit
}
while read INPUT; do
NUMBERS=(1 1)
RESULT=`fill_numbers $INPUT`
echo "> $INPUT --- $RESULT"
done