amolnayak311/algorithms-illuminated

Local Minima is probably not working right.

michaelmiscanuk opened this issue · 0 comments

Hi,

I tried to decrease in a matrix a value -1 - I made it -3, and result is giving me 9 as a local minima, which is surely not local minima:

import numpy as np

# Assumption is that the matrix has unique numbers
def localminima1(matrix):
    m = matrix.shape[1] // 2  # Num cols
    i_minval = np.argmin(matrix[:, m])  # Done in O(n)
    min_val = matrix[i_minval, m]
    # Comparison done in constant time, the recursive calls would be done log n times
    left_val = matrix[i_minval, m - 1] if m > 0 else float("inf")
    right_val = matrix[i_minval, m + 1] if m < matrix.shape[1] - 1 else float("inf")
    if min_val < left_val and min_val < right_val:
        return (m, i_minval)
    else:
        return (
            localminima1(matrix[:, 0:m])
            if left_val < min_val
            else localminima1(matrix[:, (m + 1) :])
        )

# fmt:off
array = np.matrix([
    [1, 2, 5, 4], 
    [0, -2, 9, 6], 
    [7, -3, 3, 10], 
    [11, 12, 13, 14]
])
# fmt:on
print("Input is\n", array)
ix = localminima1(array)
print("\nA local minima is at", ix, "with value", array[ix])

Result:

[[ 1 2 5 4]
[ 0 -2 9 6]
[ 7 -3 3 10]
[11 12 13 14]]

A local minima is at (1, 2) with value 9