Jump to content

Talk:Spiral matrix: Difference between revisions

Line 309:
i came across this page during a search for a mechanism to implement the spiral matrix in VBA bt unfortunately it was not listed here. But afrterwards by translating the java code i manage to obtain the result. I beleive a lot f peopla have manage to do this but didnt come across anyone who has shared it
so here it goes....
Sub spiral()
Init
 
:Howdy, and welcome to RC (if appropriate). Might I suggest creating an account?
ws.Range("a412:k425").ClearContents
:Having said that, code submissions really should go on [[Spiral matrix|the task's page]], and not its talk page. I've moved it for you: [[Spiral matrix#VBA]]. I made some changes so that it is more generalized; your use of <code>Init</code> (which I assume sets up certain starting conditions) doesn't help anyone without access to your code.
 
:(As a minor aside, I have to wonder at your use of cells way down in the 400+ range. For something like this, I'd think that just starting at A1 would be acceptable.)
Dim n As Integer, a As Integer, b As Integer
:Not trying to be a jerk, just trying to help. -- [[User:Eriksiers|Erik Siers]] 18:28, 21 September 2010 (UTC)
Dim numCsquares As Integer, sideLen As Integer, currNum As Integer
Dim j As Integer, i As Integer
Dim j1 As Integer, j2 As Integer, j3 As Integer
 
n = ws.Range("b411").Value
 
Dim spiralArr(9, 9) As Integer
numCsquares = CInt(Application.WorksheetFunction.Ceiling(n / 2, 1))
sideLen = n
currNum = 0
For i = 0 To numCsquares - 1
'do top side
For j = 0 To sideLen - 1
currNum = currNum + 1
spiralArr(i, i + j) = currNum
Next j
'do right side
For j1 = 1 To sideLen - 1
currNum = currNum + 1
spiralArr(i + j1, n - 1 - i) = currNum
Next j1
'do bottom side
j2 = sideLen - 2
Do While j2 > -1
currNum = currNum + 1
spiralArr(n - 1 - i, i + j2) = currNum
j2 = j2 - 1
Loop
'do left side
j3 = sideLen - 2
Do While j3 > 0
currNum = currNum + 1
spiralArr(i + j3, i) = currNum
j3 = j3 - 1
Loop
sideLen = sideLen - 2
Next i
Cells(413, 1).Select
For a = 0 To n - 1
For b = 0 To n - 1
Cells(413 + a, 1 + b).Select
ActiveCell.Value = spiralArr(a, b)
Next b
Next a
 
End Sub
1,150

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.