简体   繁体   中英

2D Char array diagonal push back from a certain index?

I need to create a function that takes a 2d char matrix and a string as a parameter, and the thing is, I need to push back all diagonal char collection which are the same characters as the string parameter, and the same length with the string parameter, for example if the matrix is:

S L A R O Q M S K
L T M A K I T T E
P O A L K Q H M C
K L A C O P L I K
W R Y U K S A X Z
P Q K I O O H J L

and the string parameter is "STACK", I need to pushback "{S, T, A, C, K}" in a 1d temporary char vector as you can see on the very first left top - bottom right diagonal.

So far I created something like this:

string matrixToString(vector<vector<char>> & mat, string searchWord) {
string s = "";
vector<char> temp;
char ch = searchWord[0];
for (unsigned int i = 0; i < mat.size(); i++) {
    for (unsigned int j = 0; j < mat[0].size(); j++) {
        for (unsigned int m = ch, n = ch; m < searchWord.length() && n < searchWord.length(); i++, j++) {
            temp.push_back(mat[m][n]);
        }
    }
}
s = charToString(temp);

return s;

}

Sample Input is:

SEARCH
DAPIJY
QTVAMK
NRAELQ
LGIFTZ
///
SAVE

nothing being pushed in my vector, but expected was: {S, A, V, E}

what is wrong with this code and how can I implement such a function? Thank you for your help.

A wrong thing is unsigned int m = ch, n = ch . ch is not a position in the source string but rather, a character [code], so assigning it to a counter is meaningless.

Another problem (more like a typo) is incrementing i and j in the inner loop (and not touching m and n at all so the loop would be infinite, wouldn't m be so large initially).

One possible implementation of that inner loop would actually iterate over searchWord and compare its (k)th character to (i+k,j+k)th character of the matrix (be careful with matrix bounds, though). Only if all of the comparisons succeed you need to record the string, or maybe return it immediately (unless you need to eg return the location, you can return searchWord here as you just checked that it is equal to what you need to return).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM