%% SL 7
clear; clc;
N = 1000;
a = primes(N);
b = 2:2:N; 
c = setdiff(1:N, b);
v = intersect(a, b+c)
length(v)

%% SL 8
w = setdiff(union(b, c), a)
sum(not(mod(w, 3)))

%% SL 10
% script depicts number of integers from 1 to 1000 in 
% dependence on division remainders
M = zeros(20,1);
N = 1000;
a = primes(N);
b = 2:2:N;
c = setdiff(1:N, b);
w = setdiff(union(b, c), a);

for iDiv = 1:length(M)
    M(iDiv) = sum(not(mod(w, iDiv)));
end

figure;
bar(M);

%% SL 11
L = 20e3; % length of path
deviation = 5e-6; % standard deviation
N = 1e6; % number of trials
% random distances
distances = L + randn(1, N)*deviation; 

sum(ismember(distances, L))
length(unique(distances))
% for comparison
length(unique(randn(1, 1e6)))

%% SL 15
% bubble sort algorithm
N = 30;
R = 10*rand(1, N);
for startMove = 1:N-1
    for pos = 1:N-startMove
        if R(pos) > R(pos+1)
            R([pos, pos+1]) = R([pos+1, pos]);
        end
        figure(1);
        plot(R,'*','LineWidth',2);
        pause(0.01);
    end
end
issorted(R)

%% SL 16
% bubble sort algorithm
clear; close all; clc;
R = 10*rand(1,20);
figure(1);
for startMove = (length(R)-1):-1:1
   for pos = startMove:(length(R)-1)
      if R(pos) > R(pos+1)
         R([pos, pos+1]) = [R(pos+1) R(pos)];
         bar(R);
         hold on;
         bar(pos+1, R(pos+1), 'g');
         hold off;
         pause(0.01);
      else
         bar(R);
      end
   end
end
issorted(R)

%% SL 17
% shaker sort algorithm
clear; close all; clc;
R = 10*rand(1, 30);
figure(1);
for startMove = (length(R)-1):-1:length(R)/2
   for pos = startMove:-1:(length(R)-startMove)
      if R(pos) > R(pos+1)
         R([pos, pos+1]) = [R(pos+1) R(pos)];
      end
   end
   for pos = (length(R)-startMove+1):startMove
      if R(pos) > R(pos+1)
         R([pos+1, pos]) = [R(pos), R(pos+1)];
      end
   end
   plot(R, '*', 'LineWidth', 2);
   pause(0.15);
end

%% SL 19
v  = reshape(magic(4)', [1 numel(magic(4))]);
v  = sort(v, 'descend');
v1 = mod(v, 3) == 0 & v > 10
v(v1)
find(v1)

%% SL 20
w = (8:-1:2)'*(1:1/2:4).*magic(7)
w50 = w(w < 50);
w50(end-2:end)
% w50 = [20; 12; 31.5]
[rw, cl] = find(w < 50, 3, 'last');

%% SL 25
dta = [1 -110; 1 -140; 2 -22; 3 -2; 2 -34; 1 -1300; 2 -15; 1 -730; 3 24];
K   = [1 26 25];

M   = accumarray(dta(:, 1), dta(:, 2))
acc =  K*M  % = -3576
% acc =  dot(K, M)
% acc =  sum(K.*M.')
% acc =  sum(K.'.*M)


