c++arrays2dcrossword

Crossword game: read 2d given array and search diagonally c++


This is a crossword game. I wanna read an array diagonally. I should find some word in all over the 2d given array this array read from a given file and it is n*m size; m not always = n

How can I read 2d given diagonally like this:

Example:

m = 4
n = 4
b o o k
z a k o
s l l e
x y z l

ball: found

[b] o o k
z [a] k o
s l [l] e
x y z [l]

foo: not found

Here is the code:

char ReadArray(char* array, int r, int c, int n, int m)
{
   return (r > 0 && r <= n && c > 0 && c <= m) ?
                  array[n * (r - 1) + (c - 1)] : '\0';
}

Solution

  • char readrc(char* array, int r, int c, int n, int m)
    {
       return (r > 0 && r <= n && c > 0 && c <= m) ?
                      array[n * (r - 1) + (c - 1)] : '\0';
    }
    
    void read_down_right(char* array, int n, int m, vector<string>& list)
    {
       for (int sc = 2 - n; sc <= m - 1; sc++)
       {  
          string str = "";
          for (int r = 1, c = sc; r <= n; r++, c++)
          {
             char chr = readrc(array, r, c, n, m);
             if (chr != '\0')
                str += chr;
          }
          list.push_back(str);
       }
    }
    
    void read_down_left(char* array, int n, int m, vector<string>& list)
    {
       for (int sc = 2; sc <= m + n - 2; sc--)
       { 
          string str = "";
          for (int r = 1, c = sc; r <= n; r++, c--)
          {
             char chr = readrc(array, r, c, n, m);
             if (chr != '\0')
                str += chr;
          }
          list.push_back(str);
       }
    }
    

    pass a reference to a blank list each time. list contains all possible strings afterwards, do a linear search.