在业主群里,有邻居问一道数学题,34567,填在圆圈里,使每条线上三个数的和相等?如下图所示:
要求是至少给出三对
这位邻居很是心急,一道也没做出来,对于程序员来讲,其实不难,借助于计算机很容易实现,于是用js简单地实现了(没有特别进行优化,层次有点深)。
var arr = [3, 4, 5, 6, 7]; var size = arr.length; var maxLength = 3; var t = Array(); var tmp = []; var i = 0; for (var a = 0; a < size; a++) { for (var b = 0; b < size; b++) { tmp = []; for (var d = 0; d < size; d++) { if (b != a && b != d && a != d) { tmp.push(arr[a]); tmp.push(arr[b]); tmp.push(arr[d]); if (tmp.length == maxLength) { t[i] = tmp; i++; tmp = []; } } } } } if (t.length > 0) { var tSize = t.length; for (var m = 0; m < tSize; m++) { for (var n = 0; n < tSize; n++) { if (m != n && t[m][1] == t[n][1]) { if (arrayEquesCount(t[m], t[n]) == 1) { if (t[m][0] + t[m][1] + t[m][2] == t[n][0] + t[n][1] + t[n][2]) { console.log(t[m] + "==" + t[n]); } } } } } } function arrayEquesCount(arr1, arr2) { var count = 0; var arr1Size = arr1.length; var arr2Size = arr2.length; for (var m = 0; m < arr1Size; m++) { for (var n = 0; n < arr2Size; n++) { if (arr1[m] == arr2[n]) { count++; } } } return count; }
最终答案不考虑位置关系,共有24组,如下图所示: