# Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification

I want to use Minimize where the variables to minimize are indices pointing into an array.

Here a MWE that hopefully shows what my problem is.

vars = u@# & /@ Range;
cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1,
3 - 1}],
1 <= # <= 3 & /@ vars };
vec1 = {1, 2, 3}; vec2 = {1, 2, 3};
Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]),
cons}, vars, Integers]


The error I get:

Part::pkspec1: The expression u cannot be used as a part specification. >>


Ok,

it seems that one can get around Mathematica trying to evaluate vec2[[u]] too early by using the function Indexed[vec2,u].

The working MWE would then look like the following:

vars = u@# & /@ Range;
cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1,
3 - 1}],
1 <= # <= 3 & /@ vars};
vec1 = {1, 2, 3}; vec2 = {1, 2, 3};
NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@
Range[1, 3]), cons}, vars, Integers ]


which yields correctly:

{0., {u -> 1, u -> 2, u -> 3}}