# 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")