Algorithms (algorithm)#

group algorithm

Algorithms for sorting, searching, and matrix/list/sequence operations.

For an overview, see Algorithms.

rcsw/algorithm/algorithm.h#

Useful algorithms for arrays, lists, matrices, sequences, etc.

Functions

bool str_is_parenthesizable(const char *x, char *r, char el, char (*multiply_cb)(char x, char y))#

Deterimine if a parenthesization for x exists such that the value of the resulting expression is el, where el is some element of the alphabet.

Parameters:
  • x – String to attempt to parenthesize

  • r – Result matrix (assumed to be |x| by |x|)

  • el – The goal char

  • multiply_cb – Callback to multiple two chars in the alphabet

Returns:

true if such a parenthesization exists; false if not, or if a parameter is invalid.

rcsw/algorithm/edit_dist.h#

Algorithm for finding the edit distance between two sequences of objects.

Functions

status_t edit_dist_init(struct edit_dist_finder *finder, const void *a, const void *b, size_t elt_size, bool (*cmpe)(const void *e1, const void *e2), size_t (*seq_len)(const void *seq))#

Initialize an edit distance finder.

Parameters:
  • finder – The finder to initialize

  • a – Pointer to sequence #1

  • b – Pointer to sequence #2

  • elt_size – Size of elements in bytes

  • cmpe – Callback for comparing if two sequences are equivalent or not

  • seq_len – Callback for obtaining the length of a sequence

Returns:

status_t

void edit_dist_destroy(struct edit_dist_finder *finder)#

Destroy an edit distance finder.

Parameters:
  • finder – The finder handle

int edit_dist_find(struct edit_dist_finder *finder, enum exec_type type)#

Find the edit distance between two sequences.

Parameters:
  • finder – The edit distance finder handle

  • type – The type of method to use: iterative or recursive with memoization

Returns:

The edit distance, or -1 on error

struct edit_dist_finder#
#include <rcsw/algorithm/edit_dist.h>

Algorithm handle for finding the edit distance between two contiguous sequences of objects.

Public Members

const void *seq_a#

Sequence #1.

const void *seq_b#

Sequence #1.

size_t elt_size#

Size of each element in a sequence in bytes.

int *memoization#

Memoization table used with a recursive implementation.

bool (*cmpe)(const void *const e1, const void *const e2)#

Compare two elements for equality.

size_t (*seq_len)(const void *const seq)#

Get the length of a sequence.

rcsw/algorithm/lcs.h#

Longest Common Subsequence (LCS) of two sequences of characters.

Functions

status_t lcs_init(struct lcs_calculator *lcs, const char *x, const char *y)#

Initialize a longest common subsequence (LCS) calculator.

Parameters:
  • lcs – The LCS calculator to initialize

  • x – Sequence # 1

  • y – Sequence # 2

Returns:

status_t

void lcs_destroy(struct lcs_calculator *lcs)#

Destroy a created LCS calculator.

Any further use of the LCS after calling this function is undefined.

Parameters:
  • lcs – The LCS handle

int lcs_rec(struct lcs_calculator *lcs)#

Compute the LCS of x,y using top down dynamic programming.

Parameters:
  • lcs – The LCS handle

Returns:

LCS of (x,y) or -1 if an error occurred

int lcs_iter(struct lcs_calculator *lcs)#

Compute LCS(x,y) using bottom up dynamic programming.

Parameters:
  • lcs – The LCS handle

Returns:

status_t

struct lcs_calculator#
#include <rcsw/algorithm/lcs.h>

Representation of algorithm to find the longest common subsequence of two strings.

Public Members

size_t size#

Longest common subsequence length.

size_t len_x#

Length of string #1.

size_t len_y#

Length of string #2.

const char *y#

String #2.

const char *x#

String #1.

int *results#

N x N array storing the optimal results route.

char *sequence#

Longest common subsequence.

rcsw/algorithm/mcm_opt.h#

Matrix Chain Multiplication Optimizer.

Functions

status_t mcm_opt_init(struct mcm_optimizer *mcm, const uint64_t *matrices, uint64_t size)#

Initialize a Matrix Chain Multiplication (MCM) optimizer.

Parameters:
  • mcm – The MCM to initialize

  • size – # of input matrices -1.

  • matrices – The matrix chain, but 0 indexed instead of 1 indexed.

Returns:

status_t

void mcm_opt_destroy(struct mcm_optimizer *mcm)#

Destroy an initialized optimizer.

Any further use of the MCM after calling this function is undefined.

Parameters:
  • mcm – The MCM handle

status_t mcm_opt_optimize(struct mcm_optimizer *mcm)#

Compute the best way to multiply a sequence of N matrices via iterative dynamic programming.

Parameters:
  • mcm – The MCM handle

Returns:

status_t

status_t mcm_opt_print(const struct mcm_optimizer *mcm)#

Print the results of the chain order optimization to stdout.

Parameters:
  • mcm – The MCM handle

Returns:

status_t

status_t mcm_opt_report(const struct mcm_optimizer *mcm, uint64_t *ordering)#

Report the results of chain order optimization via filling an array of integers with the indices of the matrix chain (0 for p[0], 1 for p[1], etc.).

Parameters:
  • mcm – The MCM handle

  • ordering – Array to be filled with indices of optimal multiplication

Returns:

status_t

struct mcm_optimizer#
#include <rcsw/algorithm/mcm_opt.h>

Matrix chain multiplication optimizer.

Public Members

uint64_t min_mults#

Minimum # of scalar multiplications needed for the chain.

const uint64_t *matrices#

Input matrices, specified as an array of the outer dimensions.

size_t size#

of input matrices.#

uint64_t *results#

N x N array of optimil multiplication costs.

uint64_t *route#

N x N array storing the optimal results route.

uint64_t *ordering#

Optimal multiplicative ordering, specified as 0-indexed matrix IDs.

rcsw/algorithm/search.h#

Collection of search algorithms. Binary search in iterative and recursive variants.

Functions

int bsearch_iter(const void *a, const void *e, int (*cmpe)(const void *e1, const void *e2), size_t elt_size, int low, int high)#

Search a sorted array using binary search (iterative).

O(log n). Preferred over bsearch_rec() for large arrays as it does not grow the stack.

Warning

The array must be sorted in the order defined by cmpe. Passing an unsorted array produces undefined results.

Parameters:
  • a – The array to search.

  • e – The element to search for.

  • cmpe – Comparison callback. Must return <0, 0, or >0 per the standard comparator convention.

  • elt_size – Size of each element in bytes.

  • low – Lowest index to consider (typically 0).

  • high – Highest index to consider (typically max index of array).

Returns:

Index of the matching element, or -1 if not found or on error.

int bsearch_rec(const void *in, const void *e, int (*cmpe)(const void *e1, const void *e2), size_t elt_size, int low, int high)#

Search a sorted array using binary search (recursive).

O(log n). Stack depth is O(log n); prefer bsearch_iter() for large arrays or constrained stacks.

Warning

The array must be sorted in the order defined by cmpe. Passing an unsorted array produces undefined results.

Parameters:
  • in – The array to search.

  • e – The element to search for.

  • cmpe – Comparison callback. Must return <0, 0, or >0 per the standard comparator convention.

  • elt_size – Size of each element in bytes.

  • low – Lowest index to consider (typically 0).

  • high – Highest index to consider (typically max index of array).

Returns:

Index of the matching element, or -1 if not found or on error.

rcsw/algorithm/sort.h#

Collection of sorting algorithms.

Functions

status_t qsort_rec(void *a, int min_index, int max_index, size_t elt_size, int (*cmpe)(const void *const e1, const void *const e2))#

Sort an array using recursive quicksort.

Average case O(n log n). The pivot is the median of the first, middle, and last elements, and partitioning splits runs of equal keys evenly, so sorted, reverse-sorted, and all-equal input are all O(n log n); O(n²) is possible only for adversarially constructed input. Not stable. Recursion is only into the smaller partition, so recursion depth is at most log2(n).

Parameters:
  • a – The input array.

  • min_index – Starting index (inclusive).

  • max_index – Ending index (inclusive).

  • elt_size – Size of each element in bytes.

  • cmpe – Comparison function for elements.

status_t qsort_iter(void *a, int max_index, size_t elt_size, int (*cmpe)(const void *const e1, const void *const e2))#

Sort an array using iterative quicksort.

Same pivot selection, partitioning, and complexity as qsort_rec(), but uses a fixed-size explicit stack instead of recursion: the smaller partition is always processed first, so at most log2(n) partitions are pending.

Parameters:
  • a – Array to sort.

  • max_index – Maximum index to sort up to (i.e., sorts [0, max_index]).

  • elt_size – Size of each element in bytes.

  • cmpe – Comparison function for elements.

status_t radix_sort(size_t *arr, size_t *tmp, size_t n_elts, size_t base)#

Sort an array of non-negative integers using radix sort.

O(nk) time and space, where k is the number of digits in the maximum element value for the given base. Non-comparative; integer keys only.

Parameters:
  • arr – The array to sort.

  • tmp – Temporary array used during sorting. Must be at least as large as arr.

  • n_elts – Number of elements in arr and tmp.

  • base – Numeric base for digit decomposition (e.g., 10, 8, 16).

status_t insertion_sort(void *arr, size_t n_elts, size_t elt_size, int (*cmpe)(const void *const e1, const void *const e2))#

Sort an array using insertion sort.

O(n²) average and worst case. Only appropriate for very small arrays or arrays that are known to be nearly sorted. For general use prefer qsort_rec() or qsort_iter().

Parameters:
  • arr – The array to sort.

  • n_elts – Number of elements in the array.

  • elt_size – Size of each element in bytes.

  • cmpe – Comparison function for elements.

status_t radix_counting_sort(size_t *arr, size_t *tmp, size_t n_elts, size_t digit, size_t base)#

Sort an array of non-negative integers via counting sort.

Internal helper used by radix_sort(). Processes one digit of each element at a time.

Parameters:
  • arr – The array to sort.

  • tmp – Temporary array; must be at least as large as arr.

  • n_elts – Number of elements in arr and tmp.

  • digit – Current digit position being processed.

  • base – Numeric base; must be <= 16.

Returns:

status_t

status_t radix_sort_prefix_sum(const size_t *arr, size_t n_elts, size_t digit, size_t base, size_t *prefix_sums)#

Compute prefix sums for one digit pass of radix sort.

Internal helper used by radix_sort(). Counts how many values are less than arr[i] for the given digit position.

Parameters:
  • arr – The array being sorted.

  • n_elts – Number of elements in arr.

  • digit – Current digit position being processed.

  • base – Numeric base; must be <= 16.

  • prefix_sums – Output array (same size as arr) to receive prefix sums.

Returns:

status_t