clear all; close all;

n = 10;
p = 0.5;

Nexp = 100;
results = zeros(Nexp,1);

for exp = 1:Nexp
    fprintf('Experiment %03d...\n',exp);
    A = getRandomSignedGraph(n,p);

    Niter = 1e6;
    for iter = 1:Niter
        balanced = isGraphBalanced(A);
        if (balanced)
            break;
        end

        % I) Pick a triad at random
        triad_nodes = randsample(n, 3, false); % Sample without replacement
        triad_edges = [triad_nodes circshift(triad_nodes,-1)];

        % II) Check if triad is balanced. Use the fact that, in a balanced
        %       triangle, the product of the signs of the three edges is
        %       positive.
        triad_balanced = 1;
        for k = 1:3
            triad_balanced = triad_balanced * ...
                             A(triad_edges(k,1),triad_edges(k,2));
        end
        triad_balanced = triad_balanced > 0;

        % III) If the triad is not balanced, then choose one of the edges
        %       at random and flip its sign
        if (~triad_balanced)
            k = randi(3,1);
            A(triad_edges(k,1),triad_edges(k,2)) = ...
                -A(triad_edges(k,1),triad_edges(k,2));

            A(triad_edges(k,2),triad_edges(k,1)) = ...
                -A(triad_edges(k,2),triad_edges(k,1));
        end
    end
    
    results(exp) = balanced;
end