Detect Circular Pattern Match

Code

#include <stdio.h>
#include <stdint.h>

uint8_t is_circular_match(uint16_t reg, uint16_t target) {
    uint32_t doubled = ((uint32_t)reg << 16) | reg;
    for(int i = 0; i < 16; i++){
        if (((doubled >> i) & 0xFFFF) == target)
           return 1;
    }
    return 0;
}

int main() {
    uint16_t reg, target;
    scanf("%hu %hu", &reg, &target);
    printf("%hhu", is_circular_match(reg, target));
    return 0;
}

Solving Approach

  • Duplicate the bits(reg << 16) | reg
    This creates a 32-bit value that contains all possible rotations of reg.
  • Slide a 16-bit window through this 32-bit value.
    For each shift i (0 to 15), extract (doubled >> i) & 0xFFFF.
  • Compare each 16-bit window with target.
  • If any match → return 1, else return 0

 

 

Upvote
Downvote
Loading...

Input

45056 11

Expected Output

1