// // main.m // MagicSquare // // Created by Kosta Sush on 2016-07-27. // Copyright © 2016 Kosta Sush. All rights reserved. // #import /** 8 1 6 3 5 7 4 9 2 */ @interface Matrix : NSObject @property (nonatomic, strong) NSMutableArray *rows; - (instancetype)initWithRows:(NSArray *)rows; - (void)addRowFromString:(NSString *)row; - (NSInteger)difsCompareTo:(Matrix *)other; + (NSArray *)magicMatrix; @end @implementation Matrix - (instancetype)initWithRows:(NSMutableArray *)rows { if (self = [super init]) { self.rows = rows; } return self; } - (void)addRowFromString:(NSString *)row { if (!row.length) return; if (!self.rows) { self.rows = [NSMutableArray arrayWithCapacity:3]; } NSArray *rowArray = [row componentsSeparatedByString:@" "]; [self.rows addObject:rowArray]; } - (NSInteger)difsCompareTo:(Matrix *)other { NSInteger cnt = 0; for (int i = 0; i < self.rows.count; i++) { for (int j = 0; j < self.rows[i].count; j++) { NSInteger cost = [self.rows[i][j] integerValue] - [other.rows[i][j] integerValue]; cnt += labs(cost); } } return cnt; } + (NSArray *)magicMatrix { Matrix *mtx1 = [Matrix new]; [mtx1 addRowFromString:@"8 1 6"]; [mtx1 addRowFromString:@"3 5 7"]; [mtx1 addRowFromString:@"4 9 2"]; Matrix *mtx2 = [Matrix new]; [mtx2 addRowFromString:@"4 3 8"]; [mtx2 addRowFromString:@"9 5 1"]; [mtx2 addRowFromString:@"2 7 6"]; Matrix *mtx3 = [Matrix new]; [mtx3 addRowFromString:@"2 9 4"]; [mtx3 addRowFromString:@"7 5 3"]; [mtx3 addRowFromString:@"6 1 8"]; Matrix *mtx4 = [Matrix new]; [mtx4 addRowFromString:@"6 7 2"]; [mtx4 addRowFromString:@"1 5 9"]; [mtx4 addRowFromString:@"8 3 4"]; Matrix *mtx5 = [Matrix new]; [mtx5 addRowFromString:@"6 1 8"]; [mtx5 addRowFromString:@"7 5 3"]; [mtx5 addRowFromString:@"2 9 4"]; Matrix *mtx6 = [Matrix new]; [mtx6 addRowFromString:@"8 3 4"]; [mtx6 addRowFromString:@"1 5 9"]; [mtx6 addRowFromString:@"6 7 2"]; Matrix *mtx7 = [Matrix new]; [mtx7 addRowFromString:@"4 9 2"]; [mtx7 addRowFromString:@"3 5 7"]; [mtx7 addRowFromString:@"8 1 6"]; Matrix *mtx8 = [Matrix new]; [mtx8 addRowFromString:@"2 7 6"]; [mtx8 addRowFromString:@"9 5 1"]; [mtx8 addRowFromString:@"4 3 8"]; return @[mtx1, mtx2, mtx3, mtx4, mtx5, mtx6, mtx7, mtx8]; } @end int main(int argc, const char * argv[]) { @autoreleasepool { char input[100]; Matrix *inputMtx = [Matrix new]; while(scanf("%[^\n]%*c",input)==1 ) { NSString *inputString1 = [NSString stringWithCString:input encoding:NSUTF8StringEncoding]; [inputMtx addRowFromString:inputString1]; } NSMutableArray *cnts = [NSMutableArray arrayWithCapacity:8]; for (Matrix *mtx in [Matrix magicMatrix]) { NSInteger dif = [inputMtx difsCompareTo:mtx]; [cnts addObject:@(dif)]; } NSArray *sorted = [cnts sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { return [obj1 integerValue] > [obj2 integerValue]; }]; printf("%ld", [sorted.firstObject integerValue]); } return 0; }