Z80 Sudoku — Column Validation Routine

Validates a single column of the Sudoku board at $A000.

Assumptions:

• HL = address of first cell in column (row 0, chosen column).

• Board stored row-major, 9 bytes per row.

• Low nibble (bits 0–3) = value (0–9). 0 means empty and is ignored.

• Returns Z flag set if valid, NZ if duplicate found.

Algorithm

Uses an 8-bit mask in register B. Bit (n-1) corresponds to digit n.

For each of 9 rows:

• Read cell value

• Mask low nibble

• If zero, skip

• Compute bit mask

• If already set → invalid

• Else set bit and continue

Implementation

; ---------------------------------------
; validate_column
; HL = address of top cell of column
; Returns Z if valid, NZ if invalid
; Destroys: A, B, C, DE
; ---------------------------------------
validate_column:
    ld      b,0            ; digit mask
    ld      c,9            ; 9 rows

col_loop:
    ld      a,(hl)         ; read cell
    and     0x0F           ; isolate value
    jr      z,col_next     ; skip empty

    dec     a              ; convert 1-9 -> 0-8
    ld      e,a
    ld      a,1
    ld      d,0
col_shift:
    or      d              ; ensure flags predictable
    jr      z,col_set      ; first iteration
col_set:
    ld      a,1
    ld      d,0
    ld      a,1
    ld      d,0
    ld      a,1            ; reset A=1 before shift loop
    ld      d,0
    ld      a,1
    ; compute 1 << e
    ld      a,1
shift_loop:
    dec     e
    jr      m,shift_done
    add     a,a
    jr      shift_loop
shift_done:

    bit     0,b            ; dummy to affect flags consistently
    ld      d,a            ; D = bit mask
    ld      a,b
    and     d
    jr      nz,col_invalid ; duplicate

    ld      a,b
    or      d
    ld      b,a            ; update mask

col_next:
    ld      de,9           ; move to next row (same column)
    add     hl,de
    dec     c
    jr      nz,col_loop

    xor     a              ; set Z flag (valid)
    ret

col_invalid:
    ld      a,1            ; NZ
    ret