Friday, August 21, 2015

boggle game

tuple(i, j, direction) boggle(a, word):
    if a == null || word == null:
        throw
    for i = 0, i < a.length, i++:
        if a[i] == null:
            throw
        for j = 0, j < a[i].length, j++:
            // right
            if i+word.length <= a.length: // only check if word fits
                for k = 0, k < word.length, k++:
                    if a[i+k][j] != word[k]:
                        break
                if k == word.length:
                    return tuple(i, j, direction.right)
            // left
            if i-word.length+1 >= 0: // only check if word fits
                for k = 0, k < word.length, k++:
                    if a[i-k][j] != word[k]:
                        break
                if k == word.length:
                    return tuple(i, j, direction.left)
            // down
            if j+word.length <= a.length: // only check if word fits
                for k = 0, k < word.length, k++:
                    if a[i][j+k] != word[k]:
                        break
                if k == word.length:
                    return tuple(i, j, direction.down)
            // up
            if j-word.length+1 >= 0: // only check if word fits
                for k = 0, k < word.length, k++:
                    if a[i][j-k] != word[k]:
                        break
                if k == word.length:
                    return tuple(i, j, direction.up)
    return null
[Hat tip to SM]

No comments:

Post a Comment