% Assignment 4 a b
% Takes in a positive integer n, and generates
% a sample of a group of random permutations 
% for a vector of size n. From this sample the events
% in which an element did not move in the random
% permutation, and calculate an approximation for
% the probability of an element not moving.

function val = JKO_01_04(n)

% initialize the count of positive events to zero
count(1:1000) = 0;

% generate 1000 samples
for k=1:1000;
    
    % generate a random permutation
    x = randperm(n);
    
    % Find out how many elements did not move in the
    % permutation and store the value to count(k).

    % (We choose a constant permutation to match against.
    % Due to symmetry it doesnt matter which constant
    % permutation is chosen. The previous permutation, or
    % a any fixed permutation. The permutation of choice
    % here is 1, 2, 3, 4, .. n)
    
    count(k) = sum(x(1:n) == (1:n)); % increment sum of non-moving elements.
end

% visualize amounts of non-moving elements.
hist(count, max(count));

% return an approximation of probability of not moving.
val = sum(count) / 1000;
