Tuesday, June 26, 2012

Some useful matrix methods...


Every time while developing iOS Applications which use matrix related calculations, I used to think how to convert index to matrix co-ordinate etc. So i thought of writing this one -  why to reinvent the wheel every-time :)

-(NSInteger) getIndexFromMatrix : (CGPoint) inPoint size:(CGSize)gridSize
{
    if( (inPoint.x >= 0 && inPoint.x < gridSize.width) && (inPoint.y >= 0 && inPoint.y < gridSize.height))
        return inPoint.x*(gridSize.width-1) + (inPoint.x+inPoint.y);
    return -1;
}

-(CGPoint) getMatrixFromIndex : (NSInteger) index size:(CGSize)gridSize
{
    return CGPointMake(index/(int)gridSize.width, index%(int)gridSize.height);
}

-(BOOL) isIndexIsDialognal:(CGPoint)index1 andIndex:(CGPoint)index2
{
    return (abs(index1.x - index2.x)==abs(index1.y - index2.y));
}

-(NSMutableArray*) adjacentIndicesForIndex:(CGPoint)inPoint matrixSize:(CGSize) matrixSize
{
    NSMutableArray *array = [NSMutableArray array];
    
    for (int dx = -1; dx <= 1; ++dx) 
        for (int dy = -1; dy <= 1; ++dy) 
            if (dx != 0 || dy != 0
            {
                CGPoint adjacentIndex = CGPointMake(inPoint.x + dx, inPoint.y + dy);
                if(![self isIndexIsDialognal:adjacentIndex andIndex:inPoint]) //Checking for diagonal elements
                {
                    NSInteger index = [self getIndexFromMatrix:adjacentIndex size:matrixSize];
                    if(index >= 0)
                        [array addObject:[NSNumber numberWithInt:index]];
                }
            }
    return array;
}

No comments:

Post a Comment