Skip to content

Instantly share code, notes, and snippets.

  • Save antrix1989/c99b10dfb8132ca2264a4ae447bcd9eb to your computer and use it in GitHub Desktop.
Save antrix1989/c99b10dfb8132ca2264a4ae447bcd9eb to your computer and use it in GitHub Desktop.
//
// main.m
// alg
//
// Created by Sergey Demchenko on 10/6/16.
// Copyright © 2016 Antrix. All rights reserved.
//
#import <Foundation/Foundation.h>
//1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
// j j
//i//0;0 0;1 0;2 i//2;0 1;0 0;0
//1;0 1;1 1;2 -> //2;1 1;1 0;1
//2;0 2;1 2;2 //2;2 1;2 0;2
// j = (N - 1) - i
// i = j
// N = 3
// 0 1 2 6 3 0
// 3 4 5 7 4 1
// 6 7 8 8 5 2
//2;1 -> 1;2
// 0 1 2 3
// 4 5 6 7
// 8 9 a b
// c d e f
void print(NSArray *array)
{
int N = (int)array.count;
for (int i = 0; i < N; i++) {
NSArray *subArray = array[i];
assert(subArray.count == N);
NSString *row = @"";
for (int j = 0; j < N; j++) {
NSNumber *k = subArray[j];
row = [NSString stringWithFormat:@"%@ %@", row, k];
}
NSLog(@"%@", row);
}
}
void rotate(NSMutableArray<NSMutableArray<NSNumber *> *> *array)
{
int N = (int)array.count;
NSMutableArray<NSMutableArray<NSNumber *> *> *result = [NSMutableArray new];;
for (int i = 0; i < N; i++) {
NSMutableArray *subArray = [NSMutableArray new];
for (int j = 0; j < N; j++) {
[subArray addObject:[[NSNumber alloc] initWithInt:-1]];
}
[result addObject:subArray];
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int rJ = (N - 1) - i;
int rI = j;
NSNumber *n = array[i][j];
result[rI][rJ] = n;
// NSLog(@" -----");
// print(result);
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
array[i][j] = result[i][j];
}
}
}
void invoke()
{
int N = 3;
NSMutableArray *array = [NSMutableArray new];
int k = 0;
for (int i = 0; i < N; i++) {
NSMutableArray *subArray = [NSMutableArray new];
for (int j = 0; j < N; j++) {
[subArray addObject:[[NSNumber alloc] initWithInt:k]];
k++;
}
[array addObject:subArray];
}
print(array);
rotate(array);
NSLog(@" -----");
print(array);
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
invoke();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment