

Suppose that we want to create a maximum of 30 generations and 50 individuals for the optimization process. Now here’s the interesting part: the optimization process using the genetic algorithm. #create the function that we want to optimize fitness=function(x) The fitness the function will we use in the ga function from the GA library.
KNAPSACK ALGORITHM CODE
Then, we create the objective function that we want to optimize with the constraint function by writing these lines of code below. > data item weight survival 2 pocket knife 1 3 3 mineral water 6 15 9 snacks 3 8 #1 means that we bring the item, while 0 means that we left the item chromosomes=c(0,1,1,0,0,0,0,0,1) data We can write it as the “chromosome”, and since the problem that we want to solve is a 0–1 knapsack problem, then from these lines of codes below, 1 means that we bring the item, while 0 means that we left the item. To give you a better understanding of the genetic algorithm in this problem, suppose that we only bring a pocket knife, mineral water, and snacks in your knapsack, initially. First, we need to input the data and the parameters that we used by writing these lines of code. From the problem statement, we can define the weight of the items as the constraint function, while the survival points cumulated from the items in the knapsack as the objective function.įor the implementation in this article, here we using the GA library in R created by Luca Scrucca. The goal is: you want to maximize your knapsack capacity while maximizing your survival points as well. Suppose too that you have a knapsack that can contain items with a maximum capacity of 25 kilograms, where you can only bring one copy for each item. The image available, with the weight and survival point for each item, respectively (Image by the author) Suppose that you want to go hiking with your friends, and you have the items that you can use for hiking, with the weight (in kilograms) and survival point of each item, respectively, as follows. To give you a better understanding of the genetic algorithm, let’s jump to the case study where we will use the genetic algorithm to solve the knapsack problem in R.Ĭase Study: Solving Knapsack Problem using Genetic Algorithm These all individuals will be used for training the next generation until the number of generations is reaching the limit.

