Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Created October 17, 2017 01:35
Show Gist options
  • Select an option

  • Save thomasnield/96c4924619e67e200d8826d51f4a2e7e to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/96c4924619e67e200d8826d51f4a2e7e to your computer and use it in GitHub Desktop.
Linear Optimization with Kotlin and Apache Commons Math
package org.nield.kotlinstatistics
import org.apache.commons.math3.optim.MaxIter
import org.apache.commons.math3.optim.linear.*
import org.apache.commons.math3.optim.nonlinear.scalar.GoalType
/*
Linear optimization with Apache Commons Math and Kotlin
Original problem: http://benalexkeen.com/linear-programming-with-python-and-pulp-part-3/
*/
fun main(args: Array<String>) {
// describe the optimization problem
val f = LinearObjectiveFunction(doubleArrayOf(30000.0, 45000.0), 0.0)
val constraints = mutableListOf<LinearConstraint>()
constraints.add(LinearConstraint(doubleArrayOf(1.0, 0.0), Relationship.GEQ, 0.0))
constraints.add(LinearConstraint(doubleArrayOf(0.0, 1.0), Relationship.GEQ, 0.0))
constraints.add(LinearConstraint(doubleArrayOf(3.0, 4.0), Relationship.LEQ, 30.0))
constraints.add(LinearConstraint(doubleArrayOf(5.0, 6.0), Relationship.LEQ, 60.0))
constraints.add(LinearConstraint(doubleArrayOf(1.5, 3.0), Relationship.LEQ, 21.0))
// create and run the solver
val solution = SimplexSolver().optimize(MaxIter(1000), f, LinearConstraintSet(constraints), GoalType.MAXIMIZE, NonNegativeConstraint(true))
// get the solution
val x = solution.point[0]
val y = solution.point[1]
val min = solution.value
println("$x $y $min")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment