I want to construct a function showNum(ar,k)
getting all the k-digit numbers from array ar
.
For example, showNum([1,2,3],2)
should return 12,13,21,23,31,32
andshowNum([1,2,3],1)
should return 1,2,3
.
My code works well with the case that k
is fix.
For instance, the case k
is 3.
My idea is to loop 3 times.
function showNum(a){
var ar = [];
var n = a.length;
for(i = 0; i <= n; i++){
for(j = 0; j <= n; j++){
for(k = 0; k <= n; k++){
if(a[i] != a[j] && a[i] != a[k] && a[k] != a[j]) ar.push(a[i]*100 + a[j]*10 + a[k]);
}
}
}
return ar;
}
But when k
is arbitrarily less than n
, I don't know how to loop.