#include "RLS.h"

Result RLS::run() {
    MasterMind* pb = m_problem;
    clear_record();

    // Solution x : the parent
    int* s_x = pb->get_random_candidate();
    int v_x = pb->try_candidate(s_x);
    Candidate* x = new Candidate(s_x, v_x);

    // Solution y : the child
    int* s_y = pb->get_random_candidate();
    Candidate* y = new Candidate(s_y, 0);

    int nb_calls = 1;

//    std::cout << "BEFORE LOOP..." << std::endl;
    while(! pb->is_optimal(x->sol, x->value, m_objective)) {
//        std::cout << "ITERATION: " << x->value << std::endl;
//        pb->display_candidate(x->sol);
//        std::cout << std::endl;
        int r = 1;
        pb->copy_candidate(x->sol, y->sol);
        pb->modify_with_radius(y->sol, r);
        y->value = pb->try_candidate(y->sol);
//        pb->display_candidate(y->sol);
//        std::cout << "(" << y->value << ")" << std::endl;
        if(y->value >= x->value) {
            // Swap x and y
            Candidate* tmp = x;
            x = y;
            y = tmp;
        }
        nb_calls++;
        record(nb_calls, x->value);

        if(m_abortion_limit > 0 && nb_calls >= m_abortion_limit) {
            Result res(x->sol, x->value, nb_calls);
            delete[] y->sol;
            delete y;
            delete x;
            return res;
        }
    }

    Result res(x->sol, x->value, nb_calls);

    // Cleaning
    delete[] y->sol;
    delete y;
    delete x;

    return res;
}
