Checking all possible orders is a classical permutation task even if there might be a more efficient algorithm for this specific problem.
One optimization can be done by reducing the permutation to array length-1 since in circular orders e.g. 0,1,2,3,4 and 4,0,1,2,3 (and all further rotations) are the same. You can view the order from you own seat always starting at position 0.
(function ()
{
'use strict';
let popularity =
[
[ 0, 1, 1, 1, 1], // ← yes you like all your friends
[-1, 0, 1,-1, 0],
[-1, 1, 0, 1, 0],
[ 1, 1, 1, 0,-1],
[ 1, 0, 0,-1, 0],
];
function permutation(arr)
{
let
l = arr.length,
perms = []
;
if(l<2)
return [arr];
for(let i=0; i<l; i++)
{
let
cpy = Array.from(arr),
[perm] = cpy.splice(i, 1)
;
perms.push(...permutation(cpy).map(v => [perm, ...v]));
}
return perms;
}
let
keys = Array.from(popularity.keys()).slice(1),
permutations = permutation(keys),
rating = permutations.map(v =>
{
let
last = v.length -1,
// start with our own relationships to the left and right neighbour
// (each: we like him, he likes us)
rate =
popularity [0] [v[0]]
+ popularity [v[0]] [0]
+ popularity [0] [v[last]]
+ popularity [v[last]] [0]
;
for(let i = 0; i<last; i++)
rate += popularity[v[i]][v[i+1]] + popularity[v[i+1]][v[i]];
return [rate, [0, ...v]];
}
).sort( (v1, v2) => ( v1[0] === v2[0] ? 0 : (v1[0] > v2[0] ? -1 : 1)) );
console.log(rating);
})();
output:
[ [ 8, [ 0, 4, 1, 2, 3 ] ],
[ 8, [ 0, 3, 2, 1, 4 ] ],
[ 6, [ 0, 3, 1, 2, 4 ] ],
[ 6, [ 0, 4, 2, 1, 3 ] ],
[ 4, [ 0, 1, 4, 2, 3 ] ],
[ 4, [ 0, 1, 2, 3, 4 ] ],
[ 4, [ 0, 4, 1, 3, 2 ] ],
[ 4, [ 0, 1, 3, 2, 4 ] ],
[ 4, [ 0, 2, 3, 1, 4 ] ],
[ 4, [ 0, 3, 2, 4, 1 ] ],
[ 4, [ 0, 4, 2, 3, 1 ] ],
[ 4, [ 0, 4, 3, 2, 1 ] ],
[ 2, [ 0, 3, 4, 2, 1 ] ],
[ 2, [ 0, 3, 1, 4, 2 ] ],
[ 2, [ 0, 2, 4, 1, 3 ] ],
[ 2, [ 0, 4, 3, 1, 2 ] ],
[ 2, [ 0, 3, 4, 1, 2 ] ],
[ 2, [ 0, 1, 2, 4, 3 ] ],
[ 2, [ 0, 2, 1, 4, 3 ] ],
[ 2, [ 0, 2, 1, 3, 4 ] ],
[ 0, [ 0, 1, 4, 3, 2 ] ],
[ 0, [ 0, 2, 3, 4, 1 ] ],
[ -2, [ 0, 1, 3, 4, 2 ] ],
[ -2, [ 0, 2, 4, 3, 1 ] ] ]
As we can see, there still are reversed permutations combined with yourself (0) having the same rating of course. Eleminating mirrored orders, i.e. reversed permutations, would be another optimization.
I did this for demonstration in single steps to have a more readable code facing single problems step by step. You could refactor the rating calculation directly into the permutation algorithm.
Properly calculating the time complexity does not seem to be that easy. Please read the discussion in the comments below.