word_search_solver/
lib.rs

1/// Finds the positions, if any, of the starting character of
2/// any matches in any direction.
3/// `word_search` is expected to be a 2d array with all rows being the same length.
4/// The resulting vec may have duplicates depending on if the starting character there
5/// has valid words in multiple directions.
6pub fn find_word_in_word_search(word: &str, word_search: &Vec<Vec<char>>) -> Vec<(usize, usize)> {
7	let mut matches = vec![];
8
9	// edge cases
10	if word.len() == 0 || word_search.len() == 0 || word_search[0].len() == 0 {
11		return vec![];
12	}
13
14	let word_chars = word.chars().collect::<Vec<char>>();
15	let word_len = word_chars.len() as isize;
16	let word_search_width = word_search[0].len() as isize;
17	let word_search_height = word_search.len() as isize;
18
19	// loop through every coord in word_search
20	for y in 0..word_search_height {
21		for x in 0..word_search_width {
22			// if character isnt start of word, continue
23			if word_search[y as usize][x as usize] != word_chars[0] {
24				continue;
25			}
26
27			// loop through every direction that a word can go in
28			let deltas = [
29				(-1, -1),
30				(-1, 0),
31				(-1, 1),
32				(0, -1),
33				(0, 1),
34				(1, -1),
35				(1, 0),
36				(1, 1),
37			];
38			'deltas_loop: for (dx, dy) in deltas {
39				// check if direction would not end up oob
40				let end_x = x + dx * (word_len - 1);
41				let end_y = y + dy * (word_len - 1);
42				if end_x >= word_search_width
43					|| end_y >= word_search_height
44					|| end_x < 0 || end_y < 0
45				{
46					continue;
47				}
48
49				// loop through every character in the direction
50				// and see if any of them don't match up with the word
51				for i in 0..word_len {
52					let xprime = x + dx * i;
53					let yprime = y + dy * i;
54					if word_search[yprime as usize][xprime as usize] != word_chars[i as usize] {
55						continue 'deltas_loop;
56					}
57				}
58
59				// word found! add to matches list
60				matches.push((x as usize, y as usize));
61			}
62		}
63	}
64
65	return matches;
66}