Improve on the following code: [code]
- User
Improve on the following code:
<!DOCTYPE - Assistant
Improve on the following code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Linear Programming Graphical Solver</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#controls {
margin-bottom: 20px;
}
#constraints {
margin-bottom: 10px;
}
.constraint {
margin-bottom: 5px;
}
#graph {
border: 1px solid #ccc;
position: relative;
width: 600px;
height: 600px;
}
#tooltip {
position: absolute;
background-color: rgba(0,0,0,0.7);
color: #fff;
padding: 5px;
border-radius: 3px;
pointer-events: none;
display: none;
font-size: 12px;
}
button {
margin-left: 5px;
}
label {
margin-right: 5px;
}
input[type="number"] {
width: 60px;
}
</style>
</head>
<body>
<h1>Linear Programming Graphical Solver</h1>
<div id="controls">
<h2>Constraints</h2>
<div id="constraints">
<!-- Constraint inputs will be added here -->
</div>
<button id="addConstraint">Add Constraint</button>
<h2>Objective Function</h2>
<div>
<label for="objective">Maximize / Minimize:</label>
<select id="objective">
<option value="maximize">Maximize</option>
<option value="minimize">Minimize</option>
</select>
</div>
<div>
<label for="objA">Objective Function:</label>
<input type="number" id="objA" value="1"> x +
<input type="number" id="objB" value="1"> y
</div>
</div>
<h2>Graph</h2>
<div id="graph">
<canvas id="canvas" width="600" height="600"></canvas>
<div id="tooltip"></div>
</div>
<h2>Solution</h2>
<div id="solution">
<!-- Optimal solution will be displayed here -->
</div>
<script>
// Linear Programming Graphical Solver
// Initial setup
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const constraintsDiv = document.getElementById('constraints');
const addConstraintBtn = document.getElementById('addConstraint');
const objectiveSelect = document.getElementById('objective');
const objAInput = document.getElementById('objA');
const objBInput = document.getElementById('objB');
const solutionDiv = document.getElementById('solution');
const tooltip = document.getElementById('tooltip');
// Define constraints array
let constraints = [];
// Add initial constraint
addConstraint();
// Event listeners
addConstraintBtn.addEventListener('click', addConstraint);
objectiveSelect.addEventListener('change', drawGraph);
objAInput.addEventListener('input', drawGraph);
objBInput.addEventListener('input', drawGraph);
// Function to add a new constraint input
function addConstraint() {
const id = Date.now();
const constraintDiv = document.createElement('div');
constraintDiv.className = 'constraint';
constraintDiv.dataset.id = id;
constraintDiv.innerHTML = `
<label>A:</label>
<input type="number" step="any" class="a" value="1">
<label>x +</label>
<label>B:</label>
<input type="number" step="any" class="b" value="1">
<label>y ≤</label>
<input type="number" step="any" class="c" value="10">
<button class="remove">Remove</button>
`;
constraintsDiv.appendChild(constraintDiv);
// Add to constraints array
constraints.push({ a: 1, b: 1, c: 10, id: id });
// Add event listeners
const aInput = constraintDiv.querySelector('.a');
const bInput = constraintDiv.querySelector('.b');
const cInput = constraintDiv.querySelector('.c');
const removeBtn = constraintDiv.querySelector('.remove');
aInput.addEventListener('input', () => updateConstraint(id, 'a', parseFloat(aInput.value)));
bInput.addEventListener('input', () => updateConstraint(id, 'b', parseFloat(bInput.value)));
cInput.addEventListener('input', () => updateConstraint(id, 'c', parseFloat(cInput.value)));
removeBtn.addEventListener('click', () => removeConstraint(id));
drawGraph();
}
// Function to update a constraint
function updateConstraint(id, field, value) {
const constraint = constraints.find(con => con.id === id);
if (constraint) {
constraint[field] = value;
drawGraph();
}
}
// Function to remove a constraint
function removeConstraint(id) {
constraints = constraints.filter(con => con.id !== id);
const constraintDiv = constraintsDiv.querySelector(`[data-id="${id}"]`);
if (constraintDiv) {
constraintsDiv.removeChild(constraintDiv);
}
drawGraph();
}
// Function to draw the graph
function drawGraph() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw axes
drawAxes();
// Draw constraints
constraints.forEach(con => drawConstraint(con));
// Calculate and draw feasible region
const feasiblePoints = calculateFeasibleRegion();
if (feasiblePoints.length > 0) {
drawFeasibleRegion(feasiblePoints);
// Find and draw optimal solution
const optimal = findOptimalSolution(feasiblePoints);
if (optimal) {
drawOptimalPoint(optimal);
displaySolution(optimal);
} else {
solutionDiv.innerHTML = 'No optimal solution found.';
}
} else {
solutionDiv.innerHTML = 'No feasible region.';
}
// Draw objective function
drawObjectiveFunction();
}
// Function to draw axes
function drawAxes() {
ctx.beginPath();
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
// X axis
ctx.moveTo(50, canvas.height - 50);
ctx.lineTo(canvas.width - 50, canvas.height - 50);
// Y axis
ctx.moveTo(50, canvas.height - 50);
ctx.lineTo(50, 50);
ctx.stroke();
// Labels
ctx.fillStyle = '#000';
ctx.font = '12px Arial';
ctx.fillText('0', 45, canvas.height - 45);
ctx.fillText('X', canvas.width - 55, canvas.height - 55);
ctx.fillText('Y', 55, 55);
}
// Function to draw a single constraint
function drawConstraint(con) {
// y = (c - a x) / b
if (con.b === 0) return; // Avoid division by zero
const x1 = 0;
const y1 = (con.c - con.a * x1) / con.b;
const x2 = con.c / con.a;
const y2 = 0;
// Convert to canvas coordinates
const p1 = toCanvasCoords(x1, y1);
const p2 = toCanvasCoords(x2, y2);
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.lineWidth = 1;
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
// Shade the appropriate side based on inequality
// For simplicity, we will not implement shading individual constraints
}
// Function to convert mathematical coordinates to canvas coordinates
function toCanvasCoords(x, y) {
const scale = 50; // pixels per unit
const canvasX = 50 + x * scale;
const canvasY = canvas.height - 50 - y * scale;
return { x: canvasX, y: canvasY };
}
// Function to calculate the feasible region
function calculateFeasibleRegion() {
// Find intersection points of all constraints
let points = [];
// Generate all pairs of constraints
for (let i = 0; i < constraints.length; i++) {
for (let j = i + 1; j < constraints.length; j++) {
const inter = intersect(constraints[i], constraints[j]);
if (inter) {
points.push(inter);
}
}
}
// Also include intercepts of each constraint
constraints.forEach(con => {
points.push({ x: 0, y: con.c / con.b });
points.push({ x: con.c / con.a, y: 0 });
});
// Remove duplicate points
points = uniquePoints(points);
// Filter points that satisfy all constraints and x,y >=0
const feasiblePoints = points.filter(p => {
if (p.x < 0 || p.y < 0) return false;
return constraints.every(con => (con.a * p.x + con.b * p.y <= con.c + 1e-6));
});
// Find convex hull of feasible points
return convexHull(feasiblePoints);
}
// Function to find intersection of two constraints
function intersect(con1, con2) {
const a1 = con1.a, b1 = con1.b, c1 = con1.c;
const a2 = con2.a, b2 = con2.b, c2 = con2.c;
const det = a1 * b2 - a2 * b1;
if (det === 0) return null; // Parallel lines
const x = (c1 * b2 - c2 * b1) / det;
const y = (a1 * c2 - a2 * c1) / det;
return { x: x, y: y };
}
// Function to remove duplicate points
function uniquePoints(points) {
const unique = [];
points.forEach(p => {
if (!unique.some(q => Math.abs(q.x - p.x) < 1e-6 && Math.abs(q.y - p.y) < 1e-6)) {
unique.push(p);
}
});
return unique;
}
// Function to compute convex hull using Graham's scan
function convexHull(points) {
if (points.length < 3) return points;
// Sort the points
points.sort((a, b) => a.x === b.x ? a.y - b.y : a.x - b.x);
// Create upper and lower hulls
const upper = [];
for (let p of points) {
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
const lower = [];
for (let i = points.length - 1; i >= 0; i--) {
const p = points[i];
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
// Concatenate upper and lower to get full hull
upper.pop();
lower.pop();
return upper.concat(lower);
}
// Helper function for convex hull
function cross(o, a, b) {
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
}
// Function to draw feasible region
function drawFeasibleRegion(points) {
ctx.beginPath();
ctx.fillStyle = 'rgba(0, 255, 0, 0.3)';
points.forEach((p, index) => {
const coord = toCanvasCoords(p.x, p.y);
if (index === 0) ctx.moveTo(coord.x, coord.y);
else ctx.lineTo(coord.x, coord.y);
});
ctx.closePath();
ctx.fill();
}
// Function to find the optimal solution
function findOptimalSolution(points) {
if (points.length === 0) return null;
const objective = objectiveSelect.value;
const a = parseFloat(objAInput.value);
const b = parseFloat(objBInput.value);
let optimalPoint = points[0];
let optimalValue = a * points[0].x + b * points[0].y;
points.forEach(p => {
const value = a * p.x + b * p.y;
if (objective === 'maximize') {
if (value > optimalValue) {
optimalValue = value;
optimalPoint = p;
}
} else {
if (value < optimalValue) {
optimalValue = value;
optimalPoint = p;
}
}
});
return optimalPoint;
}
// Function to draw the optimal point
function drawOptimalPoint(p) {
const coord = toCanvasCoords(p.x, p.y);
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.arc(coord.x, coord.y, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.font = '12px Arial';
ctx.fillText('Optimal', coord.x + 7, coord.y - 7);
}
// Function to display the solution
function displaySolution(p) {
const a = parseFloat(objAInput.value);
const b = parseFloat(objBInput.value);
const value = a * p.x + b * p.y;
solutionDiv.innerHTML = `
Optimal Solution: x = ${p.x.toFixed(2)}, y = ${p.y.toFixed(2)} <br>
${objectiveSelect.value.charAt(0).toUpperCase() + objectiveSelect.value.slice(1)} Value = ${value.toFixed(2)}
`;
}
// Function to draw the objective function
function drawObjectiveFunction() {
const a = parseFloat(objAInput.value);
const b = parseFloat(objBInput.value);
if (a === 0 && b === 0) return; // Invalid objective function
// To plot the line ax + by = k, choose k as needed
// We'll plot it near the optimal point direction
const k = 0; // Base value
// Find two points on the objective function line
let x1 = 0;
let y1 = k / b;
let x2 = k / a;
let y2 = 0;
// Adjust k to visualize the line within the graph
// For simplicity, we plot a arbitrary line
x1 = -10;
y1 = (k - a * x1) / b;
x2 = 10;
y2 = (k - a * x2) / b;
const p1 = toCanvasCoords(x1, y1);
const p2 = toCanvasCoords(x2, y2);
ctx.beginPath();
ctx.strokeStyle = 'purple';
ctx.lineWidth = 2;
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
// Add event listeners for tooltip
canvas.addEventListener('mousemove', onMouseMove);
canvas.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
// Function to handle mouse move for tooltip
function onMouseMove(event) {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
// Check if mouse is near any constraint line
// For simplicity, this is not implemented here
// You can implement proximity checks and show relevant tooltips
// Example tooltip
tooltip.style.left = event.clientX + 10 + 'px';
tooltip.style.top = event.clientY + 10 + 'px';
tooltip.innerHTML = 'Tooltips can be implemented here.';
tooltip.style.display = 'block';
}
// Initial draw
drawGraph();
</script>
</body>
</html>```
Certainly! Here's an improved version of your Linear Programming Graphical Solver. The enhancements focus on:
User Interface Improvements:
≤, ≥, =) for constraints.Functionality Enhancements:
Code Optimizations:
let, const, arrow functions, and template literals.Below is the enhanced code with these improvements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Linear Programming Graphical Solver</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
#controls {
width: 100%;
max-width: 800px;
margin-bottom: 30px;
padding: 20px;
border: 2px solid #4CAF50;
border-radius: 8px;
background-color: #f9f9f9;
}
#constraints {
margin-bottom: 15px;
}
.constraint {
display: flex;
align-items: center;
margin-bottom: 10px;
flex-wrap: wrap;
}
.constraint label {
margin: 0 5px;
}
.constraint input[type="number"] {
width: 60px;
margin-right: 10px;
}
.constraint select {
margin-right: 10px;
}
.constraint button {
margin-left: auto;
background-color: #f44336;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
border-radius: 4px;
}
.constraint button:hover {
background-color: #d32f2f;
}
button#addConstraint {
background-color: #4CAF50;
color: white;
border: none;
padding: 7px 15px;
cursor: pointer;
border-radius: 4px;
margin-top: 10px;
}
button#addConstraint:hover {
background-color: #45a049;
}
#graphContainer {
position: relative;
width: 80%;
max-width: 700px;
margin-bottom: 30px;
}
#canvas {
border: 2px solid #ccc;
width: 100%;
height: 600px;
background-color: #fff;
}
#tooltip {
position: absolute;
background-color: rgba(0,0,0,0.8);
color: #fff;
padding: 8px;
border-radius: 4px;
pointer-events: none;
display: none;
font-size: 14px;
z-index: 10;
}
#solution {
width: 100%;
max-width: 800px;
padding: 20px;
border: 2px solid #2196F3;
border-radius: 8px;
background-color: #e3f2fd;
}
#solution h3 {
margin-top: 0;
}
@media (max-width: 768px) {
#canvas {
height: 400px;
}
}
</style>
</head>
<body>
<h1>Linear Programming Graphical Solver</h1>
<div id="controls">
<h2>Constraints</h2>
<div id="constraints">
<!-- Constraint inputs will be dynamically added here -->
</div>
<button id="addConstraint">Add Constraint</button>
<h2>Objective Function</h2>
<div style="margin-top:15px;">
<label for="objective">Type:</label>
<select id="objective">
<option value="maximize">Maximize</option>
<option value="minimize">Minimize</option>
</select>
</div>
<div style="margin-top:10px;">
<label for="objA">Objective Function:</label>
<input type="number" id="objA" value="1" step="any"> x +
<input type="number" id="objB" value="1" step="any"> y
</div>
</div>
<div id="graphContainer">
<canvas id="canvas" width="700" height="700"></canvas>
<div id="tooltip"></div>
</div>
<div id="solution">
<h3>Optimal Solution</h3>
<p id="solutionContent">Please define constraints and objective function to find the optimal solution.</p>
</div>
<script>
// Linear Programming Graphical Solver - Improved Version
// Get DOM elements
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const constraintsDiv = document.getElementById('constraints');
const addConstraintBtn = document.getElementById('addConstraint');
const objectiveSelect = document.getElementById('objective');
const objAInput = document.getElementById('objA');
const objBInput = document.getElementById('objB');
const solutionDiv = document.getElementById('solutionContent');
const tooltip = document.getElementById('tooltip');
// Store constraints
let constraints = [];
// Initialize with two constraints for demonstration
addConstraint({a: 1, b: 1, inequality: '≤', c: 10});
addConstraint({a: 2, b: 1, inequality: '≤', c: 15});
// Event Listeners
addConstraintBtn.addEventListener('click', () => addConstraint());
objectiveSelect.addEventListener('change', drawGraph);
objAInput.addEventListener('input', drawGraph);
objBInput.addEventListener('input', drawGraph);
window.addEventListener('resize', drawGraph); // Redraw on window resize
// Function to add a new constraint input row
function addConstraint(data = {a:1, b:1, inequality:'≤', c:10}) {
const id = Date.now();
const constraintDiv = document.createElement('div');
constraintDiv.className = 'constraint';
constraintDiv.dataset.id = id;
constraintDiv.innerHTML = `
<label>A:</label>
<input type="number" step="any" class="a" value="${data.a}">
<label>x +</label>
<label>B:</label>
<input type="number" step="any" class="b" value="${data.b}">
<label>y</label>
<label> </label>
<select class="inequality">
<option value="≤" ${data.inequality === '≤' ? 'selected' : ''}>≤</option>
<option value="≥" ${data.inequality === '≥' ? 'selected' : ''}>≥</option>
<option value="=" ${data.inequality === '=' ? 'selected' : ''}>=;</option>
</select>
<label>C:</label>
<input type="number" step="any" class="c" value="${data.c}">
<button class="remove">Remove</button>
`;
constraintsDiv.appendChild(constraintDiv);
// Add to constraints array
constraints.push({a: data.a, b: data.b, inequality: data.inequality, c: data.c, id: id});
// Add event listeners for inputs and remove button
const aInput = constraintDiv.querySelector('.a');
const bInput = constraintDiv.querySelector('.b');
const inequalitySelect = constraintDiv.querySelector('.inequality');
const cInput = constraintDiv.querySelector('.c');
const removeBtn = constraintDiv.querySelector('.remove');
aInput.addEventListener('input', () => updateConstraint(id, 'a', parseFloat(aInput.value)));
bInput.addEventListener('input', () => updateConstraint(id, 'b', parseFloat(bInput.value)));
inequalitySelect.addEventListener('change', () => updateConstraint(id, 'inequality', inequalitySelect.value));
cInput.addEventListener('input', () => updateConstraint(id, 'c', parseFloat(cInput.value)));
removeBtn.addEventListener('click', () => removeConstraint(id));
drawGraph();
}
// Function to update constraint
function updateConstraint(id, field, value) {
const constraint = constraints.find(con => con.id === id);
if (constraint) {
constraint[field] = value;
drawGraph();
}
}
// Function to remove constraint
function removeConstraint(id) {
constraints = constraints.filter(con => con.id !== id);
const constraintDiv = constraintsDiv.querySelector(`[data-id="${id}"]`);
if (constraintDiv) constraintsDiv.removeChild(constraintDiv);
drawGraph();
}
// Function to draw the entire graph
function drawGraph() {
// Adjust canvas size based on container
const containerWidth = document.getElementById('graphContainer').clientWidth;
canvas.width = containerWidth;
canvas.height = containerWidth; // Keep square for simplicity
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Define scaling
const padding = 50;
const scale = (canvas.width - 2 * padding) / 20; // 1 unit = 50 pixels
const origin = {x: padding, y: canvas.height - padding};
// Draw axes
drawAxes(ctx, origin, scale);
// Draw constraints
constraints.forEach(con => drawConstraint(ctx, con, origin, scale));
// Calculate feasible region
const feasiblePoints = calculateFeasibleRegion(constraints);
if (feasiblePoints.length === 0) {
solutionDiv.innerHTML = 'No feasible region defined. Please adjust constraints.';
return;
}
// Draw feasible region
drawFeasibleRegion(ctx, feasiblePoints, origin, scale);
// Find optimal solution
const optimal = findOptimalSolution(feasiblePoints, objectiveSelect.value, parseFloat(objAInput.value), parseFloat(objBInput.value));
if (optimal) {
drawOptimalPoint(ctx, optimal, origin, scale);
displaySolution(optimal, objectiveSelect.value, objAInput.value, objBInput.value);
} else {
solutionDiv.innerHTML = 'No optimal solution found.';
}
// Draw Objective Function Line
drawObjectiveFunction(ctx, origin, scale, parseFloat(objAInput.value), parseFloat(objBInput.value), feasiblePoints, parseFloat(objAInput.value) + parseFloat(objBInput.value));
}
// Function to draw axes
function drawAxes(ctx, origin, scale) {
ctx.beginPath();
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
// X-axis
ctx.moveTo(origin.x, origin.y);
ctx.lineTo(canvas.width - 20, origin.y);
// Y-axis
ctx.moveTo(origin.x, origin.y);
ctx.lineTo(origin.x, 20);
ctx.stroke();
// Draw arrows
ctx.beginPath();
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
// X-axis arrow
ctx.moveTo(canvas.width - 20, origin.y);
ctx.lineTo(canvas.width - 30, origin.y - 5);
ctx.moveTo(canvas.width - 20, origin.y);
ctx.lineTo(canvas.width - 30, origin.y + 5);
// Y-axis arrow
ctx.moveTo(origin.x, 20);
ctx.lineTo(origin.x - 5, 30);
ctx.moveTo(origin.x, 20);
ctx.lineTo(origin.x + 5, 30);
ctx.stroke();
// Labels
ctx.fillStyle = '#000';
ctx.font = '14px Arial';
ctx.fillText('0', origin.x - 15, origin.y + 15);
ctx.fillText('X', canvas.width - 25, origin.y + 25);
ctx.fillText('Y', origin.x + 10, 30);
// Grid lines and labels
ctx.strokeStyle = '#e0e0e0';
ctx.lineWidth = 1;
ctx.font = '12px Arial';
for(let i=1; i<=20; i++) {
// Vertical grid lines
ctx.beginPath();
ctx.moveTo(origin.x + i * scale, origin.y);
ctx.lineTo(origin.x + i * scale, 20);
ctx.stroke();
// Horizontal grid lines
ctx.beginPath();
ctx.moveTo(origin.x, origin.y - i * scale);
ctx.lineTo(canvas.width - 20, origin.y - i * scale);
ctx.stroke();
// Axis labels
ctx.fillStyle = '#000';
ctx.fillText(i, origin.x + i * scale - 5, origin.y + 15); // X-axis
ctx.fillText(i, origin.x - 20, origin.y - i * scale + 5); // Y-axis
}
}
// Function to draw a single constraint
function drawConstraint(ctx, con, origin, scale) {
const {a, b, inequality, c} = con;
// Handle cases where a or b is zero
if (a === 0 && b === 0) return; // Invalid constraint
if (a === 0) { // Vertical line x = c/b
if (b === 0) return;
const x = c / a;
const xPos = origin.x + x * scale;
ctx.beginPath();
ctx.strokeStyle = '#FF5722';
ctx.lineWidth = 2;
ctx.moveTo(xPos, 20);
ctx.lineTo(xPos, canvas.height - 20);
ctx.stroke();
} else if (b === 0) { // Horizontal line y = c/a
const y = c / b;
const yPos = origin.y - y * scale;
ctx.beginPath();
ctx.strokeStyle = '#FF5722';
ctx.lineWidth = 2;
ctx.moveTo(origin.x, yPos);
ctx.lineTo(canvas.width - 20, yPos);
ctx.stroke();
} else {
// Compute two points for the constraint line
const x1 = 0;
const y1 = (c - a * x1) / b;
const x2 = c / a;
const y2 = 0;
// Convert to canvas coordinates
const p1 = {
x: origin.x + x1 * scale,
y: origin.y - y1 * scale
};
const p2 = {
x: origin.x + x2 * scale,
y: origin.y - y2 * scale
};
ctx.beginPath();
ctx.strokeStyle = '#FF5722';
ctx.lineWidth = 2;
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
}
// Draw inequality shading
shadeConstraint(ctx, con, origin, scale);
}
// Function to shade the feasible side of the constraint
function shadeConstraint(ctx, con, origin, scale) {
const {a, b, inequality, c} = con;
// Define two points far along the constraint line for shading
const x1 = -10, y1 = (c - a * x1) / b;
const x2 = 20, y2 = (c - a * x2) / b;
// Convert to canvas coordinates
const p1 = {x: origin.x + x1 * scale, y: origin.y - y1 * scale};
const p2 = {x: origin.x + x2 * scale, y: origin.y - y2 * scale};
// Define a large polygon area for shading
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
// Extend to canvas edges based on inequality
if (inequality === '≤' || inequality === '<=') {
ctx.lineTo(canvas.width - 20, p2.y - (canvas.width * 2));
ctx.lineTo(origin.x - 10, p1.y - (canvas.width * 2));
} else if (inequality === '≥' || inequality === '>=') {
ctx.lineTo(canvas.width - 20, p2.y + (canvas.width * 2));
ctx.lineTo(origin.x - 10, p1.y + (canvas.width * 2));
} else { // equality, no shading
ctx.closePath();
ctx.strokeStyle = '#000';
ctx.stroke();
return;
}
ctx.closePath();
ctx.fillStyle = 'rgba(173, 216, 230, 0.2)';
ctx.fill();
}
// Function to calculate feasible region points
function calculateFeasibleRegion(constraints) {
let points = [];
// Include intersection points of all constraint pairs
for(let i=0; i<constraints.length; i++) {
for(let j=i+1; j<constraints.length; j++) {
const inter = intersect(constraints[i], constraints[j]);
if (inter && isValidPoint(inter, constraints)) {
points.push(inter);
}
}
}
// Include axis intercepts
constraints.forEach(con => {
if (con.b !== 0) {
points.push({x:0, y: con.c / con.b});
}
if (con.a !== 0) {
points.push({x: con.c / con.a, y:0});
}
});
// Remove duplicates
points = uniquePoints(points);
// Find convex hull for feasible region
points = convexHull(points);
return points;
}
// Function to find intersection of two constraints
function intersect(con1, con2) {
const {a: a1, b: b1, c: c1} = con1;
const {a: a2, b: b2, c: c2} = con2;
const det = a1 * b2 - a2 * b1;
if (det === 0) return null; // Parallel lines
const x = (c1 * b2 - c2 * b1) / det;
const y = (a1 * c2 - a2 * c1) / det;
return {x: x, y: y};
}
// Function to check if a point satisfies all constraints
function isValidPoint(point, constraints) {
if (point.x < -1e-6 || point.y < -1e-6) return false; // Negative values
for(let con of constraints) {
const lhs = con.a * point.x + con.b * point.y;
if (con.inequality === '≤' && lhs > con.c + 1e-6) return false;
if (con.inequality === '≥' && lhs < con.c - 1e-6) return false;
if (con.inequality === '=' && Math.abs(lhs - con.c) > 1e-6) return false;
}
return true;
}
// Function to remove duplicate points
function uniquePoints(points) {
const unique = [];
points.forEach(p => {
if (!unique.some(q => Math.abs(q.x - p.x) < 1e-6 && Math.abs(q.y - p.y) < 1e-6)) {
unique.push(p);
}
});
return unique;
}
// Function to compute convex hull using Graham's scan
function convexHull(points) {
if (points.length < 3) return points;
// Sort points by x, then by y
points.sort((a, b) => a.x === b.x ? a.y - b.y : a.x - b.x);
const upper = [];
for(let p of points) {
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length -1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
const lower = [];
for(let i = points.length -1; i >=0; i--) {
const p = points[i];
while (lower.length >=2 && cross(lower[lower.length -2], lower[lower.length -1], p) <=0) {
lower.pop();
}
lower.push(p);
}
upper.pop();
lower.pop();
return upper.concat(lower);
}
// Helper function for convex hull
function cross(o, a, b) {
return (a.x - o.x)*(b.y - o.y) - (a.y - o.y)*(b.x - o.x);
}
// Function to draw feasible region
function drawFeasibleRegion(ctx, points, origin, scale) {
ctx.beginPath();
ctx.moveTo(origin.x + points[0].x * scale, origin.y - points[0].y * scale);
points.slice(1).forEach(p => {
ctx.lineTo(origin.x + p.x * scale, origin.y - p.y * scale);
});
ctx.closePath();
ctx.fillStyle = 'rgba(144,238,144, 0.3)';
ctx.fill();
ctx.strokeStyle = '#32CD32';
ctx.lineWidth = 2;
ctx.stroke();
}
// Function to find optimal solution
function findOptimalSolution(points, type, objA, objB) {
if (points.length === 0) return null;
let optimal = points[0];
let optimalValue = objA * optimal.x + objB * optimal.y;
points.forEach(p => {
const value = objA * p.x + objB * p.y;
if (type === 'maximize') {
if (value > optimalValue) {
optimal = p;
optimalValue = value;
}
} else {
if (value < optimalValue) {
optimal = p;
optimalValue = value;
}
}
});
return optimal;
}
// Function to draw the optimal point
function drawOptimalPoint(ctx, point, origin, scale) {
ctx.beginPath();
ctx.arc(origin.x + point.x * scale, origin.y - point.y * scale, 6, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.strokeStyle = '#000';
ctx.stroke();
// Optional: Label the point
ctx.font = '14px Arial';
ctx.fillStyle = '#000';
ctx.fillText(`(${point.x.toFixed(2)}, ${point.y.toFixed(2)})`, origin.x + point.x * scale + 10, origin.y - point.y * scale - 10);
}
// Function to display the solution
function displaySolution(point, type, objA, objB) {
const value = objA * point.x + objB * point.y;
solutionDiv.innerHTML = `
<strong>Optimal Point:</strong> (x = ${point.x.toFixed(2)}, y = ${point.y.toFixed(2)})<br>
<strong>${type.charAt(0).toUpperCase() + type.slice(1)} Value:</strong> ${value.toFixed(2)}
`;
}
// Function to draw the objective function (for visualization purposes)
function drawObjectiveFunction(ctx, origin, scale, objA, objB, feasiblePoints, initialK) {
// Determine a range of k values to plot multiple objective lines
const numLines = 5;
const kValues = [];
let step = 5;
for(let i=1; i<=numLines; i++) {
kValues.push(initialK + i * step);
kValues.push(initialK - i * step);
}
kValues.forEach(k => {
const x1 = 0;
const y1 = k / objB;
const x2 = k / objA;
const y2 = 0;
// Convert to canvas coordinates
const p1 = {x: origin.x + x1 * scale, y: origin.y - y1 * scale};
const p2 = {x: origin.x + x2 * scale, y: origin.y - y2 * scale};
ctx.beginPath();
ctx.strokeStyle = 'rgba(128, 0, 128, 0.5)';
ctx.lineWidth = 1;
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
});
}
// Optional: Add tooltip functionality for interactive exploration
canvas.addEventListener('mousemove', function(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Convert canvas coordinates to mathematical coordinates
const padding = 50;
const scale = (canvas.width - 2 * padding) / 20;
const originX = padding;
const originY = canvas.height - padding;
const mathX = (x - originX) / scale;
const mathY = (originY - y) / scale;
// Check proximity to feasible points
const tolerance = 0.2; // Adjust as needed
const feasiblePoints = calculateFeasibleRegion(constraints);
for(let p of feasiblePoints) {
if (Math.abs(p.x - mathX) < tolerance && Math.abs(p.y - mathY) < tolerance) {
tooltip.style.left = `${event.clientX + 10}px`;
tooltip.style.top = `${event.clientY + 10}px`;
tooltip.innerHTML = `Point: (${p.x.toFixed(2)}, ${p.y.toFixed(2)})`;
tooltip.style.display = 'block';
return;
}
}
tooltip.style.display = 'none';
});
canvas.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
// Initial draw
drawGraph();
</script>
</body>
</html>
Enhanced Styling and Layout:
Flexible Constraint Inputs:
≤, ≥, =) for each constraint, allowing for more versatile problem definitions.Interactive and Informative Graph:
#FF5722 for visibility), and the feasible region uses a semi-transparent green for clarity.Robust Mathematical Computations:
Improved User Experience:
Code Quality Enhancements:
Constraint Validation: Implement more robust validation for user inputs to prevent nonsensical constraints (e.g., a=0 and b=0).
Dynamic Scaling: Automatically adjust the scale and axes based on the range of constraints for better visualization, especially for larger values.
Export/Import Feature: Allow users to save their equations and reload them later for continued work.
Extended Functionality: Incorporate methods to handle multiple objective functions or provide sensitivity analysis for the solutions.
This improved version should provide a more robust, user-friendly, and visually appealing tool for solving linear programming problems graphically. Feel free to further customize and enhance it based on specific requirements or user feedback!
Not yet included in a published release.