Can you implement the Boyer–Moore-Horspool algorithmfor a circular buffer in C?
- User
Can you implement the Boyer–Moore-Horspool algorithmfor a circular buffer in C?
- Assistant
Can you implement the Boyer–Moore-Horspool algorithmfor a circular buffer in C?
Certainly! The Boyer–Moore–Horspool (BMH) algorithm is an efficient string-searching algorithm that preprocesses the pattern to create a bad character shift table, allowing the search to skip sections of the text, thus improving performance compared to naïve search methods.
When dealing with a circular buffer, the primary challenge is handling the wrap-around nature of the buffer. This means that the buffer's end is logically connected to its beginning, and indices must be managed modulo the buffer's capacity to ensure correct access.
Below is a comprehensive implementation of the BMH algorithm tailored for a circular buffer in C. The implementation includes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define the maximum shift value based on the character set
#define ALPHABET_SIZE 256
// Structure for Circular Buffer
typedef struct {
char *buffer; // Pointer to buffer memory
size_t capacity; // Total capacity of the buffer
size_t size; // Current number of elements
size_t head; // Start index of the buffer
} CircularBuffer;
// Initialize the circular buffer
CircularBuffer* init_circular_buffer(size_t capacity) {
CircularBuffer *cb = malloc(sizeof(CircularBuffer));
if (!cb) {
perror("Failed to allocate circular buffer");
exit(EXIT_FAILURE);
}
cb->buffer = malloc(capacity * sizeof(char));
if (!cb->buffer) {
perror("Failed to allocate buffer memory");
free(cb);
exit(EXIT_FAILURE);
}
cb->capacity = capacity;
cb->size = 0;
cb->head = 0;
return cb;
}
// Free the circular buffer
void free_circular_buffer(CircularBuffer *cb) {
if (cb) {
free(cb->buffer);
free(cb);
}
}
// Add a character to the circular buffer
void add_char(CircularBuffer *cb, char c) {
if (cb->size < cb->capacity) {
cb->buffer[(cb->head + cb->size) % cb->capacity] = c;
cb->size++;
} else {
// Overwrite the oldest data
cb->buffer[cb->head] = c;
cb->head = (cb->head + 1) % cb->capacity;
}
}
// Get character at logical index (0 to size-1)
char get_char(const CircularBuffer *cb, size_t index) {
if (index >= cb->size) {
fprintf(stderr, "Index out of bounds\n");
exit(EXIT_FAILURE);
}
return cb->buffer[(cb->head + index) % cb->capacity];
}
// BMH Search in Circular Buffer
// Returns the starting index of the first occurrence of pattern in buffer
// Returns -1 if not found
ssize_t bmh_search_circular(const CircularBuffer *cb, const char *pattern, size_t pattern_len) {
if (pattern_len == 0 || pattern_len > cb->size) {
return -1;
}
// Preprocessing: Create the bad character shift table
size_t shift_table[ALPHABET_SIZE];
for (int i = 0; i < ALPHABET_SIZE; i++) {
shift_table[i] = pattern_len;
}
for (size_t i = 0; i < pattern_len - 1; i++) {
shift_table[(unsigned char)pattern[i]] = pattern_len - 1 - i;
}
size_t i = 0; // Index in buffer
while (i <= cb->size - pattern_len) {
size_t j = pattern_len - 1;
// Compare the pattern with the buffer
while (j < pattern_len && pattern[j] == get_char(cb, i + j)) {
if (j == 0) {
return i; // Match found
}
j--;
}
// Calculate shift
unsigned char mismatched_char = get_char(cb, i + pattern_len - 1);
size_t shift = shift_table[mismatched_char];
if (shift == 0) {
shift = 1;
}
i += shift;
}
return -1; // Not found
}
// Example usage
int main() {
// Initialize circular buffer with capacity 20
CircularBuffer *cb = init_circular_buffer(20);
// Example data to add to circular buffer
const char *data = "This is a sample text for Boyer-Moore-Horspool.";
for (size_t i = 0; i < strlen(data); i++) {
add_char(cb, data[i]);
}
// Define pattern to search
const char *pattern = "Moore";
size_t pattern_len = strlen(pattern);
// Perform BMH search
ssize_t index = bmh_search_circular(cb, pattern, pattern_len);
if (index != -1) {
printf("Pattern found at index: %zd\n", index);
// To print the matched substring
printf("Matched substring: ");
for (size_t i = 0; i < pattern_len; i++) {
printf("%c", get_char(cb, index + i));
}
printf("\n");
} else {
printf("Pattern not found.\n");
}
// Clean up
free_circular_buffer(cb);
return 0;
}
Circular Buffer Structure:
buffer: Dynamically allocated array to hold characters.capacity: Total size of the buffer.size: Current number of elements in the buffer.head: Index of the oldest element in the buffer.Initialization and Cleanup:
init_circular_buffer: Allocates memory for the buffer and initializes its attributes.free_circular_buffer: Frees the allocated memory to prevent memory leaks.Buffer Operations:
add_char: Adds a character to the buffer. If the buffer is full, it overwrites the oldest character and adjusts the head.get_char: Retrieves a character at a given logical index, handling wrap-around using modulo arithmetic.BMH Search Function (bmh_search_circular):
ALPHABET_SIZE typically 256 for extended ASCII).Example Usage:
bmh_search_circular function to find the pattern.Buffer Wrap-Around: The get_char function ensures that any access beyond the buffer's end wraps around to the beginning, maintaining the circular nature.
Shift Table: The shift table is crucial for the BMH algorithm's efficiency, allowing it to skip sections of the buffer. It's built based on the pattern, excluding the last character to handle cases where mismatches occur near the end of the pattern.
Performance: The BMH algorithm typically offers good performance, especially for longer patterns, by minimizing the number of character comparisons.
Error Handling: The implementation includes basic error handling (e.g., index out of bounds), but depending on the use case, you might want to enhance it further.
To test the implementation:
Compile the code using a C compiler, for example:
gcc -o bmh_circular bmh_circular.c
Run the executable:
./bmh_circular
You should see output indicating whether the pattern was found and its position within the circular buffer.
Pattern found at index: 24
Matched substring: Moore
This output indicates that the pattern "Moore" was found starting at index 24 within the circular buffer.
Feel free to modify the data and pattern variables in the main function to test different scenarios and patterns within the circular buffer.
Not yet included in a published release.