时间:2021-07-01 10:21:17 帮助过:91人阅读
Det/@N@Range@9~Permutations~{9}~ArrayReshape~{9!,3,3}//Max
max_det = 0;
init_perm = reshape(1:9, [3, 3]);
all_perms = perms(1:9);
for i = 1:size(all_perms, 1)
matrix = all_perms(i, :);
matrix = reshape(matrix, [3, 3]);
det_value = det(matrix);
if det_value > max_det
max_det = det_value;
init_perm = matrix;
end
end
list = Permutations[Range[9], {9}];import itertools
import time
def max_matrix():
begin = time.time()
elements = [1, 2, 3, 4, 5, 6, 7, 8, 9]
maxdet = 0
maxmat = []
for i in itertools.permutations(elements, 9):
det = i[0] * i[4] * i[8] + i[1] * i[5] * i[6] + i[2] * i[3] * i[7] - i[2] * i[4] * i[6] - i[1] * i[3] * i[8] - i[0] * i[5] * i[7]
if(det > maxdet):
maxdet = det
maxmat = []
for j in range(0, 9):
maxmat.append(i[j])
print "|" + str(maxmat[0]) + " " + str(maxmat[1]) + " " + str(maxmat[2]) + "|"
print "|" + str(maxmat[3]) + " " + str(maxmat[4]) + " " + str(maxmat[5]) + "| = " + str(maxdet)
print "|" + str(maxmat[6]) + " " + str(maxmat[7]) + " " + str(maxmat[8]) + "|"
end = time.time()
print str(end - begin) + 's used.'
if __name__ == '__main__':
max_matrix()
题目应该改成1 2 3 ...n^2组成n阶行列式的最大值。并求最优解的时间复杂度才有意思。
C++:#include
#include
using namespace std;
int ans, a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int main() {
do
ans = max(ans, a[0] * (a[4] * a[8] - a[5] * a[7]) +
a[1] * (a[5] * a[6] - a[3] * a[8]) +
a[2] * (a[3] * a[7] - a[4] * a[6]));
while (next_permutation(a, a + 9));
printf("%d\n", ans);
}
把yellow的答案重排一下可得p=perms(1:9);
[n,~]=size(p);
z=zeros(n,1);
for i=1:n
z(i)=det(reshape(p(i,:),3,3));
end
max(z)
id=find(z==max(z));
for i=1:length(id)
disp(reshape(p(id(i),:),3,3));
end
对于三阶的穷举,可以不用det函数会比较简单:p = reshape(perms(1:9),'',3,3);
M = max(sum(prod(p,2),3)-sum(prod(p,3),2));
话题的语言还少个Mathematica,就我来吧Det[Partition[#, 3]] & /@ Permutations[Range[9]] // Max
412