Certainly! Implementing the Boyer–Moore–Horspool (BMH) algorithm to search within a circular buffer requires handling the circular nature of the buffer while efficiently searching for the pattern. Below is a complete C implementation that demonstrates how to achieve this.
Overview
-
Circular Buffer Structure: We'll define a CircularBuffer structure that holds the buffer data, its capacity, and pointers to the head and tail.
-
BMH Algorithm: The BMH algorithm preprocesses the pattern to create a shift table, which determines how many characters to skip when a mismatch occurs.
-
Handling Circularity: Accessing characters in the circular buffer involves wrapping around when the end of the buffer is reached.
Implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// Define the CircularBuffer structure
typedef struct {
char *buffer; // Pointer to buffer data
size_t capacity; // Total capacity of the buffer
size_t head; // Index of the head (start of data)
size_t size; // Current size of data in buffer
} CircularBuffer;
// Initialize the circular buffer
bool initCircularBuffer(CircularBuffer *cb, size_t capacity) {
cb->buffer = (char *)malloc(capacity * sizeof(char));
if (!cb->buffer) {
return false;
}
cb->capacity = capacity;
cb->head = 0;
cb->size = 0;
return true;
}
// Free the circular buffer
void freeCircularBuffer(CircularBuffer *cb) {
free(cb->buffer);
cb->buffer = NULL;
cb->capacity = 0;
cb->head = 0;
cb->size = 0;
}
// Add a character to the circular buffer
bool addChar(CircularBuffer *cb, char c) {
if (cb->size < cb->capacity) {
size_t index = (cb->head + cb->size) % cb->capacity;
cb->buffer[index] = c;
cb->size++;
return true;
} else {
// Buffer is full; overwrite the oldest character
cb->buffer[cb->head] = c;
cb->head = (cb->head + 1) % cb->capacity;
return true;
}
}
// Function to get character at logical index in buffer
char getChar(const CircularBuffer *cb, size_t index) {
if (index >= cb->size) {
// Out of bounds
return '\0';
}
size_t realIndex = (cb->head + index) % cb->capacity;
return cb->buffer[realIndex];
}
// Boyer-Moore-Horspool search in circular buffer
// Returns the starting index of the first occurrence, or -1 if not found
long boyerMooreHorspoolSearch(const CircularBuffer *cb, const char *pattern) {
size_t m = strlen(pattern);
if (m == 0 || m > cb->size) {
return -1;
}
// Preprocess the shift table
int shift[256];
for (int i = 0; i < 256; i++) {
shift[i] = m;
}
for (size_t i = 0; i < m - 1; i++) {
shift[(unsigned char)pattern[i]] = m - 1 - i;
}
size_t n = cb->size;
size_t i = m - 1;
while (i < n) {
size_t j = m - 1;
bool mismatch = false;
while (j < m) {
char bufferChar = getChar(cb, i - j);
char patternChar = pattern[j];
if (bufferChar != patternChar) {
mismatch = true;
break;
}
if (j == 0) break;
j--;
}
if (!mismatch) {
// Match found at position (i - m + 1)
return (long)(i - m + 1);
}
// Shift the window
char nextChar = getChar(cb, i);
i += shift[(unsigned char)nextChar];
}
return -1; // Not found
}
// Helper function to print the buffer (for debugging)
void printBuffer(const CircularBuffer *cb) {
printf("Buffer content: ");
for (size_t i = 0; i < cb->size; i++) {
printf("%c", getChar(cb, i));
}
printf("\n");
}
int main() {
// Example usage
CircularBuffer cb;
size_t capacity = 20;
if (!initCircularBuffer(&cb, capacity)) {
fprintf(stderr, "Failed to initialize circular buffer.\n");
return 1;
}
// Add data to the buffer
const char *data = "This is a sample text for testing.";
for (size_t i = 0; i < strlen(data); i++) {
addChar(&cb, data[i]);
}
printBuffer(&cb);
// Define the pattern to search
const char *pattern = "sample";
// Perform the search
long index = boyerMooreHorspoolSearch(&cb, pattern);
if (index != -1) {
printf("Pattern \"%s\" found at index %ld.\n", pattern, index);
} else {
printf("Pattern \"%s\" not found.\n", pattern);
}
// Clean up
freeCircularBuffer(&cb);
return 0;
}
Explanation
-
Circular Buffer Initialization and Management:
CircularBuffer: A structure to hold buffer data, capacity, head index, and current size.
initCircularBuffer(): Initializes the buffer with the given capacity.
addChar(): Adds a character to the buffer. If the buffer is full, it overwrites the oldest character and updates the head.
getChar(): Retrieves a character at a logical index, accounting for the circular nature.
-
Boyer-Moore-Horspool Algorithm:
- Shift Table: An array
shift[256] is created to store the shift values for each possible character (assuming ASCII). It initializes all shifts to the length of the pattern, and then for each character in the pattern (except the last one), it sets the shift value based on its position.
- Search Process:
- Start comparing from the end of the pattern.
- If characters match, continue backward; if all characters match, return the starting index.
- If a mismatch occurs, use the shift table to determine how many positions to skip ahead.
- Handling Circularity: The
getChar() function abstracts the circular access, ensuring that character retrieval wraps around the buffer seamlessly.
-
Usage Example in main():
- Initializes a circular buffer with a capacity of 20.
- Adds a sample string to the buffer.
- Searches for the pattern "sample" using the BMH algorithm.
- Prints the result of the search.
Notes
-
Character Set: This implementation assumes an ASCII character set (256 possible characters). If you are dealing with a different character set or multi-byte characters (like UTF-8), the shift table and comparison logic need to be adjusted accordingly.
-
Efficiency: The BMH algorithm is efficient for large texts and patterns, especially when the pattern is not too short. However, for very small patterns (e.g., single characters), simpler algorithms like the Knuth-Morris-Pratt (KMP) may be more appropriate.
-
Edge Cases: The implementation checks for cases where the pattern is empty or longer than the buffer content, returning -1 (not found) accordingly.
-
Overwriting Behavior: In the addChar() function, when the buffer is full, new characters overwrite the oldest ones. Depending on your use case, you might want to handle this differently.
Sample Output
Buffer content: This is a sample text for testing.
Pattern "sample" found at index 10.
This output indicates that the pattern "sample" was successfully found starting at index 10 in the circular buffer.