Count of number of given string in 2D character array
Sun Apr 07 2024
findString:
A function meticulously designed to traverse the 2D array, scrutinizing each character as a potential starting point for the given string. By considering horizontal (both left and right) and vertical (both up and down) orientations, the method comprehensively searches for matching sequences. It employs a nested loop structure, first to navigate through the array's rows and columns, and then to compare subsequent characters in the potential matching direction with the string's characters. When a full match is identified, the count is incremented, reflecting the presence of the string in that orientation.
1let twoDArr = [
2  ['D', 'D', 'D', 'G', 'D', 'D'],
3  ['B', 'B', 'D', 'E', 'B', 'S'],
4  ['B', 'S', 'K', 'E', 'B', 'K'],
5  ['D', 'D', 'D', 'D', 'D', 'E'],
6  ['D', 'D', 'D', 'D', 'D', 'E'],
7  ['D', 'D', 'D', 'D', 'D', 'G'],
8];
9let str = 'GEEKS';
10//TC : O(mns)
11function findString(str, arr) {
12  let count = 0;
13  for (let i = 0; i < arr.length; i++) {
14    for (let j = 0; j < arr[i].length; j++) {
15      if (arr[i][j] === str[0]) {
16        if (j + str.length <= arr[i].length) { 
17            let matches = true;
18            for (let k = 0; k < str.length; k++) {
19              if (arr[i][j + k] !== str[k]) {
20                matches = false;
21                break;
22              }
23            }
24            if (matches) count++;
25          }
26          if (j - str.length + 1 >= 0) {
27            let matches = true;
28            for (let k = 0; k < str.length; k++) {
29              if (arr[i][j - k] !== str[k]) {
30                matches = false;
31                break;
32              }
33            }
34            if (matches) count++;
35          }
36          if (i + str.length <= arr.length) {
37            let matches = true;
38            for (let k = 0; k < str.length; k++) {
39              if (arr[i + k][j] !== str[k]) {
40                matches = false;
41                break;
42              }
43            }
44            if (matches) count++;
45          }
46          if (i - str.length + 1 >= 0) { 
47            let matches = true;
48            for (let k = 0; k < str.length; k++) {
49              if (arr[i - k][j] !== str[k]) {
50                matches = false;
51                break;
52              }
53            }
54            if (matches) count++;
55          }
56      }
57      
58    }
59  }
60  return count;
61}
62console.log(findString(str, twoDArr));
63
64
65let twoDArr1 = [
66    ['B','B','M','B','B','B'],
67    ['C','B','A','B','B','B'],
68    ['I','B','G','B','B','B'],
69    ['G','B','I','B','B','B'],
70    ['A','B','C','B','B','B'],
71    ['M','C','I','G','A','M'],
72  ];
73  let str1 = 'MAGIC';
74  console.log(findString(str1, twoDArr1));