I had this programming problem that I'm trying to solve and since I'm running out of patience, instead of coding the script to follow an algorithm (which I wasnt able to code perfectly), I resorted to solve it using the pattern I see in the problem.
It works don't get me wrong, but I do wonder if it is generally alright to solve a problem (that I think is intended to train your brain to create a general algorithm from a series of patterns) with a solution that is derived from how the pattern works.
And the pattern I saw is that since the pattern on how the spiral is made is this:
N (1s to the right)
N-1 (1s downwards)
N-1 (1s to the right)
N-3 (1s upwards)
N-3 (1s to the left)
.. and so on and so forth.
Until it is the 2nd n-x where the difference is 2, or the last n-x where the difference is 1, I keep on printing 1s based on the pattern above to the direction that I'm also looping.
I solved it until the attempt and is able to submit but I felt that I cheated the problem.
I'm not asking for the best algorthm for the problem, but for your thoughts on how I did this problem. Was it a good alternative? As long is it works, it's an algorithm?
I don't know where else I can ask this question and this is a little broad but I hope I can get some ideas here. Thanks.
(Added JavaScript since I did my solution there and the one I have experience the most)
function spiralize (n) {
var output = Array(n).fill(0).map(_ => Array(n).fill(0));
var i = 0, j = -1, max = n;
while(true) {
if([[0,1], [1,0], [0,-1], [-1, 0]].find(([x, y], index) => {
[output, i, j, max] = traverseArray(output, i, j, max, x, y, n);
if((index % 2 == 0 && max == 2) || (index % 2 == 1 && max == 1))
return true;
}))
return output;
}
}
function traverseArray(output, i, j, max, iter1, iter2, n) {
iter1 ? max == n ? max-- : max -= 2 : max;
temp = max;
while(temp-- > 0)
output[i += iter1][j += iter2] = 1;
return [output, i, j, max];
}
Algorithm design, and to a great extent general mathematics, is the art of finding patterns and regularity. This allows you to craft automated solutions generated by computations rather than by explicit and exhaustive data.
There is no "morality" in programming: if it works and works well, there is no reason to reject a way to code. (Unless it needs to be understood by others.)
If I was to program this, and assuming that storing the whole array is allowed, I would probably just let the spiraling work on its own: starting horizontally from the upper-left corner, fill with O's, until the border or a zero is hit (if a zero, backtrack by one position). Then turn right by a quarter turn. At some point, no more moves are possible. The pattern can be summarized as "move forward until you hit a wall and turn right".
I would probably also extend the array and fill the outline with zeroes, so that you don't have to distinguish between hitting the border or seeing a zero.