matrix = [[true, false, false],
[false, true, false],
[false, false, false]]
the [1][2]and[2][1] both have 2 true's surrounding them. so the count for that element place is 2. The remaining places are 1, since they are surrounded by 1 element.
result = [[0 for x in range(len(matrix[0]))] for y in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
for x in [1,0,-1]:
for y in [1,0,-1]:
if 0<=i+x<len(matrix) and 0<=j+y<len(matrix[0]):
result[i][j]= matrix[i+x][j+y]
return result
This is the expected output
output= [[1, 2, 1],
[2, 1, 1],
[1, 1, 1]]
But i am getting the output as
[[true,true,false],
[true,true,false],
[false,false,true]]
The number of elements of a matrix = the number of rows multiplied by the number of columns. For example, if the number of rows is 3 and the number of columns is 4 in a matrix then the number of elements in it is 3 x 4 = 12.
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
Mark all elements using a hash table. Iterate in the array of numbers in the Z array, check if the number is present in the hash-table. Increase the count for every element present. Once all the elements are checked, print the count.
Java doesn't have the concept of a "count" of the used elements in an array. To get this, Java uses an ArrayList . The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big). To get the count, you use mylist.
Two issues. The first happens in your for loop. You don't want to count the current index and only want to sample it's neighbors, so you want to throw out cases where x == y == 0
. Do this by adding an if statement like if x == y == 0: continue
The second issue is that you're setting the value not incrementing it. This here: result[i][j]= matrix[i+x][j+y]
only sets the value to True
and doesn't increase it when further neighbors are detected. Instead add like: result[i][j] += matrix[i+x][j+y]
With both these fixes you get the correct output:
true = True
false = False
matrix = [[true, false, false],
[false, true, false],
[false, false, false]]
result = [[0 for x in range(len(matrix[0]))] for y in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
for x in [1,0,-1]:
for y in [1,0,-1]:
if x == y == 0: continue
if 0<=i+x<len(matrix) and 0<=j+y<len(matrix[0]):
result[i][j] += matrix[i+x][j+y]
for i in result:
print(i)
Output:
[1, 2, 1]
[2, 1, 1]
[1, 1, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With