<script>
function
count(a,c)
{
let co = 0;
for
(let i = 0; i < a.length; i++)
if
(a[i] == c)
co++;
return
co;
}
function
finalNumber(n,k,a)
{
let modtemp;
let co;
let temp =
new
Array(a.length);
let ans = [Number.MAX_VALUE,
""
];
for
(let i = 0; i < 10; i++)
{
temp = a.split(
""
);
modtemp = 0;
co = count(a, String.fromCharCode(i + '0
'.charCodeAt(0)));
// '
j
' manages the difference '
i
' and '
j
'
for (let j = 1; j < 10; j++)
{
// For the elements ahead of '
i
' index
if (i + j < 10)
{
// Checks all elements with difference '
j
'
// and replaces them with '
i
'
for (let p = 0; p < n; p++)
{
// Break if count is achieved
if (co >= k)
break;
if (i + '
0
'.charCodeAt(0) == temp[p].charCodeAt(0) - j)
{
// Replaces all elements with difference
// '
j
' and with '
i
'
temp[p] = String.fromCharCode(i + '
0
'.charCodeAt(0));
modtemp += j;
co++;
}
}
}
// For the elements before '
i
' index
if (i - j >= 0)
{
for (let p = n - 1; p >= 0; p--)
{
if (co >= k)
break;
if (i + '
0
'.charCodeAt(0) == temp[p].charCodeAt(0) + j)
{
temp[p] = String.fromCharCode(i + '
0'.charCodeAt(0));
modtemp += j;
co++;
}
}
}
}
if
(ans[0] > modtemp)
ans = [modtemp, temp.join(
""
)];
}
document.write( ans[0] +
"<br>"
+ ans[1] +
"<br>"
);
return
-1;
}
let n = 5, k = 4;
let a =
"21122"
;
finalNumber(n, k, a);
</script>