Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Q2</title>
- </head>
- <body>
- <input type="text" id="distance" style="width: 50%" placeholder="Distance from this station to source, start with 0, split by space"/><br/>
- <input type="text" id="cost" style="width: 50%" placeholder="Cost of each station, start with 0, split by space"/><br/>
- <input type="text" id="travel" style="width: 50%" placeholder="Maximum travel distance" /><br/>
- <button onclick="solve()">Solve</button>
- <div id="result"></div>
- <script>
- var best;
- function solve()
- {
- var input = getInput();
- var result = calculate(input);
- showResult(input, result);
- }
- function getInput ()
- {
- var distanceText = document.querySelector("#distance").value;
- var costText = document.querySelector("#cost").value;
- var travelDistance = Number(document.querySelector("#travel").value);
- var distanceArr = distanceText.split(" ").map(function(text){return Number(text);});
- var costArr = costText.split(" ").map(function(text){return Number(text);});
- return {
- distance: distanceArr,
- cost: costArr,
- travelDistance: travelDistance
- };
- }
- function calculate(input)
- {
- best = [];
- var x = input.distance;
- var cost = input.cost;
- var capacity = input.travelDistance;
- best.push(0);
- for (var i = 0; i < x.length - 1; i++)
- {
- best.push(-1);
- }
- var answer = findBest(x, cost, capacity, x.length - 1);
- return answer;
- }
- // Implementation of BestCost function
- var findBest = function(distances, costs, capacity, distanceIndex)
- {
- if (best[distanceIndex] != -1)
- {
- return best[distanceIndex];
- }
- var minDistanceIndex = findMinDistance(capacity, distances, distanceIndex);
- var answer = findBest(distances, costs, capacity, minDistanceIndex) +
- calculateCost(distances, costs, capacity, minDistanceIndex, distanceIndex);
- for (var i = minDistanceIndex + 1; i < distanceIndex; i++)
- {
- var newAnswer = findBest(distances, costs, capacity, i) +
- calculateCost(distances, costs, capacity, i, distanceIndex);
- if (newAnswer < answer)
- {
- answer = newAnswer;
- }
- }
- best[distanceIndex] = answer;
- return answer;
- }
- // Implementation of MinGasStation function
- function findMinDistance(capacity, distances, distanceIndex)
- {
- for (var i = 0; i < distances.length; i++)
- {
- if (distances[distanceIndex] - distances[i] <= capacity)
- {
- return i;
- }
- }
- }
- // Implementation of Cost function
- function calculateCost(distances, costs, capacity, a, b)
- {
- var distance = distances[b] - distances[a];
- return costs[b] * (distance / capacity);
- }
- function showResult(input, result)
- {
- var resultText = "Total cost is "+ result;
- document.querySelector("#result").innerHTML = resultText;
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment