So while solving a programming problem, I stumbled upon this particular problem which turned out to be very interesting and I was able to find a elegant approch to it.
So, let us take a look at the problem which I have simplified for the readers:
We are given two integers N and X in the input, and following this input, we are given another N inputs of arrays having two elements.
For ex: Suppose N = 4, X = 28. Now following this input, we are given 4 arrays having two elements each
say: [4,5], [6,8], [10, 3], [3, 8]
Now our task is to choose 1 element from each array such that sum of all those elements equal X
If our task can be completed, we output "Yes", else "No"
In the above example, we can choose 4 from the first array, 6 from the second, 10 from the third, and 8 from the fourth.
Summing all these elements, we get \(4+6+10+8 = 28\).
Hence we output "Yes".
So initially I thought to run some for-loops and make a large array having one element from each array. But I was not able to think further and so I dropped this idea.
Then the idea of binary sequences struck my head.
So imagine all the numbers in binary from 0 to \(2^4 - 1\)
They are: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
I thought of splitting all these numbers into seperate digits, which would give me indexes of all possible combination of elements.
For ex: \(0000\) can be split into \(0,0,0,0\) digits, and now we have one possible combination of elements.
We can take 0th element from the first array, 0th from the second, 0th from the third, and 0th from the fourth.
Now we can find the sum of these elements, which would turn out to be 23.
Let us take the next sequence, after \(0000\), we have \(0001\). Which can be split into digits as \(0,0,0,1\)
So we can take the 0th element from first array, 0th from the second, 0th from the third, 1st element from the fourth.
Summing these elements, we get \(4 + 6 + 10 + 8\) which equals \(28\)
Hence the output is "Yes"
Here is the code I wrote:
N, X = list(map(int, input().split()))
arrs = []
for j in range(N):
arrs.append(list(map(int, input().split())))
total_products = []
for i in range(2**N):
_sum = 0
for l in range(len(arrs)):
_sum += arrs[l][int(list('0' * (N - len(bin(i)[2::])) + bin(i)[2::])[l])]
if(_sum > X):
break
if(_sum == X):
print("Yes")
exit();
print("No")
Veenomoose
Elegant indeed