NEP -DAA -DESIGN AND ANALYSIS OF ALOGRITHM

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 PROGRAM B7 PROGRAM B8 . . .

3

 
  
 # Function to solve the 0/1 Knapsack Problem using a greedy approach
greedy_knapsack <- function(values, weights, capacity) {
  n <- length(values)
  value_to_weight_ratio <- values / weights
  
  # Create an index vector for sorting items by the value-to-weight ratio
  sorted_indices <- order(-value_to_weight_ratio)
  
  # Initialize variables
  total_value <- 0
  knapsack <- integer(n)
  
  for (i in 1:n) {
    item_index <- sorted_indices[i]
    if (weights[item_index] <= capacity) {
      knapsack[item_index] <- 1
      total_value <- total_value + values[item_index]
      capacity <- capacity - weights[item_index]
    }
  }
  
  return(list(total_value = total_value, selected_items = knapsack))
}

# Example usage
values <- c(10, 20, 30)
weights <- c(2, 5, 10)
capacity <- 15

result <- greedy_knapsack(values, weights, capacity)

cat("Selected items (0/1): ", result$selected_items, "\n")
cat("Total value: ", result$total_value, "\n")