例如,如果存在N = 4 1,则我想填充3×3矩阵,其中每个排列对称,每个排列对应于上下三角形中的2 1 1。我会得到[010,101,010],[001,001,110]和[011,100,100]。
答案 0 :(得分:0)
这个怎么样?
void matrixFill(int[,] m, int n)
{
m[n-1, n-1] = 0;
if (n > 1)
{
for (int i = 0; i < n-1; i++)
{
m[i, n-1] = 1;
m[n-1, i] = 1;
}
matrixFill(m , n-1);
}
}
每个递归级别设置一个对角线元素,剩余的行/列在此元素中相交。
没有明确迭代的第二次尝试:
// 1st call matrixFill2(m , n-1, n-1)
void matrixFill2(int[,] m, int x, int y)
{
if ((x >= 0) && (y >= 0))
{
m[x, y] = (x == y) ? 0 : 1;
matrixFill2(m, x-1, y);
matrixFill2(m, x, y-1);
matrixFill2(m, x-1, y-1);
}
}
此版本将多次设置矩阵单元格。行/列索引保持不变或减少。因此,递归最终会终止。
答案 1 :(得分:0)
#Figured it out
from __future__ import print_function
import itertools
import numpy as np
N = 4
S = N*(N-1)/2
E = 3
which = np.array(list(itertools.combinations(range(S), E)))
grid = np.zeros((len(which), S), dtype="int8")
grid[np.arange(len(which))[None].T, which] = 1
for perm in range(len(grid)):
grid_num = perm
A = np.zeros((N,N))
counter = 0
for i in range(N):
for j in range(i):
A[i][j] = grid[grid_num][counter]
A[j][i] = grid[grid_num][counter]
counter = counter + 1
print()
print(A)