Skip to content

Instantly share code, notes, and snippets.

@wisaruthk
Last active December 30, 2022 04:17
Show Gist options
  • Save wisaruthk/25b8bbf4806ed39c800eccbe301fde97 to your computer and use it in GitHub Desktop.
Save wisaruthk/25b8bbf4806ed39c800eccbe301fde97 to your computer and use it in GitHub Desktop.
simplex method coding in swift (by ChatGPT)
struct LinearProgram {
let objective: [Double]
let constraints: [[Double]]
let sense: [Character]
let rhs: [Double]
}
func simplex(lp: LinearProgram) -> [Double]? {
var tableau = lp.constraints
tableau.append(lp.objective)
let m = lp.constraints.count
let n = lp.objective.count
var basis = [Int]()
for i in 0..<m {
basis.append(n + i)
}
while true {
// Find the pivot column
var pivotColumn = -1
var minRatio = Double.greatestFiniteMagnitude
for j in 0..<n {
if tableau[m][j] > 0 {
for i in 0..<m {
if tableau[i][j] < 0 {
let ratio = -tableau[i][n] / tableau[i][j]
if ratio < minRatio {
pivotColumn = j
minRatio = ratio
}
}
}
}
}
// Check for optimality
if pivotColumn == -1 {
break
}
// Find the pivot row
var pivotRow = -1
minRatio = Double.greatestFiniteMagnitude
for i in 0..<m {
if tableau[i][pivotColumn] < 0 {
let ratio = -tableau[i][n] / tableau[i][pivotColumn]
if ratio < minRatio {
pivotRow = i
minRatio = ratio
}
}
}
// Update the basis
basis[pivotRow] = pivotColumn
// Update the tableau
let pivot = tableau[pivotRow][pivotColumn]
for j in 0...n {
tableau[pivotRow][j] /= pivot
}
for i in 0..<m+1 {
if i != pivotRow {
let factor = tableau[i][pivotColumn]
for j in 0...n {
tableau[i][j] -= factor * tableau[pivotRow][j]
}
}
}
}
// Extract the solution
var solution = [Double](repeating: 0, count: n)
for i in 0..<m {
if basis[i] < n {
solution[basis[i]] = tableau[i][n]
}
}
return solution
}
// Example usage
let objective = [3, 5, 2]
let constraints = [[1, 2, 1], [3, 2, 0]]
let sense = ["<=", "<="]
let rhs = [5, 6]
let lp = LinearProgram(objective: objective, constraints: constraints, sense: sense, rhs: rhs)
let solution = simplex(lp: lp)
print(solution)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment