Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating NXN spirals

Tags:

python

I have been given the task of creating a spiral in python where the user inputs a number e.g 3 and it will output a 3x3 spiral which looks like this:

- - \
/ \ |
\ - /

I am not looking for the full code I just have no idea how to do it, obviously printing out every possible solution using if statements isn't possible or logical. The real question here is what should i be looking to do, for loops, define my own function? are there any docs people can link me to that would help. The full task outline is as follows:

Your task here is to write a program to draw a spiral of a given size inside a box.

Your program should ask the user for a positive integer denoting the size of the box. Your program should then print out a spiral inside of a box of that size.

For example:

Enter size: 3
- - \
/ \ |
\ - /

and:

Enter size: 4
- - - \
/ - \ |
| \ / |
\ - - /

​and:

Enter size: 5     
- - - - \
/ - - \ |
| / \ | |
| \ - / |
\ - - - /

The input size will always be greater than 1.

like image 836
Nick Adams Avatar asked Aug 05 '15 12:08

Nick Adams


1 Answers

I respect you for not wanting the full code. This is intentionally only a partial answer.

Start by making a 2-dimensional array. Something like:

grid = [[None]*n for i in range(n)]

This allows you to write code like grid[i][j] = '\'.

Start with i,j = 0,0. In a loop spiral around the grid. It might help to have a variable direction which takes on values 'right', 'left', 'up', 'down' together with a corresponding delta taking on values like (0,1) (for moving to the right) to be added to (i,j) to implement the move.

Go along a line in a certain direction placing '-' or '|' until you hit a corner (check for None as well as the limits of the overall grid). When you get to a corner, place the appropriate corner marker and change directions.

Once the grid is filled, join each rows with an empty string delimiter and join the result with '\n' as the delimiter.

like image 72
John Coleman Avatar answered Oct 19 '22 10:10

John Coleman