0

I have a set of two arrays of numbers, and I need to find 3 indices of these arrays, such that 2 inequalities using the arrays are satisfied. We can assume the value of one index to simplify the problem to 2 inequalities, 2 unknown indices.

However, I am having a very hard time thinking about how to solve this. For explicit detail, I have the equations:

array2[index_a] = array1[index_b] + array1[index_a]
array1[index_c] = array2[index_b] + array2[index_c]

where we can assume that index_a is a known parameter, and I need to solve for index_b and index_c.

I have thought about using the linear algebra solver, but I'm not sure how to template it as I don't really have functions to solve, just index values.

Any advice would be greatly appreciated.

D. Brown
  • 101
  • If this is a numpy, you can combine the inequalities using `&` (which means logical AND), but we need some sample and expected output from you to know if this is what you are trying to look for –  Jun 15 '22 at 04:16

1 Answers1

0

If the arrays are large, so that N^2 elements would not fit in the memory.

Then you could iterate one index and look for the other using numpy vectorized oeprations.

Generate an example

import numpy as np
M = 10
N = 1000
array1 = np.random.randint(-M, M, N);
array2 = np.random.randint(-M, M, N);
index_a = 24

Solving using O(N) memory


def find_index2a(array1, array2, index_a):
  for index_b in np.nonzero(array2[index_a] == array1 + array1[index_a])[0]:
    for index_c in np.nonzero(array1 == array2[index_b] + array2)[0]:
      # this will generate the tuples (index_b, index_c) in lexicographic order
      yield index_b, index_c
index_b, index_c = next(find_index2a(array1, array2, index_a))
print((index_a, index_b, index_c))
print(f'{array2[index_a]} = {array1[index_b]} + {array1[index_a]}')
print(f'{array1[index_c]} = {array2[index_b]} + {array2[index_c]}')

Solving using O(N^2) memory

import numpy as np
def find_index2b(array1, array2, index_a):
  N = len(array1)
  assert N == len(array2)
  index_b, index_c = np.indices((N, N))
  return np.nonzero((array2[index_a] == array1[index_b] + array1[index_a]) &
                    (array1[index_c] == array2[index_b] + array2[index_c]))
index_b, index_c = find_index2b(array1, array2, index_a)
print((index_a, index_b, index_c))
print(f'{array2[index_a]} = {array1[index_b]} + {array1[index_a]}')
print(f'{array1[index_c]} = {array2[index_b]} + {array2[index_c]}')
Bob
  • 13,867
  • 1
  • 5
  • 27