Advertisement
stoianpp

SpiralMatrix

Oct 23rd, 2014
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #import <Foundation/Foundation.h>
  2.  
  3. void printMatrix(NSMutableArray *dataArray, int size){
  4.     NSMutableString *output = [[NSMutableString alloc] init];
  5.     for (int i = 0; i < size; i++){
  6.         for (int j = 0; j < size; j++){
  7.             [output appendFormat:@"%4d", [dataArray[i][j] intValue]];
  8.         }
  9.         [output appendString:@"\n"];
  10.     }
  11.     NSLog(@"\n%@", output);
  12. }
  13.  
  14. void fillMatrix(NSMutableArray *arrayMatrix, int size){
  15.     int counter = 1;
  16.     int y = 0;
  17.     int x = 0;
  18.     int newX = -1;
  19.     int newY = 0;
  20.     int direction = 1;
  21.     while(counter <= size*size){
  22.         switch(direction%4){
  23.             case 0: newY--; break;
  24.             case 1: newX++; break;
  25.             case 2: newY++; break;
  26.             case 3: newX--; break;
  27.         }
  28.        
  29.         if(0 <= newX && newX < size && 0 <= newY && newY < size && [arrayMatrix[newY][newX] intValue] == 0){
  30.             y = newY;
  31.             x = newX;
  32.             arrayMatrix[y][x] = [NSNumber numberWithInt: counter];
  33.         } else{
  34.             newX = x;
  35.             newY = y;
  36.             ++direction;
  37.             continue;
  38.         }
  39.         ++counter;
  40.     }
  41. }
  42.  
  43. int main(int argc, const char * argv[]) {
  44.     @autoreleasepool {
  45.         int size = 5;
  46.         NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity: size];
  47.         for(int i = 0; i < size; i++){
  48.             NSMutableArray *row = [[NSMutableArray alloc] init];
  49.             for(int j = 0; j < size; j++){
  50.                 [row addObject: @0];
  51.             }
  52.             [dataArray insertObject:row atIndex:i];
  53.         }
  54.         fillMatrix(dataArray,size);
  55.         printMatrix(dataArray,size);
  56.     }
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement