Expansion: Added a brute force word search

Just in case
This commit is contained in:
Jérôme Guélen 2025-03-02 18:07:46 +01:00
parent 63f94dc215
commit 0703fece88
No known key found for this signature in database
2 changed files with 30 additions and 3 deletions

View file

@ -6,7 +6,7 @@
/* By: jguelen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/02 14:27:58 by jguelen #+# #+# */
/* Updated: 2025/03/02 17:51:04 by jguelen ### ########.fr */
/* Updated: 2025/03/02 18:06:54 by jguelen ### ########.fr */
/* */
/* ************************************************************************** */
@ -49,7 +49,7 @@ static int *create_kmp_array(char *needle, size_t needle_len)
}
/*
** @Param Should only be provided with non NULL or empty arguments
** @Param Should only be provided with arguments that are neither NULL or empty
** Could be extended to report all occurrences of needle in haystack
** but for now only reports the first.
** (cf http://monge.univ-mlv.fr/~lecroq/string/node8.html#SECTION0080)
@ -80,3 +80,24 @@ ssize_t word_search_kmp(char *haystack, char *needle)
free(kmp);
return (-1);
}
/*
** Should not be given NULL or empty arguments.
*/
ssize_t word_search_brute(char *haystack, char *needle)
{
ssize_t i;
size_t needle_len;
size_t haystack_len;
needle_len = ft_strlen(needle);
haystack_len = ft_strlen(haystack);
i = 0;
while (i <= (haystack_len - needle_len))
{
if (ft_memcmp(haystack + i, needle, needle_len) == 0)
return (i);
i++;
}
return (-1);
}

View file

@ -6,7 +6,7 @@
/* By: jguelen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/02 14:10:36 by jguelen #+# #+# */
/* Updated: 2025/03/02 14:30:16 by jguelen ### ########.fr */
/* Updated: 2025/03/02 17:56:02 by jguelen ### ########.fr */
/* */
/* ************************************************************************** */
@ -59,5 +59,11 @@
** -1 if no such occurrence was found and -2 in case of allocation error.
*/
ssize_t word_search_kmp(char *haystack, char *needle);
/*
** The simple, familiar brute force searching algorithm of a word in a text.
** Returns the index where an occurrence of needle is found in haystack, or
** -1 if no such occurrence exists.
*/
ssize_t word_search_brute(char *haystack, char *needle);
#endif