def img_av(img, x, y) if x >= 0 && x < img[0].length() && y >= 0 && y < img.length() width = img[0].length() height = img.length() # For ignoring invalid sub-scriptions leftEnd0 = 1 - (width - x) / width rightEnd0 = 1 - (x + 1) / width top0 = 1 - (height - y) / height bottom0 = 1 - (y + 1) / height # Use modulo in order to avoid accessing invalid areas sum = img[y][x] + img[y][(x-1) % width] * leftEnd0 + img[y][(x+1) % width] * rightEnd0 + img[(y-1) % height][x] * top0 + img[(y+1) % height][x] * bottom0 + img[(y-1) % height][(x-1) % width] * leftEnd0*top0 + img[(y-1) % height][(x+1) % width] * rightEnd0*top0 + img[(y+1) % height][(x-1) % width] * leftEnd0*bottom0 + img[(y+1) % height][(x+1) % width] * rightEnd0*bottom0 length = 1 + leftEnd0 + rightEnd0 + top0 + bottom0 + leftEnd0 * top0 + rightEnd0 * top0 + leftEnd0 * bottom0 + rightEnd0 * bottom0 sum * 1.0 / length else -1 end end