"K nearest points to the origin on a 2D plane"
- I took this to mean "write an algorithm that figure out K closest coordinates to the origin (0, 0) of a 2D matrix.
- Assume origin is at top left.
- We want to fan out from the origin. Choosing coordinates in the order along X and Y in an order closest to origin.
- For example, for Row 2, Col 2 = (2,0), (0,2), (2,1), (1,2), (2,2)
- Example class in Objective-C:
@interface CloseToMatrixOrigin : NSObject
+ (void)printK:(int)k closestCoordinateToOriginOfMatrix:(NSArray*)matrix;
@end
@implementation CloseToMatrixOrigin
+ (void)printK:(int)k closestCoordinateToOriginOfMatrix:(NSArray*)matrix {
int count = 0;
for (int i = 0; i < [matrix count]; i++) {
for (int j = 0; j <= i; j++) {
int row;
int col;
if (j != i) {
for (int toggle = 1; toggle <= 2; toggle++) {
row = (toggle == 1) ? i : j;
col = (toggle == 1) ? j : i;
if (![CloseToMatrixOrigin printRow:row andCol:col forCount:++count andK:k]) {
return;
}
}
} else {
row = col = i;
if (![CloseToMatrixOrigin printRow:row andCol:col forCount:++count andK:k]) {
return;
}
}
}
}
}
+ (BOOL)printRow:(int)row andCol:(int)col forCount:(int)count andK:(int)k {
NSLog(@"[%d, %d]", row, col);
if (count == k) {
return NO;
}
return YES;
}
@end