Created
October 26, 2013 07:15
-
-
Save Altimor/7166276 to your computer and use it in GitHub Desktop.
PIPOTW: Outward Counterclockwise Spiral Matrix Traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSArray*)spirralArrayFromGridOfWidth:(int)width height:(int)height startline:(int)line column:(int)column{ | |
NSMutableArray *returnArray = [NSMutableArray new]; | |
int currentDirectionIndex = 0; | |
int currentInt; | |
int nextPivotal = 3; | |
int numOfPivotal = 1; | |
line++; | |
for(int i=1;i<=width*height; i++){ | |
if(nextPivotal == i){ | |
numOfPivotal++; | |
nextPivotal += ceil((float)numOfPivotal/2); | |
currentDirectionIndex++; | |
} | |
switch (currentDirectionIndex%4) { | |
case 0: | |
// Up | |
line--; | |
break; | |
case 1: | |
// Left | |
column--; | |
break; | |
case 2: | |
// Down | |
line++; | |
break; | |
case 3: | |
// Right | |
column++; | |
break; | |
} | |
currentInt = (line-1)*width+column; | |
if(currentInt<=0||line>height||column>width||!column||!line){ | |
i--; | |
} else { | |
[returnArray addObject:[NSNumber numberWithInt:currentInt]]; | |
} | |
} | |
return returnArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment