I chanced upon this question and came up with the following algorithm, looking for criticisms and advice on how to improve my algorithm efficiency.
You are given 3 arguments:
A & B are integers within the range (0 to 100,000)
M is an array of integers within the range (0 to 2)
Return an output (as a string) that describes matrix M in the following format:
The first part of the string should contain a description of the upper row using only the
1
and0
characters and should add up to the integer AThe second part of the string should contain a description of the lowerrow using only the
1
and0
characters and should add up to the integer BThe sum of integers at K index of the output
(string1
,string2)
should be equal to M[K] so like:string1[K] + string2[K] == M[K]
So for example,
Given
A = 2, B = 2, M = [2, 0, 2, 0]
, your function should return a string like"1010, 1010"
Given
A = 3, B = 2, M = [2, 1, 1, 0, 1]
, your function should return"11001, 10100"
Given
A = 2, B = 3, M = [0, 0, 1, 1, 2]
, your function should return0
, because no matrix can be constructed that satisfies such conditions.
def convert(A, B, M):
if (A+B) != sum(M) or max(A, B) > len(M):
return 0
'''
logic:
set 2 arrays
if value in matrix = 2, array1 & array2 at index where 2 occurs
will be [1] and [1]
if value in matrix = 0, array1 & array2 at index where 0 occurs will
be [0] and [0]
Then, we only need to handle 1s in matrix...
same logic as above,
however,
we handle position of 1 by checking whether A > B or vice versa
'''
array1 = [""] * len(M)
array2 = [""] * len(M)
# first check for 2's and 0's:
for index, value in enumerate(M):
if value == 2:
array1[index] = 1
array2[index] = 1
A -= 1
B -= 1
elif value == 0:
array1[index] = 0
array2[index] = 0
# then check for 1's:
elif value == 1 and A>B:
array1[index] = 1
array2[index] = 0
A -= 1
elif value == 1 and A<=B:
array1[index] = 0
array2[index] = 1
B -= 1
array1 = ''.join(str(x) for x in array1)
array2 = ''.join(str(x) for x in array2)
return array1 + ', ' + array2