问题来自群友:
94 77 67 72
8 95 61 87
24 36 47 69
100 38 43 57
这样一个矩阵
重新排列,使每个元素与相邻(上下左右)的元素差的绝对值求和,不重复计算这个差
问一种算法让最后的总和最小
我的算法
当时没多想,用第一想法解决了,还意外的比别人快。。。
准备
org = {94, 77, 67, 72, 8, 95, 61, 87, 24, 36, 47, 69, 100, 38, 43, 57};
index = Range@16~Partition~4;
sum[l_] =
Quiet@With[{f = Part},
Total[Abs[f[l, #] - f[l, # + 1]] & /@
Flatten@index[[;; , ;; 3]]] +
Total[Abs[f[l, #] - f[l, # + 4]] & /@ Flatten@index[[;; 3]]]];
rep[l_] := Permute[l, Cycles@{RandomSample[Range@16, 2]}]
求解
group = rep /@ ConstantArray[org, 100];
Table[group = SortBy[group, sum][[;; 100]];
group = group~Join~(rep /@ RandomChoice[group, 100]);
sum@group[[1]], {100}]
最后得到多种解,最优值为341