Esempio n. 1
0
        }//*/

        public static KnapsackSolution FptasAlgorithm(KnapsackAlgorithmInput test)
        {
            var startTime = System.Diagnostics.Stopwatch.StartNew();

            int[] weightsCopy = (int[])test.Weights.Clone();
            int[] pricesCopy1 = (int[])test.Prices.Clone();
            int[] pricesCopy2 = (int[])test.Prices.Clone();
            Array.Sort(pricesCopy1);

            double K = pricesCopy1[pricesCopy1.Length - 1] * EParam / test.TypesOfItems;

            for (int i = 0; i < test.TypesOfItems; i++)
            {
                pricesCopy2[i] = (int)(pricesCopy2[i] / K);
            }

            KnapsackAlgorithmInput newInput = new KnapsackAlgorithmInput(test.TypesOfItems, pricesCopy2,
                                                                         test.Weights, test.Capacity, test.PriceBorder, test.WeightBorder);

            KnapsackSolution sol = DynamicProgrammingAlgorithm(newInput);

            startTime.Stop();
            return(new KnapsackSolution(startTime.Elapsed, (int)(sol.FinalPrice * K), test.TypesOfItems, sol.FinalWeight,
                                        test.Capacity, test.MaxPrice, test, sol.Weights, false));
        }
Esempio n. 2
0
        public static KnapsackSolution DynamicProgrammingAlgorithmFptas(KnapsackAlgorithmInput test, double K)
        {
            var startTime = System.Diagnostics.Stopwatch.StartNew();

            double[] knapsack = new double[test.Capacity + 1];
            knapsack[0] = 0;
            int[] totalWeights = new int[test.Capacity + 1];
            totalWeights[0] = 0;

            for (int i = 1; i <= test.Capacity; i++)
            {
                double max    = knapsack[i - 1];
                int    weight = totalWeights[i - 1];
                for (int j = 0; j < test.TypesOfItems; j++)
                {
                    int x = i - test.Weights[j];
                    if (x >= 0 && (knapsack[x] + test.Prices[j]) > max)
                    {
                        max    = (knapsack[x] + test.Prices[j]) * K;
                        weight = totalWeights[x] + test.Weights[j];
                    }
                    knapsack[i]     = max;
                    totalWeights[i] = weight;
                }
            }

            startTime.Stop();
            return(new KnapsackSolution(startTime.Elapsed, (int)knapsack[test.Capacity], test.TypesOfItems,
                                        totalWeights[test.Capacity], test.Capacity, test.MaxPrice, test, new List <int[]>(), false));
        }
Esempio n. 3
0
        public static KnapsackSolution BranchBoundAlgorithm(KnapsackAlgorithmInput test)
        {
            var startTime = System.Diagnostics.Stopwatch.StartNew();

            int[] priceWeightRatio = new int[test.TypesOfItems];
            int[] pricesCopy       = (int[])test.Prices.Clone();
            int[] weightsCopy      = (int[])test.Weights.Clone();

            for (int i = 0; i < test.TypesOfItems; i++)
            {
                priceWeightRatio[i] = test.Prices[i] / test.Weights[i];
            }
            Array.Sort((int[])priceWeightRatio.Clone(), pricesCopy);
            Array.Sort((int[])priceWeightRatio.Clone(), weightsCopy);

            int totalPrice  = 0;
            int totalWeight = 0;

            Array.Reverse(pricesCopy);
            Array.Reverse(weightsCopy);

            BranchesBound(pricesCopy, weightsCopy, test.Capacity, 0, totalPrice, totalWeight,
                          ref totalPrice, ref totalWeight, startTime);

            startTime.Stop();

            return(new KnapsackSolution(startTime.Elapsed, totalPrice, test.TypesOfItems, totalWeight,
                                        test.Capacity, test.MaxPrice, test, new List <int[]>(), true));
        }//*/
Esempio n. 4
0
        public static KnapsackAlgorithmInput GenerateInputCapacity(int capacity)
        {
            int priceBorder  = rand.Next(1, 100000);
            int types        = rand.Next(1, 100);
            int weightBorder = rand.Next(1, capacity);

            int[] prices = new int[types];
            for (int i = 0; i < types; i++)
            {
                prices[i] = rand.Next(1, priceBorder);
            }

            int[] weights = new int[types];
            for (int i = 0; i < types; i++)
            {
                weights[i] = rand.Next(1, weightBorder);
            }

            prices[rand.Next(0, types)]  = priceBorder;
            weights[rand.Next(0, types)] = weightBorder;

            KnapsackAlgorithmInput test = new KnapsackAlgorithmInput(types, prices, weights, capacity, priceBorder, weightBorder);

            return(test);
        }
Esempio n. 5
0
        public static KnapsackAlgorithmInput[] InputFromFile(string filePath)
        {
            string[]        separator      = { "b", "c", "n", "res" };
            List <string[]> separatedLines = new List <string[]>();

            System.IO.StreamReader file = new System.IO.StreamReader(filePath);

            string line;

            while ((line = file.ReadLine()) != null)
            {
                separatedLines.Add(line.Split(separator, StringSplitOptions.RemoveEmptyEntries));
            }

            KnapsackAlgorithmInput[] inputs = new KnapsackAlgorithmInput[separatedLines.Count];

            for (int i = 0; i < separatedLines.Count; i++)
            {
                int[] weights = separatedLines[i][2].Split('w').
                                Where(x => !string.IsNullOrWhiteSpace(x)).
                                Select(x => int.Parse(x)).ToArray();
                int[] prices = separatedLines[i][3].Split('p').
                               Where(x => !string.IsNullOrWhiteSpace(x)).
                               Select(x => int.Parse(x)).ToArray();
                int capacity;
                int.TryParse(separatedLines[i][1], out capacity);
                int typesOfItems;
                int.TryParse((separatedLines[i][0].Split(new char[] { 'n' })[0]), out typesOfItems);
                int maxPrice;
                int.TryParse(separatedLines[i][4], out maxPrice);
                inputs[i] = new KnapsackAlgorithmInput(typesOfItems, prices, weights, capacity, maxPrice);
            }

            return(inputs);
        }
Esempio n. 6
0
        public static KnapsackSolution DynamicProgrammingAlgorithm(KnapsackAlgorithmInput test)
        {
            var startTime = System.Diagnostics.Stopwatch.StartNew();

            List <int[]>[] weightsArray = new List <int[]> [test.Capacity + 1];
            weightsArray[0] = new List <int[]>();
            int[] knapsack = new int[test.Capacity + 1];
            knapsack[0] = 0;
            int[] totalWeights = new int[test.Capacity + 1];
            totalWeights[0] = 0;

            for (int i = 1; i <= test.Capacity; i++)
            {
                int          max     = knapsack[i - 1];
                int          weight  = totalWeights[i - 1];
                List <int[]> maxList = new List <int[]>(weightsArray[i - 1]);
                for (int j = 0; j < test.TypesOfItems; j++)
                {
                    int          x = i - test.Weights[j];
                    List <int[]> duplicateXList;
                    if (x >= 0)
                    {
                        duplicateXList = new List <int[]>(weightsArray[x]);
                        if ((knapsack[x] + test.Prices[j]) > max)
                        {
                            max    = knapsack[x] + test.Prices[j];
                            weight = totalWeights[x] + test.Weights[j];
                            duplicateXList.Add(new int[2] {
                                1, test.Weights[j]
                            });
                            maxList = new List <int[]>(duplicateXList);
                        }
                    }
                    weightsArray[i] = new List <int[]>(maxList);
                    knapsack[i]     = max;
                    totalWeights[i] = weight;
                }
            }

            for (int i = 0; i < weightsArray[test.Capacity].Count; i++)
            {
                int number = weightsArray[test.Capacity][i][1];
                for (int j = i + 1; j < weightsArray[test.Capacity].Count; j++)
                {
                    if (weightsArray[test.Capacity][j][1] == weightsArray[test.Capacity][i][1])
                    {
                        weightsArray[test.Capacity][i][0]++;
                        weightsArray[test.Capacity].RemoveAt(j);
                        j--;
                    }
                }
            }

            startTime.Stop();
            return(new KnapsackSolution(startTime.Elapsed, knapsack[test.Capacity], test.TypesOfItems,
                                        totalWeights[test.Capacity], test.Capacity, test, weightsArray[test.Capacity], false));
        }
Esempio n. 7
0
 public KnapsackAlgorithmInput(KnapsackAlgorithmInput input)
 {
     TypesOfItems = input.TypesOfItems;
     Prices       = input.Prices;
     Weights      = input.Weights;
     Capacity     = input.Capacity;
     WeightBorder = input.WeightBorder;
     PriceBorder  = input.PriceBorder;
     MaxPrice     = input.MaxPrice;
 }
Esempio n. 8
0
 private void LoadInputBtn_Click(object sender, RoutedEventArgs e)
 {
     if (modeBtn.Content.ToString() == "Off")
     {
         OpenFileDialog openFileDialog = new OpenFileDialog();
         openFileDialog.Filter = "Text file (*.kip)|*.kip";
         if (openFileDialog.ShowDialog() == true)
         {
             BinaryFormatter formatter = new BinaryFormatter();
             try
             {
                 using (FileStream fs = new FileStream(openFileDialog.FileName,
                                                       FileMode.OpenOrCreate))
                 {
                     input           = (KnapsackAlgorithmInput)formatter.Deserialize(fs);
                     textField.Text += input;
                 }
             }
             catch (Exception)
             {
                 MessageBox.Show("Looks like this is not a real input file", "Error",
                                 MessageBoxButton.OK, MessageBoxImage.Error);
             }
         }
     }
     else
     {
         OpenFileDialog openFileDialog = new OpenFileDialog();
         openFileDialog.Filter = "Text file (*.kips)|*.kips";
         if (openFileDialog.ShowDialog() == true)
         {
             BinaryFormatter formatter = new BinaryFormatter();
             try
             {
                 using (FileStream fs = new FileStream(openFileDialog.FileName,
                                                       FileMode.OpenOrCreate))
                 {
                     inputs          = (KnapsackAlgorithmInputs)formatter.Deserialize(fs);
                     textField.Text += inputs;
                 }
             }
             catch (Exception)
             {
                 MessageBox.Show("Looks like this is not a real inputs file", "Error",
                                 MessageBoxButton.OK, MessageBoxImage.Error);
             }
         }
     }
 }
Esempio n. 9
0
 public KnapsackSolution(TimeSpan time, int finalPrice, int typesOfItems, int finalWeight,
                         int capacity, KnapsackAlgorithmInput input, List <int[]> weights, bool bbTrigger)
 {
     Time         = time;
     FinalPrice   = finalPrice;
     TypesOfItems = typesOfItems;
     Capacity     = capacity;
     FinalWeight  = finalWeight;
     Input        = input;
     if (bbTrigger)
     {
         Weights = Algorithm.DynamicProgrammingAlgorithm(input).Weights;
     }
     else
     {
         Weights = weights;
     }
 }
Esempio n. 10
0
        public static KnapsackSolution GreedyAlgorithm(KnapsackAlgorithmInput test)
        {
            var startTime = System.Diagnostics.Stopwatch.StartNew();

            int[] priceWeightRatio = new int[test.TypesOfItems];
            int[] pricesCopy       = (int[])test.Prices.Clone();
            int[] weightsCopy      = (int[])test.Weights.Clone();

            for (int i = 0; i < test.TypesOfItems; i++)
            {
                priceWeightRatio[i] = test.Prices[i] / test.Weights[i];
            }
            Array.Sort((int[])priceWeightRatio.Clone(), pricesCopy);
            Array.Sort((int[])priceWeightRatio.Clone(), weightsCopy);
            //Array.Sort(priceWeightRatio);

            List <int[]> list = new List <int[]>();

            int totalWeight = 0;
            int totalPrice  = 0;
            int itemIndex   = test.TypesOfItems - 1;

            while (totalWeight < test.Capacity && itemIndex >= 0)
            {
                int index1 = 0;
                while (totalWeight + weightsCopy[itemIndex] < test.Capacity)
                {
                    totalWeight += weightsCopy[itemIndex];
                    totalPrice  += pricesCopy[itemIndex];
                    if (totalWeight + weightsCopy[itemIndex] >= test.Capacity)
                    {
                        list.Add(new int[] { index1 + 1, weightsCopy[itemIndex] });
                    }
                    index1++;
                }
                itemIndex--;
            }

            startTime.Stop();
            return(new KnapsackSolution(startTime.Elapsed, totalPrice, test.TypesOfItems, totalWeight,
                                        test.Capacity, test.MaxPrice, test, list, false));
        }
Esempio n. 11
0
 private void OkBtn_Click(object sender, RoutedEventArgs e)
 {
     if (randBtn.Background == Brushes.Purple)
     {
         Window.input  = KnapsackAlgorithmInput.GenerateFullRandomInput();
         Window.inputs = null;
         Close();
     }
     else if (capBtn.Background == Brushes.Purple)
     {
         int cap;
         if (int.TryParse(capTB.Text, out cap) && cap > 1)
         {
             Window.input  = KnapsackAlgorithmInput.GenerateInputCapacity(cap);
             Window.inputs = null;
             Close();
         }
         else
         {
             MessageBox.Show("Something with your requirements, true again", "Error",
                             MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
     else if (typesBtn.Background == Brushes.Purple)
     {
         Random rand = new Random();
         int    types;
         if (int.TryParse(typeTB.Text, out types) && types > 1)
         {
             Window.input  = KnapsackAlgorithmInput.GenerateInput(rand.Next(1, 100000), rand.Next(1000, 50000), types);
             Window.inputs = null;
             Close();
         }
         else
         {
             MessageBox.Show("Something with your requirements, true again", "Error",
                             MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
 }
Esempio n. 12
0
        public static void InputToFile(string filePath, KnapsackAlgorithmInput input, bool append)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, append))
            {
                file.Write($"n{input.TypesOfItems}");
                file.Write($"c{input.Capacity}");
                file.Write("b");

                foreach (int weight in input.Weights)
                {
                    file.Write($"w{weight}");
                }
                file.Write("b");
                foreach (int price in input.Prices)
                {
                    file.Write($"p{price}");
                }
                file.Write("b");

                KnapsackSolution sol = Algorithm.DynamicProgrammingAlgorithm(input);

                file.WriteLine($"res{sol.FinalPrice}");
            }
        }
Esempio n. 13
0
        private async void StartBtn_Click(object sender, RoutedEventArgs e)
        {
            if (input == null && inputs == null)
            {
                MessageBox.Show("Your have no input!", "Error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                if (input != null)
                {
                    if (algorithm != null)
                    {
                        textField.Text        += input;
                        startBtn.IsEnabled     = false;
                        stopBtn.IsEnabled      = true;
                        saveInputBtn.IsEnabled = false;
                        saveSolBtn.IsEnabled   = false;

                        latestSolution = algorithm(input);
                        latestInput    = new KnapsackAlgorithmInput(input);

                        textField.Text        += latestSolution;
                        startBtn.IsEnabled     = true;
                        stopBtn.IsEnabled      = false;
                        saveInputBtn.IsEnabled = true;
                        saveSolBtn.IsEnabled   = true;
                    }
                    else
                    {
                        MessageBox.Show("Your haven't chosen an algorithm!", "Error",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else if (inputs != null)
                {
                    if (algorithm != null)
                    {
                        textField.Text        += inputs;
                        startBtn.IsEnabled     = false;
                        stopBtn.IsEnabled      = true;
                        saveInputBtn.IsEnabled = false;
                        saveSolBtn.IsEnabled   = false;

                        latestSolutions = Algorithm.BigTest(inputs.Inputs, algorithm);
                        latestInputs    = new KnapsackAlgorithmInputs(inputs);

                        textField.Text        += latestSolutions;
                        startBtn.IsEnabled     = true;
                        stopBtn.IsEnabled      = false;
                        saveInputBtn.IsEnabled = true;
                        saveSolBtn.IsEnabled   = true;
                    }
                    else
                    {
                        MessageBox.Show("Your haven't chosen an algorithm!", "Error",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }
Esempio n. 14
0
 public void SolveInput()
 {
     latestSolution = algorithm(input);
     latestInput    = new KnapsackAlgorithmInput(input);
 }
Esempio n. 15
0
        private void ManualBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (int.TryParse(strCapacity.Trim(), out manualInputCapacity) && manualInputCapacity > 1)
                {
                    try
                    {
                        manualInputWeights = strWeights.Trim().Split(' ').
                                             Where(x => !string.IsNullOrWhiteSpace(x)).
                                             Select(x => int.Parse(x)).ToArray();

                        manualInputPrices = strPrices.Trim().Split(' ').
                                            Where(x => !string.IsNullOrWhiteSpace(x)).
                                            Select(x => int.Parse(x)).ToArray();

                        if (manualInputPrices.Length != manualInputWeights.Length)
                        {
                            throw new Exception();
                        }
                        else
                        {
                            if (algorithm != null)
                            {
                                textField.Text        += input;
                                startBtn.IsEnabled     = false;
                                stopBtn.IsEnabled      = true;
                                saveInputBtn.IsEnabled = false;
                                saveSolBtn.IsEnabled   = false;

                                input = new KnapsackAlgorithmInput(manualInputPrices.Length,
                                                                   manualInputPrices, manualInputWeights, manualInputCapacity, 0);

                                latestSolution = algorithm(input);
                                //textField.VerticalOffset = textField.;
                                latestInput = new KnapsackAlgorithmInput(input);

                                textField.Text        += latestSolution;
                                startBtn.IsEnabled     = true;
                                stopBtn.IsEnabled      = false;
                                saveInputBtn.IsEnabled = true;
                                saveSolBtn.IsEnabled   = true;
                            }
                            else
                            {
                                MessageBox.Show("Your haven't chosen an algorithm!", "Error",
                                                MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Something wrong with your weights and prices",
                                        "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    finally
                    {
                    }
                }
                else
                {
                    MessageBox.Show("Something wrong with your capacity, remember it should be more than 1",
                                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Something wrong with your manual input",
                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 16
0
 private void OkBtn_Click(object sender, RoutedEventArgs e)
 {
     if (randBtn.Background == Brushes.Purple)
     {
         int n;
         if (int.TryParse(sizeTB.Text, out n) && n > 0)
         {
             List <KnapsackAlgorithmInput> inputs = new List <KnapsackAlgorithmInput>();
             for (int i = 0; i < n; i++)
             {
                 inputs.Add(KnapsackAlgorithmInput.GenerateFullRandomInput());
             }
             Window.inputs = new KnapsackAlgorithmInputs(inputs);
             Window.input  = null;
             Close();
         }
         else
         {
             MessageBox.Show("Something with your requirements, true again", "Error",
                             MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
     else if (capBtn.Background == Brushes.Purple)
     {
         int cap, size;
         if (int.TryParse(capTB.Text, out cap) && cap > 1 &&
             int.TryParse(sizeTB.Text, out size) && size > 0)
         {
             List <KnapsackAlgorithmInput> inputs = new List <KnapsackAlgorithmInput>();
             for (int i = 0; i < cap; i++)
             {
                 inputs.Add(KnapsackAlgorithmInput.GenerateInputCapacity(cap));
             }
             Window.inputs = new KnapsackAlgorithmInputs(inputs);
             Window.input  = null;
             Close();
         }
         else
         {
             MessageBox.Show("Something with your requirements, true again", "Error",
                             MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
     else if (typesBtn.Background == Brushes.Purple)
     {
         Random rand = new Random();
         int    types, size;
         if (int.TryParse(typeTB.Text, out types) && types > 1 &&
             int.TryParse(sizeTB.Text, out size) && size > 0)
         {
             List <KnapsackAlgorithmInput> inputs = new List <KnapsackAlgorithmInput>();
             for (int i = 0; i < types; i++)
             {
                 inputs.Add(KnapsackAlgorithmInput.GenerateInput(rand.Next(1, 100000), rand.Next(1000, 50000), types));
             }
             Window.inputs = new KnapsackAlgorithmInputs(inputs);
             Window.input  = null;
             Close();
         }
         else
         {
             MessageBox.Show("Something with your requirements, true again", "Error",
                             MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
 }