DEV Community

Cisco Vlahakis
Cisco Vlahakis

Posted on

Coding strategy for a nutrition-based linear equation system

Suppose you'd like to develop a nutrition app that allows users to precisely set the nutritional component amounts in their food to arrive at the "perfect" menu for the day or week. Traditionally, nutrition awareness programs have taught us to eat from a variety of food groups to maximize micronutrient consumption. While this is great advice, you can still go wrong. Suppose you eat too much of one color, such as red, but not enough black, green, or blue. I use colors as an example indicator of different micronutrient compositions. When you eat the perfect combination of macro- and micro- nutrients, your body flourishes and you just "feel" your absolute best! This is why I believe heavily in custom nutritional intervention.

Suppose there are 100 nutritional components, such as Calories, Protein, Carbs, Sodium, Vitamin C, AGEs, etc.

Suppose that a food can have 1 or many nutritional components.

A user can select weights for each nutritional component, and my app should tell them the exact foods by gram they should consume to hit each of those goals.

Yet I was stuck on just how to program such a task.

Luckily, there are libraries like glpk or Simplex that make solving many, large linear systems of equations possible. This is exactly what I needed for this core feature of my app:

require 'glpk'  # or another linear programming library

# Define your food items
foods = [
  {:name => 'Turkey Breast', :calories => 135, :sodium => 70, :AGEs => 1000, ...},
  {:name => 'Strawberry', :calories => 50, :sodium => 2, :AGEs => 500, ...},
  # more food items...
]

# Get user's nutritional goals
goals = {:calories => 1700, :sodium => 2300, :AGEs => 9000, ...}

# Get user's food preferences (true = included in diet, false = not included)
preferences = {'Turkey Breast' => true, 'Strawberry' => false}

# Filter out unwanted foods
foods = foods.select { |food| preferences.fetch(food.fetch(:name)) }

# Create an empty matrix
matrix = []

# Transform data into a matrix that can be used by the linear programming library
# For each nutritional component
goals.keys.each do |component|
  # Create a new row
  row = []

  # For each food item
  foods.each do |food|
    # Add the amount of the component in the food to the row
    row << food.fetch(component)
  end

  # Add the row to the matrix
  matrix << row
end

# Solve the linear programming problem to find a combination of food items that satisfies the user's goals
solution = glpk.solve(matrix)

# Print the solution
solution.each do |item|
  puts "#{item[:name]}: #{item[:amount]}g"
end
Enter fullscreen mode Exit fullscreen mode

Performing linear algebra in a web app is no longer difficult with libraries like glpk or Simplex!

Top comments (0)