Number of cycles of a permutation
J, 4 bytes
#@C.
This assumes that the permutation is 0-based. It uses the builtin C.
which given a list representing a direct permutation outputs a list of cycles. Then #
composed @
on that returns the number of cycles in that list.
Try it here.
JavaScript, 99 98 bytes
This solution assumes the array and its values are zero-indexed (e.g. [2, 1, 0]
).
f=a=>{h={},i=c=0;while(i<a.length){s=i;while(!h[i]){h[i]=1;i=a[i]}c++;i=s;while(h[++i]);}return c}
Explanation
// assumes the array is valid and zero-indexed
var findCycles = (array) => {
var hash = {}; // remembers visited nodes
var index = 0; // current node
var count = 0; // number of cycles
var start; // starting node of cycle
// loop until all nodes visited
while(index < array.length) {
start = index; // cache starting node
// loop until found previously visited node
while(!hash[index]) {
hash[index] = 1; // mark node as visited
index = array[index]; // get next node
}
count++; // increment number of cycles
index = start + 1; // assume next node is right after
// loop until found unvisited node
while(hash[index]) {
index++; // get next node
}
}
return count; // return number of cycles
};
Python, 77 69 67 bytes
f=lambda p,i=1:i and0 **p[i-1]+f(p[:i-1]+[0]+p[i:],p[i-1]or max(p))