'How to create arrays with combinations between certain indexes of a fixed length and fixed sum
For example:
array = [4,3,2,0,0,0,0,0,0]
The 0th index should only have combinations with 3rd index and 6th index. The 1st index should only have combinations with 4th index and 7th index. The 2nd index should only have combinations with 5th index and 8th index. (sum should stay the same between these indexes). Then output should be:
[1,2,2,1,1,0,2,0,0]
[2,1,1,1,1,1,1,1,0]...
In both these combinations, sum between the respective indexes (listed above) remain the same.
Solution 1:[1]
Using the findPairs function resulting from the answer to your previous question:
from itertools import product
def findPairs(sum_value, len_value):
lst = range(sum_value + 1)
return [
pair
for pair in product(lst, repeat=len_value)
if sum(pair) == sum_value
]
import itertools
combinations = itertools.product(findPairs(array[0], 3), findPairs(array[1], 3), findPairs(array[2], 3))
result = [list(itertools.chain(*zip(p1, p2, p3))) for p1, p2, p3 in combinations]
print(result[0:10])
[[0, 0, 0, 0, 0, 0, 4, 3, 2], [0, 0, 0, 0, 0, 1, 4, 3, 1],
[0, 0, 0, 0, 0, 2, 4, 3, 0], [0, 0, 1, 0, 0, 0, 4, 3, 1],
[0, 0, 1, 0, 0, 1, 4, 3, 0], [0, 0, 2, 0, 0, 0, 4, 3, 0],
[0, 0, 0, 0, 1, 0, 4, 2, 2], [0, 0, 0, 0, 1, 1, 4, 2, 1],
[0, 0, 0, 0, 1, 2, 4, 2, 0], [0, 0, 1, 0, 1, 0, 4, 2, 1]]
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2246849 |
