Looking for a word in a 2D array

7 visualizaciones (últimos 30 días)
Alex Flores
Alex Flores el 28 de Abr. de 2017
Comentada: Alex Flores el 2 de Mayo de 2017
Hey guys, so I am having trouble finishing my code for this problem: Write a function called WordSearch.m that looks for a word in a 2-D character array. The function should take in two inputs:
  1. an m by n character array (letters in the Englishalphabet) that is the word search grid and
  2. a cell array of words that should be searchedfor.
The function looks for each word from the cell array in the 2-D character array. It searches for the word horizontally (left-to-right) and vertically (top-to-bottom). The function then returns a cell array that stores the row and column indices of the first character of the word if the word was found and an empty array ([]) if the word was not found. Your function should ignore the case of the letters. Your function does not need to find words ordered diagonally or backwards (right-to-left or bottom-to-top). Example:
testArray=['c' 'E' 'L' 'l'; 'S' 'U' 'r' 'I'; 'e' 'f' 'd' 'S'; 'T' 'A' 'G' 't'];
function cellArray= WordSearch(array,words)
[s1,s2]= size(words)
[m,n]= size(array)
cellArray=[]
B=1
r=1
c=1
%
for ii=1:s2 %word
found = 1 %true
for r:m %row
%
if (strcmpi(array(r,:), words(ii))==1) %L to R
cellArray(B)=[r,c]
B=B+1
found = 0 %turns false
%
elseif found
for c:n %column
if (strcmpi(array(:,c), words(ii))==1)% T to B
cellArray(B)=[r,c]
B=B+1
else
cellArray(B)=[]
B=B+1
end
end
end
end
end
Im pretty stuck and do not know where to go from here.
Thanks in advance :)

Respuestas (1)

Joseph Cheng
Joseph Cheng el 28 de Abr. de 2017
I would take a look at the function strfind(), and lower() or upper().
strfind() will return the starting index value of the found string.
so if i had
testArray = ['c' 'E' 'L' 'l'; 'S' 'U' 'r' 'I'; 'e' 'f' 'd' 'S'; 'T' 'A' 'G' 't']
words = {'Cell','set','sell'}
[row]=strfind(testArray(1,:),lower(words{1}));
[col]=strfind(testArray(:,1)',lower(words{1}));
%replacing the 1 there with the an incremental index of the for loop
you can see that col returns with 1 and col is empty because the string was not found vertically (note the transpose and retreival of the of the column array)
with that you can then see which one you have, row or column and which column/row you fed it from the for loop.
  1 comentario
Alex Flores
Alex Flores el 2 de Mayo de 2017
where do you suggest I insert this?

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by