'string search algorithm for 2d array
So im creating a Airline counter simulation in python.
Arr = np.array( [
["","A","B","C","D","E","F"],
["1","0","0","0","0","0","0"],
["2","0","0","0","0","0","0"],
["3","0","0","0","0","0","0"],
["4","0","0","0","0","0","0"],
["5","0","0","0","0","0","0"],
["6","0","0","0","0","0","0"],
["7","0","0","0","0","0","0"],
["8","0","0","0","0","0","0"]
])
this is my basic airplane representation, a string 2d array, when a seat is reserved an "0" will turn into a "X". I want some type of searching algorithm (preferably some type of binary or linear search) to find the position where X is located on the array(it may have multiple "X" in the array) Example
Arr = np.array( [
["","A","B","C","D","E","F"],
["1","X","0","0","0","0","0"],
["2","0","0","0","0","0","0"],
["3","0","0","0","0","0","0"],
["4","0","0","0","0","0","0"],
["5","0","0","0","0","0","0"],
["6","0","0","0","0","0","0"],
["7","0","0","0","0","0","0"],
["8","0","0","X","0","0","X"]
])
An example it would be:
The occupied seats are at: (1,1), (8,3), (8,6)
Im looking for something like this or similar that works with strings and in a 2d array:
def findRow(a, n, m, k):
#a is the 2d array
#n is the number of rows
#m is the number of columns
#k is the "X"
l = 0
r = n - 1
mid = 0
while (l <= r) :
mid = int((l + r) / 2)
# we'll check the left and
# right most elements
# of the row here itself
# for efficiency
if(k == a[mid][0]): #checking leftmost element
print("Found at (" , mid , ",", "0)", sep = "")
return
if(k == a[mid][m - 1]): # checking rightmost element
t = m - 1
print("Found at (" , mid , ",", t , ")", sep = "")
return
if(k > a[mid][0] and k < a[mid][m - 1]): # this means the element
# must be within this row
binarySearch(a, n, m, k, mid) # we'll apply binary
# search on this row
return
if (k < a[mid][0]):
r = mid - 1
if (k > a[mid][m - 1]):
l = mid + 1
def binarySearch(a, n, m, k, x): #x is the row number
# now we simply have to apply binary search as we
# did in a 1-D array, for the elements in row
# number
# x
l = 0
r = m - 1
mid = 0
while (l <= r):
mid = int((l + r) / 2)
if (a[x][mid] == k):
print("Found at (" , x , ",", mid , ")", sep = "")
return
if (a[x][mid] > k):
r = mid - 1
if (a[x][mid] < k):
l = mid + 1
print("Element not found")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
