1

Тема: Виведення результату в textBox c++

Ще раз доброго вечора. Є код вирішення задачі комівояджера мурашиним алгоритмом. Підключивши його до засобів Windows Forms я зіткнувся з тим - що виводить не вірне рішення.
Порівнявши виведення в консолі і у формі - відразу зрозуміло що саме не так.
Можливо я десь не вірно оголошую передачу введених даних?

#pragma once
#include"inf.h"
#include <stdlib.h>
#include <iostream>
#include <malloc.h>
namespace AntColonyAlgorythm {        
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

#define ALPHA    1
#define BETTA    3
#define T_MAX    100
#define M        20
#define Q        100
#define RHO        0.5

    /// <summary>
    /// </summary>
        struct WAY_TYPE {
    int itabu;
    double length;
    int *tabu;
};

    public ref class data : public System::Windows::Forms::Form
    {
        inf ^ F2;
    public:
        data(void)
        {
            InitializeComponent();
        }
    protected:
        /// <summary>
        /// </summary>
        ~data()
        {
            if (components)
            {
                delete components;
            }
        }
    protected: 
    private: System::Windows::Forms::Label^  label5;
    private: System::Windows::Forms::Button^  button4;
    private: System::Windows::Forms::Button^  button3;
    private: System::Windows::Forms::TextBox^  textBox6;
    private: System::Windows::Forms::Label^  label6;
    private: System::Windows::Forms::TextBox^  textBox5;
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::TextBox^  b;
    private: System::Windows::Forms::TextBox^  array;
    private: System::Windows::Forms::Label^  label4;
    private: System::Windows::Forms::Label^  label3;
    private: System::Windows::Forms::TextBox^  a;
    private: System::Windows::Forms::TextBox^  n;
    private: System::Windows::Forms::Button^  button2;
    private: System::Windows::Forms::Label^  label1;
    private:
        /// <summary>
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// </summary>
        void InitializeComponent(void)
        {
            System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(data::typeid));
            this->button4 = (gcnew System::Windows::Forms::Button());
            this->button3 = (gcnew System::Windows::Forms::Button());
            this->textBox6 = (gcnew System::Windows::Forms::TextBox());
            this->label6 = (gcnew System::Windows::Forms::Label());
            this->textBox5 = (gcnew System::Windows::Forms::TextBox());
            this->label5 = (gcnew System::Windows::Forms::Label());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->b = (gcnew System::Windows::Forms::TextBox());
            this->array = (gcnew System::Windows::Forms::TextBox());
            this->label4 = (gcnew System::Windows::Forms::Label());
            this->label3 = (gcnew System::Windows::Forms::Label());
            this->a = (gcnew System::Windows::Forms::TextBox());
            this->n = (gcnew System::Windows::Forms::TextBox());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->SuspendLayout();
            // 
            // button4
            // 
            this->button4->Location = System::Drawing::Point(12, 396);
            this->button4->Name = L"button4";
            this->button4->Size = System::Drawing::Size(827, 40);
            this->button4->TabIndex = 5;
            this->button4->Text = L"Вихід";
            this->button4->UseVisualStyleBackColor = true;
            this->button4->Click += gcnew System::EventHandler(this, &data::button4_Click);
            // 
            // button3
            // 
            this->button3->Location = System::Drawing::Point(418, 350);
            this->button3->Name = L"button3";
            this->button3->Size = System::Drawing::Size(421, 40);
            this->button3->TabIndex = 4;
            this->button3->Text = L"Про програму";
            this->button3->UseVisualStyleBackColor = true;
            this->button3->Click += gcnew System::EventHandler(this, &data::button3_Click);
            // 
            // textBox6
            // 
            this->textBox6->Location = System::Drawing::Point(584, 52);
            this->textBox6->Multiline = true;
            this->textBox6->Name = L"textBox6";
            this->textBox6->Size = System::Drawing::Size(255, 193);
            this->textBox6->TabIndex = 3;
            // 
            // label6
            // 
            this->label6->AutoSize = true;
            this->label6->Location = System::Drawing::Point(469, 59);
            this->label6->Name = L"label6";
            this->label6->Size = System::Drawing::Size(90, 13);
            this->label6->TabIndex = 2;
            this->label6->Text = L"Довжина шляху:";
            // 
            // textBox5
            // 
            this->textBox5->Location = System::Drawing::Point(584, 12);
            this->textBox5->Name = L"textBox5";
            this->textBox5->Size = System::Drawing::Size(255, 20);
            this->textBox5->TabIndex = 1;
            // 
            // label5
            // 
            this->label5->AutoSize = true;
            this->label5->Location = System::Drawing::Point(469, 15);
            this->label5->Name = L"label5";
            this->label5->Size = System::Drawing::Size(36, 13);
            this->label5->TabIndex = 0;
            this->label5->Text = L"Шлях:";
            // 
            // label2
            // 
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(9, 228);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(177, 13);
            this->label2->TabIndex = 10;
            this->label2->Text = L"Введіть початкову вершину від 1 :";
            this->label2->TextAlign = System::Drawing::ContentAlignment::TopCenter;
            // 
            // b
            // 
            this->b->Location = System::Drawing::Point(232, 225);
            this->b->Name = L"b";
            this->b->Size = System::Drawing::Size(166, 20);
            this->b->TabIndex = 11;
            // 
            // array
            // 
            this->array->Location = System::Drawing::Point(15, 75);
            this->array->Multiline = true;
            this->array->Name = L"array";
            this->array->Size = System::Drawing::Size(383, 134);
            this->array->TabIndex = 9;
            // 
            // label4
            // 
            this->label4->AutoSize = true;
            this->label4->Location = System::Drawing::Point(109, 59);
            this->label4->Name = L"label4";
            this->label4->Size = System::Drawing::Size(145, 13);
            this->label4->TabIndex = 8;
            this->label4->Text = L"Введіть матрицю відстаней";
            this->label4->TextAlign = System::Drawing::ContentAlignment::TopCenter;
            // 
            // label3
            // 
            this->label3->AutoSize = true;
            this->label3->Location = System::Drawing::Point(9, 254);
            this->label3->Name = L"label3";
            this->label3->Size = System::Drawing::Size(137, 13);
            this->label3->TabIndex = 12;
            this->label3->Text = L"Введіть кінцеву вершину :";
            // 
            // a
            // 
            this->a->Location = System::Drawing::Point(232, 251);
            this->a->Name = L"a";
            this->a->Size = System::Drawing::Size(166, 20);
            this->a->TabIndex = 13;
            // 
            // n
            // 
            this->n->Location = System::Drawing::Point(235, 12);
            this->n->Name = L"n";
            this->n->Size = System::Drawing::Size(166, 20);
            this->n->TabIndex = 3;
            // 
            // button2
            // 
            this->button2->Location = System::Drawing::Point(12, 350);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(391, 40);
            this->button2->TabIndex = 1;
            this->button2->Text = L"Підтвердити";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &data::button2_Click);
            // 
            // label1
            // 
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(12, 15);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(217, 13);
            this->label1->TabIndex = 2;
            this->label1->Text = L"Введіть кількість вершин від [ 3 ] до [ 30 ]:";
            this->label1->TextAlign = System::Drawing::ContentAlignment::TopCenter;
            // 
            // data
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->AutoScroll = true;
            this->AutoSize = true;
            this->BackColor = System::Drawing::SystemColors::ButtonFace;
            this->ClientSize = System::Drawing::Size(851, 448);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->button4);
            this->Controls->Add(this->a);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->label3);
            this->Controls->Add(this->textBox6);
            this->Controls->Add(this->n);
            this->Controls->Add(this->button3);
            this->Controls->Add(this->textBox5);
            this->Controls->Add(this->label6);
            this->Controls->Add(this->label4);
            this->Controls->Add(this->label5);
            this->Controls->Add(this->array);
            this->Controls->Add(this->b);
            this->Controls->Add(this->label2);
            this->Icon = (cli::safe_cast<System::Drawing::Icon^  >(resources->GetObject(L"$this.Icon")));
            this->MaximizeBox = false;
            this->Name = L"data";
            this->Text = L"data";
            this->Load += gcnew System::EventHandler(this, &data::data_Load);
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: void typing(int N, double **D) {
                 for (int i = 0; i < N; i++) {
                     for (int j = 0; j < N; j++){
                         double k = System::Convert::ToDouble(array->Text);
                         D[i][j] = k;}
                 }
             }

private: double probability (int to, WAY_TYPE ant, double **pheromone, double **distance, int vertex) {
    for (int i=0; i<ant.itabu; ++i) if (to == ant.tabu[i]) return 0;

    double sum = 0.0;
    int from = ant.tabu[ant.itabu-1];
    for (int j=0; j<vertex; ++j) {
        int flag = 1;
        for (int i=0; i<ant.itabu; ++i) if (j == ant.tabu[i]) flag = 0;
        if (flag) sum += pow (pheromone[from][j], ALPHA) * pow (distance[from][j], BETTA);
    }
    return pow (pheromone[from][to], ALPHA) * pow (distance[from][to], BETTA) / sum;
}

private: WAY_TYPE AntColonyOptimization (int vertex, double **distance0, int start, int finish) {
    WAY_TYPE way;
    way.itabu = 0;
    way.length = -1;
    way.tabu = (int *) malloc (sizeof (int) * vertex);
    double **distance = NULL, **pheromone = NULL;
    distance = (double **) malloc (sizeof (double *) * vertex);
    pheromone = (double **) malloc (sizeof (double *) * vertex);
    for (int i=0; i<vertex; ++i) {
        distance[i] = (double *) malloc (sizeof (double) * vertex);
        pheromone[i] = (double *) malloc (sizeof (double) * vertex);
        for (int j=0; j<vertex; ++j) {
            pheromone[i][j] = 1.0 / vertex;
            if (i != j) distance[i][j] = 1.0 / distance0[i][j];
        }
    }
    WAY_TYPE ants[M];
    for (int k=0; k<M; ++k) {
        ants[k].itabu = 0;
        ants[k].length = 0.0;
        ants[k].tabu = (int *) malloc (sizeof (int) * vertex);
        ants[k].tabu[ants[k].itabu++] = start;
    }

    for (int t=0; t<T_MAX; ++t) {
        for (int k=0; k<M; ++k) {
            do {
                int j_max = -1;
                double p_max = 0.0;
                for (int j=0; j<vertex; ++j) {
                    if (ants[k].tabu[ants[k].itabu-1] != j) {
                        double p = probability (j, ants[k], pheromone, distance, vertex);
                        if (p && p >= p_max) {
                            p_max = p;
                            j_max = j;
                        }
                    }
                }
                ants[k].length += distance0[ants[k].tabu[ants[k].itabu-1]][j_max];
                ants[k].tabu[ants[k].itabu++] = j_max;
            } while (ants[k].tabu[ants[k].itabu-1] != finish);
            for (int i=0; i<ants[k].itabu-1; ++i) {
                int from = ants[k].tabu[i % ants[k].itabu];
                int to = ants[k].tabu[(i+1) % ants[k].itabu];
                pheromone[from][to] += Q / ants[k].length;
                pheromone[to][from] = pheromone[from][to];
            }
            if (ants[k].length < way.length || way.length < 0) {
                way.itabu = ants[k].itabu;
                way.length = ants[k].length;
                for (int i = 0; i < way.itabu; ++i) way.tabu[i] = ants[k].tabu[i];
            }
            ants[k].itabu = 1;
            ants[k].length = 0.0;
        }
        for (int i=0; i<vertex; ++i)
            for (int j=0; j<vertex; ++j)
                if (i != j) pheromone[i][j] *= (1 - RHO);
    }
    return way;
}

private: System::Void data_Load(System::Object^  sender, System::EventArgs^  e) {
         }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
                int N = System::Convert::ToInt32(n->Text);
                double **D = new double *[N];
                for (int i = 0; i < N; i++) {
                    D[i] = new double[N];
                }
                int A = System::Convert::ToInt32(a->Text);
                int B = System::Convert::ToInt32(b->Text);
                WAY_TYPE way = AntColonyOptimization (N, D, --A, --B);
                textBox5->Text = System::Convert::ToString(way.length);
         }
private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
                    F2 = gcnew inf();
                F2->Show();
         }
private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e) {
                Application::Exit();                
         }
};
}
Post's attachments

1.PNG 32.66 kb, 156 downloads since 2016-11-26 

2

Re: Виведення результату в textBox c++

Дуже багато коду, я в тому тексбокс1 лейбл 2 не можу розібратись. Я можу вам порадити якомога більше відділити бізнес логіку (ваш алгоритм) від юаю, точніше навіть від 2вох (від консольного і від вінформс) Тобто щоб у вас був клас по типу.

AntColonyAlgorythm.GetResult(int input1, double input2, array input3)

А уже в юаях збираєте всі необхідні дані і передаєте в той метод. Так вам буде простіше знайти помилку я думаю.

3

Re: Виведення результату в textBox c++

truesupport написав:

Дуже багато коду, я в тому тексбокс1 лейбл 2 не можу розібратись. Я можу вам порадити якомога більше відділити бізнес логіку (ваш алгоритм) від юаю, точніше навіть від 2вох (від консольного і від вінформс) Тобто щоб у вас був клас по типу.

AntColonyAlgorythm.GetResult(int input1, double input2, array input3)

А уже в юаях збираєте всі необхідні дані і передаєте в той метод. Так вам буде простіше знайти помилку я думаю.

тобто винести в окремий .h файл?

4

Re: Виведення результату в textBox c++

Ідея в тому щоб витягнути кусок логіки яка відповідає за розрахунок результату в консольній програмі в якусь окрему сутність метод клас або ще щось такого роду наприклад

namespace Algorythm
{
    struct WAY_TYPE {
        int itabu;
        double length;
        int *tabu;
    };

    public class AntColonyAlgorythm
    {
    public:
        static WAY_TYPE CalculateResult(int vertex, double **distance0, int start, int finish)
        {
            // do something here
            WAY_TYPE type;
            return type;
        }
    };
}

і перевірити чи той кусок коду правильно працює, якщо працює ви з легкістю цей клас зможете перенети і в вашу вінформс аплікацію. Ви вже будете точно знати що у вас алгоритм працює бо ви перевірили його на консольній програмі і вже будете шукати свою помилку в обробленні користувацьких даних.

Тобто у вас в аплікаціях (консольній і формс) буде така логіка.
1. Отримати дані від користувача
2. Передати дані у метод Algorythm::AntColonyAlgorythm::CalculateResult
3 Отримати результат і показати його користувачу

5

Re: Виведення результату в textBox c++

truesupport написав:

Ідея в тому щоб витягнути кусок логіки яка відповідає за розрахунок результату в консольній програмі в якусь окрему сутність метод клас або ще щось такого роду наприклад

namespace Algorythm
{
    struct WAY_TYPE {
        int itabu;
        double length;
        int *tabu;
    };

    public class AntColonyAlgorythm
    {
    public:
        static WAY_TYPE CalculateResult(int vertex, double **distance0, int start, int finish)
        {
            // do something here
            WAY_TYPE type;
            return type;
        }
    };
}

і перевірити чи той кусок коду правильно працює, якщо працює ви з легкістю цей клас зможете перенети і в вашу вінформс аплікацію. Ви вже будете точно знати що у вас алгоритм працює бо ви перевірили його на консольній програмі і вже будете шукати свою помилку в обробленні користувацьких даних.

Тобто у вас в аплікаціях (консольній і формс) буде така логіка.
1. Отримати дані від користувача
2. Передати дані у метод Algorythm::AntColonyAlgorythm::CalculateResult
3 Отримати результат і показати його користувачу

Але ж я це вже робив, без форм - виведення працює як слід. Створивши форму, я перевірив правильність ініціалізації введених даних. Я по черзі виводив дані без виконання обчислень. Все ініціалізується і передається між textBoх - ами нормально. Значить - я не правильно передаю введені значення в алгоритм обчислення - тобто отут:

    WAY_TYPE way = AntColonyOptimization (D, N, --A, --B);

я не вірно передаю введені значення.