123456789怎樣運算等於1? - abccsss 的回答
假定每個數字只能出現一次。
回複內容:
Mathematica代碼
較簡潔
Det/@N@Range@9~Permutations~{9}~ArrayReshape~{9!,3,3}//Max
以上用Matlab暴力破解(枚舉種情形),暫未輸出行列式相同的其他情形,貌似基本秒出。
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}];list = Permutations[Range[9], {9}];
matrix = Partition[#, 3] & /@ list;
answer = Det /@ matrix;
m = Max[answer];
pos = Flatten[Position[answer, m]];
matrix[[#]] & /@ pos貼個毫無技術含量暴力程度max的python版。。。
import itertoolsimport timedef max_matrix():begin = time.time()elements = [1, 2, 3, 4, 5, 6, 7, 8, 9]maxdet = 0maxmat = []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 = detmaxmat = []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的答案重排一下可得
9 4 2
3 8 6
5 1 7
很容易看出思路了。
1.所有數按大小在斜率為-1的對角線上依次排開。(即:987在一條對角線,654在一條,321在一條)很容易看出這是讓正向數值最大的方法。
2.對於反向的對角線,排除主對角線之外的任意兩個數之和相等,且乘積越大的,相應的主對角線元素越小。(也就是讓三個乘積的最大值最小,然後最大的結果再和最小的數相配這樣)
但是以上方法僅限於1~9的3x3矩陣,對於其它的矩陣不一定適用。
因為顯然這種方法要求正向和負向都只有對角線(或平行於對角線),但是4x4的行列式就開始有拐彎了。。。
然後,我感覺還有三個漏洞,一是貪進法不一定保證正向最大,也不一定保證反向最小,更不一定保證正反向之差最大。(不一定都是漏洞,可能有的是恒成立的)
但是我感覺對3x3的非負矩陣來說,貪心在多數情況下是可以拿到最大值的。
PS:試了很多組數,都是這個解,然後又試了一組[1 2 3 4 5 6 7 8 100],顯然答案發生了變化,因為100的權值比8和7大太多,所以負向的時候直接就把2和1給了100。那麼這也就證明了貪進法確實有時候得不到最大值。前面已經有了python,c和MMA的代碼了,我來一發matlab的吧
p=perms(1:9);[n,~]=size(p);z=zeros(n,1);for i=1:n z(i)=det(reshape(p(i,:),3,3));endmax(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,就我來吧
直接9!個結果存下來剛正面,0最佳化
Det[Partition[#, 3]] & /@ Permutations[Range[9]] // Max412