#!/usr/bin/python3 """Given an offset d between two pixel indices in a pixel buffer that’s organized by lines, what’s the x offset between the pixels? It’s congruent to d % width, but the same number of pixels might represent a positive x-offset or a negative one, depending on how close to the left border the starting pixel is. Consider in a 4×4 buffer: index 8 is pixel 0 on line 2, and index 13 is pixel 1 on line 3, so the x offset is 1. But index 7 is pixel 3 on line 1, and index 12 is pixel 0 on line 3, so the x offset is -3, even though the pixel offset is the same. It’s still only a line or two of code, but it’s easy to get wrong. It’s harder to get it write with the modulo semantics C inherited from Fortran by way of CPU designs, but Python fortunately departed from those semantics. However, given the fact that you need to know at least the x-coordinate of your starting position to answer the question, there’s an easy solution that works in C too. An investigation into , where I was mistekan about this, and . """ from hypothesis import given, assume from hypothesis.strategies import integers def pix_offset(width, x, y): return y * width + x def pix_delta_x(width, p0, p1): d = p1 - p0 dw = d % width return (dw if p0 % width + dw < width else dw - width) def pix_delta_easy(width, p0, p1): "Calculate the same as pix_delta_x in a way that works in C too." return p1 % width - p0 % width nonnegative = integers(min_value=0) widths = integers(min_value=1) @given(widths, nonnegative, nonnegative, nonnegative, nonnegative) def test_pix_delta_x(width, x0, y0, x1, y1): assume(x0 < width) assume(x1 < width) p0, p1 = pix_offset(width, x0, y0), pix_offset(width, x1, y1) assert x1 - x0 == pix_delta_x(width, p0, p1) assert x1 - x0 == pix_delta_easy(width, p0, p1) # Bound size for exhaustive model check. This is ridiculously large # but still plenty fast: N = 18 def test_bounded(): "A bounded model check for all possible values up to N." for width in range(1, N): for x0 in range(width): for y0 in range(N): do_all_p1(width, x0, y0, N) def do_all_p1(width, x0, y0, N): p0 = pix_offset(width, x0, y0) for x1 in range(width): for y1 in range(N): p1 = pix_offset(width, x1, y1) assert x1 - x0 == pix_delta_x(width, p0, p1) assert x1 - x0 == pix_delta_easy(width, p0, p1)