Exemplo n.º 1
0
        static void TestSimplex(double[,] table, double[] result)
        {
            Console.WriteLine("\nВход:");
            for (int i = 0; i < table.GetLength(0); i++)
            {
                for (int j = 0; j < table.GetLength(1); j++)
                {
                    Console.Write(String.Format("{0, -6} ", Math.Round(table[i, j], 3)));
                }
                Console.WriteLine();
            }

            double[,] table_result;
            Simplex S = new Simplex(table);

            table_result = S.Calculate(result);

            Console.WriteLine("\nРешенная симплекс-таблица:");
            for (int i = 0; i < table_result.GetLength(0); i++)
            {
                for (int j = 0; j < table_result.GetLength(1); j++)
                {
                    Console.Write(String.Format("{0, -6} ", Math.Round(table_result[i, j], 3)));
                }
                Console.WriteLine();
            }
            int n = 1;

            foreach (var x in result)
            {
                Console.WriteLine($"X[{n++}] = {result[0]}");
            }
        }
Exemplo n.º 2
0
        private void Calculate()
        {
            function = 0;
            result   = new double[amountOfRoots];
            importantIndexesOfRoots.Clear();
            double[,] table_result;
            Simplex S = new Simplex(table);

            table_result = S.Calculate(result);
            yVector.Clear();

            for (int i = 0; i < amountOfRoots; ++i)
            {
                //indexes of function
                if (functionsX[i + 1] != 0)
                {
                    importantIndexesOfRoots.Add(i);
                    function += functionsX[i + 1] * result[i];
                }
            }

            for (int i = 1 + amountOfRoots; i < amountOfRoots + amountOfRestriction + 1; ++i)
            {
                yVector.Add(table_result[amountOfRestriction, i]);
            }
        }
Exemplo n.º 3
0
        }//вхідні дані для симплекс-таблиці (обмеження, цільова функція) з урахуванням залишку на початок і мінімального необхідного залишку
        public double[] Plan()//об'єм купленого палива в і-й країні
        {
            int points_number = costs.Length;

            double[] result = new double[points_number];
            double[,] table_result;
            Simplex S = new Simplex(Table);

            table_result = S.Calculate(result);
            //return result;
            return(Simplify1(result));
        }
Exemplo n.º 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView2.Columns.Clear();

            dataGridView3.Columns.Clear();
            dataGridView3.Columns.Add("column1", "");
            dataGridView2.ReadOnly         = true;
            dataGridView3.ReadOnly         = true;
            dataGridView3.Columns[0].Width = 30;

            double[,] table = new double[s1, s2];
            for (int i = 0; i < s1; i++)
            {
                for (int j = 0; j < s2; j++)
                {
                    table[i, j] = Convert.ToDouble(dataGridView1[j, i].Value);
                }
            }

            double[] result = new double[s2 - 1];

            double[,] table_result;
            Simplex S = new Simplex(table);

            table_result = S.Calculate(result);

            for (int i = 0; i < table_result.GetLength(1); i++)
            {
                dataGridView2.Columns.Add("column1", "");
                dataGridView2.Columns[i].Width = 30;
            }
            for (int j = 0; j < table_result.GetLength(0); j++)
            {
                dataGridView2.Rows.Add();
            }

            for (int i = 0; i < table_result.GetLength(0); i++)
            {
                for (int j = 0; j < table_result.GetLength(1); j++)
                {
                    dataGridView2[j, i].Value = table_result[i, j];
                }
            }

            for (int i = 0; i < result.Length; i++)
            {
                dataGridView3.Rows.Add();
                dataGridView3[0, i].Value = result[i];
            }
        }
Exemplo n.º 5
0
        private void doSymplexMethod()
        {
            double[] result = new double[2];
            double[,] table_result;
            Simplex S = new Simplex(matrix);

            table_result = S.Calculate(result);

            results.Text += output;

            int i = 1;

            foreach (double el in result)
            {
                results.Text += "x" + i + " = " + el + "\n";
                i++;
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            int A = 2; //кол-во целевых функций
            int N = 3; //кол-во ограничений
            int M = 2; //кол-во переменных

            //todo: автоизменение знака
            double[,] targetFunctions = { { 0,  -1,  -3 },
                                          { 0, -40, -10 } };
            // Максимизация или минимизация
            bool[] directions = { true, true };

            // Ограничения
            double[,] restrictions = new double[, ] {
                { 90, 2, 1 },
                { 60, 1, 1 },
                { 50, 0, 1 }
            };
            // Знаки ограничений
            // <= true
            // >= false
            bool[] signs = { true, true, false };

            // Дополнительные ограничения
            double[,] additionalRestrictions = new double[N - 1, M + 1];
            // Уступки
            double[] assigments = { 16 };
            // итоговые значения функций
            double[] criteriaValues = new double[A];
            double[] result         = new double[M];
            double[,] table_result;
            //Ввод данных
            if (true)
            {
                Console.Write("Введите количество целевых функций: ");
                A = Int32.Parse(Console.ReadLine());
                Console.Write("Введите количество Ограничений: ");
                N = Int32.Parse(Console.ReadLine());
                Console.Write("Введите количество переменных: ");
                M = Int32.Parse(Console.ReadLine());

                // Вводим коофициенты целевых функций
                for (int i = 0; i < A; i++)
                {
                    Console.WriteLine("F[" + i + "]= ");
                    targetFunctions[i, 0] = 0;
                    for (int j = 1; j < M + 1; j++)
                    {
                        targetFunctions[i, j] = -Int32.Parse(Console.ReadLine());
                    }
                    Console.WriteLine("Max? ");
                    directions[i] = Int32.Parse(Console.ReadLine()) == 1?true:false;
                }
                // Вводим коофициенты ограничений
                for (int i = 0; i < N; i++)
                {
                    Console.WriteLine("Ограничение " + i + " ");
                    Console.WriteLine("Знак ограничения " + i + " ");
                    signs[i] = Int32.Parse(Console.ReadLine()) == 1 ? true : false;
                    Console.WriteLine("Коэфициенты ограничения " + i + " ");
                    for (int j = 0; j < M + 1; j++)
                    {
                        if (signs[i])
                        {
                            restrictions[i, j] = Int32.Parse(Console.ReadLine());
                        }
                        else
                        {
                            restrictions[i, j] = -Int32.Parse(Console.ReadLine());
                        }
                    }
                }
                // Вводим уступки
                for (int j = 0; j < A - 1; j++)
                {
                    Console.WriteLine("Уступка " + j + " ");
                    assigments[j] = Int32.Parse(Console.ReadLine());
                }
            }
            for (int i = 0; i < A; i++)
            {
                // Заполняем таблицу для прохождения симплекс метода
                double[,] table = new double[N + i + 1, M + 1];
                Array.Copy(restrictions, table, N * (M + 1));
                Array.Copy(additionalRestrictions, 0, table, N * (M + 1), i * M + 1);
                Array.Copy(targetFunctions, i * (M + 1), table, N * (M + 1) + i * (M + 1), M + 1);
                // Находим оптимум
                Simplex S = new Simplex(table, directions[i]);
                table_result = S.Calculate(result);
                double crt = -targetFunctions[i, 0];
                // Новое ограничение
                for (int k = 0; k < M; k++)
                {
                    crt -= targetFunctions[i, k + 1] * result[k];
                }
                if (i != criteriaValues.Length - 1)
                {
                    crt -= assigments[i];
                    criteriaValues[i] = crt;
                    double[,] tmp     = new double[1, 4];
                    Array.Copy(targetFunctions, tmp, 4);
                    tmp[0, 0] = -crt;
                    Array.Copy(tmp, 0, additionalRestrictions, i * 4, 4);
                }
                else
                {
                    criteriaValues[i] = crt;
                }
            }


            Console.WriteLine("Решение:");
            for (int i = 0; i < criteriaValues.Length; i++)
            {
                Console.WriteLine("f" + i + " = " + criteriaValues[i]);
            }
            Console.ReadLine();
        }
        public async Task <List <Ration> > CalcRations(int userId)
        {
            var user = await context.Users
                       .Include(k => k.KormUsers).ThenInclude(k => k.Korm)
                       .FirstOrDefaultAsync(u => u.Id == userId);

            var catalogIndexFoods = await context.CatalogIndexFoods.ToListAsync();

            int n     = catalogIndexFoods.Count() + 1;
            int m     = user.KormUsers.Count() + 1;
            var table = new double[n, m];

            for (int i = 0; i < n - 1; i++)
            {
                table[i, 0] = catalogIndexFoods[i].Limitation * -1;
                var charactereizations = context.CharacterizationIndexFoods
                                         .Include(k => k.Korm)
                                         .Include(c => c.CatalogIndexFood)
                                         .Where(c => c.CatalogIndexFoodId == catalogIndexFoods[i].Id).ToList();
                for (int j = 1; j < m; j++)
                {
                    table[i, j] = Math.Abs(charactereizations[j - 1].Value) * -1;
                }
            }

            for (int i = 1; i < m; i++)
            {
                double c = user.KormUsers[i - 1].Korm.Price * -1;
                table[n - 1, i] = c;
            }
            table[n - 1, 0] = 0;
            var result = new double[user.KormUsers.Count()];

            double[,] table_result;
            Simplex S = new Simplex(table);

            table_result = S.Calculate(result);
            var taskRation = new TaskRation
            {
                User    = user,
                UserId  = user.Id,
                Rations = new List <Ration>()
            };

            for (int i = 0; i < user.KormUsers.Count; i++)
            {
                if (result[i] == 0)
                {
                    break;
                }
                var ration = new Ration
                {
                    KormId = user.KormUsers[i].KormId,
                    Value  = result[i]
                };
                taskRation.Rations.Add(ration);
            }
            await context.TaskRations.AddAsync(taskRation);

            await context.SaveChangesAsync();

            return(taskRation.Rations.ToList());
        }
    public void doWhatNameSays()
    {
        //legacy solver
        //simplex solver = new simplex(mainCtrl.totalVariables, mainCtrl.totalRestrictions, mainCtrl.indexesMain, mainCtrl.toMax, mainCtrl.rests, solutionText);
        //solver.init();
        //solver.gen_plane();

        double[,] table = new double[mainCtrl.totalRestrictions + 1, mainCtrl.totalVariables + 1];
        for (int i = 0; i < mainCtrl.totalRestrictions + 1; i++)
        {
            for (int j = 0; j < mainCtrl.totalVariables + 1; j++)
            {
                if (i < mainCtrl.totalRestrictions)
                {
                    if (j == 0)
                    {
                        table[i, j] = mainCtrl.rests[i].b;
                    }
                    else
                    {
                        table[i, j] = mainCtrl.rests[i].indexes[j - 1];
                    }
                }
                else
                {
                    if (j == 0)
                    {
                        table[i, j] = 0;
                    }
                    else
                    {
                        if (mainCtrl.toMax)
                        {
                            table[i, j] = -mainCtrl.indexesMain[j - 1];
                        }
                        else
                        {
                            table[i, j] = mainCtrl.indexesMain[j - 1];
                        }
                    }
                }
            }
        }

        //solutionText.text = "Начальная симплекс-таблица:\n";
        //for (int i = 0; i < table.GetLength(0); i++)
        //{
        //    for (int j = 0; j < table.GetLength(1); j++)
        //        solutionText.text += string.Format("{0,-8}", table[i, j]);
        //    solutionText.text += "\n";
        //}

        double[] result = new double[mainCtrl.totalVariables];
        double[,] result_table;
        //Simplex s = new Simplex(table);
        //result_table = s.Calculate(result);

        //double[,] table = { {25, -3,  5},
        //                    {30, -2,  5},
        //                    {10,  1,  0},
        //                    { 6,  3, -8},
        //                    { 0, -6, -5} };

        int[] signs = new int[mainCtrl.totalRestrictions];
        for (int i = 0, l = signs.GetLength(0); i < l; i++)
        {
            signs[i] = mainCtrl.rests[i].type;
        }
        Simplex S = new Simplex(table, signs);

        result_table = S.Calculate(result);

        solutionText.text = "Решенная симплекс-таблица:\n";
        for (int i = 0; i < result_table.GetLength(0); i++)
        {
            for (int j = 0; j < result_table.GetLength(1); j++)
            {
                solutionText.text += string.Format("{0, -8}", Math.Round(result_table[i, j], 2));
            }
            solutionText.text += "\n";
        }

        solutionText.text += "Решение:";
        for (int i = 0; i < result.GetLength(0); i++)
        {
            solutionText.text += string.Format("{0,-6}  {1,-8}", "\nX" + (i + 1) + " = ", Math.Round(result[i], 2));
        }
        solutionText.text += string.Format("{0,-6} {1,-8}", "\nZ = ", Math.Round(result_table[result_table.GetLength(0) - 1, 0], 2));

        screenToDisable.SetActive(false);
        screenToEnable.SetActive(true);
    }
Exemplo n.º 9
0
        public FinalPage(bool flag, double Weight, List <Food> meat, List <Food> fat, List <Food> carbon, int count)
        {
            InitializeComponent();
            DietItems = new List <DietItem>();
            List <Food> Meat       = meat,
                        FatFood    = fat,
                        CarbonFood = carbon;

            Count = count;

            int    StepProtein = 0, StepFat = 0, StepCarbon = 0;
            double Protein = Weight / 4, Fat = Weight * 1.1 / 4, Carbon;

            if (flag)
            {
                Carbon = Weight / 4 * 3;
            }
            else
            {
                Carbon = Weight;
            }

            Food NoFat = null;

            for (int i = 0; i < Count; i++)
            {
                DietItems.Add(new DietItem(i, ""));
                if (StepFat >= FatFood.Count)
                {
                    StepFat = 0;
                }
                while (FatFood[StepFat].Fat <= 9 || FatFood[StepFat].Fat <= FatFood[StepFat].Protein || FatFood[StepFat].Fat <= FatFood[StepFat].Carbohydrate)
                {
                    NoFat = FatFood[StepFat];
                    StepFat++;
                    if (StepFat >= FatFood.Count)
                    {
                        StepFat = 0;
                    }
                }
                if (StepProtein >= Meat.Count)
                {
                    StepProtein = 0;
                }
                if (StepCarbon >= CarbonFood.Count)
                {
                    StepCarbon = 0;
                }
                if (NoFat == null)
                {
                    Simplex simplex = new Simplex(new double[, ]
                    {
                        { 1.05 * Carbon, FatFood[StepFat].Carbohydrate, Meat[StepProtein].Carbohydrate, CarbonFood[StepCarbon].Carbohydrate },
                        { 1.05 * Protein, FatFood[StepFat].Protein, Meat[StepProtein].Protein, CarbonFood[StepCarbon].Protein },
                        { 1.05 * Fat, FatFood[StepFat].Fat, Meat[StepProtein].Fat, CarbonFood[StepCarbon].Fat },
                        { 0, -FatFood[StepFat].Callories, -Meat[StepProtein].Callories, -CarbonFood[StepCarbon].Callories }
                    });
                    double[] result = new double[3];
                    simplex.Calculate(result);
                    List <Food> Meals = new List <Food>()
                    {
                        FatFood[StepFat],
                        Meat[StepProtein],
                        CarbonFood[StepCarbon]
                    };
                    for (int j = 0; j < result.Length; j++)
                    {
                        if ((int)(result[j] * 100) != 0)
                        {
                            DietItems.Last().Info += $"{Meals[j].FoodName}: {result[j] * 100:f0}г,\n";
                        }
                    }
                    DietItems.Last().Info += $"КБЖУ: {Meals[0].Callories * result[0] + Meals[1].Callories * result[1] + Meals[2].Callories * result[2]:f0}" +
                                             $"/{Meals[0].Protein * result[0] + Meals[1].Protein * result[1] + Meals[2].Protein * result[2]:f0}" +
                                             $"/{Meals[0].Fat * result[0] + Meals[1].Fat * result[1] + Meals[2].Fat * result[2]:f0}" +
                                             $"/{Meals[0].Carbohydrate * result[0] + Meals[1].Carbohydrate * result[1] + Meals[2].Carbohydrate * result[2]:f0}";
                }
                else
                {
                    Simplex simplex = new Simplex(new double[, ]
                    {
                        { 1.05 * Carbon, FatFood[StepFat].Carbohydrate, Meat[StepProtein].Carbohydrate, CarbonFood[StepCarbon].Carbohydrate, NoFat.Carbohydrate },
                        { 1.05 * Protein, FatFood[StepFat].Protein, Meat[StepProtein].Protein, CarbonFood[StepCarbon].Protein, NoFat.Protein },
                        { 1.05 * Fat, FatFood[StepFat].Fat, Meat[StepProtein].Fat, CarbonFood[StepCarbon].Fat, NoFat.Fat },
                        { 0.5, 0, 0, 0, 1 },
                        { 0, -FatFood[StepFat].Callories, -Meat[StepProtein].Callories, -CarbonFood[StepCarbon].Callories, -NoFat.Callories }
                    });
                    double[] result = new double[4];
                    simplex.Calculate(result); List <Food> Meals = new List <Food>()
                    {
                        FatFood[StepFat],
                        Meat[StepProtein],
                        CarbonFood[StepCarbon],
                        NoFat
                    };
                    for (int j = 0; j < result.Length; j++)
                    {
                        if ((int)(result[j] * 100) != 0)
                        {
                            DietItems.Last().Info += $"{Meals[j].FoodName}: {result[j] * 100:f0}г,\n";
                        }
                    }
                    DietItems.Last().Info += $"КБЖУ: {Meals[0].Callories * result[0] + Meals[1].Callories * result[1] + Meals[2].Callories * result[2] + Meals[3].Callories * result[3]:f0}" +
                                             $"/{Meals[0].Protein * result[0] + Meals[1].Protein * result[1] + Meals[2].Protein * result[2] + Meals[3].Protein * result[3]:f0}" +
                                             $"/{Meals[0].Fat * result[0] + Meals[1].Fat * result[1] + Meals[2].Fat * result[2] + Meals[3].Fat * result[3]:f0}" +
                                             $"/{Meals[0].Carbohydrate * result[0] + Meals[1].Carbohydrate * result[1] + Meals[2].Carbohydrate * result[2] + Meals[3].Carbohydrate * result[3]:f0}";
                }
                NoFat = null;
                StepFat++;
                StepCarbon++;
                StepProtein++;
            }
            FinalListView.ItemsSource = DietItems;
        }