Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created April 11, 2019 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aire-con-gas/865ea8aa4c1aa74b3feac120ca13f6a1 to your computer and use it in GitHub Desktop.
Save aire-con-gas/865ea8aa4c1aa74b3feac120ca13f6a1 to your computer and use it in GitHub Desktop.
JS Bin // source https://jsbin.com/gokacel
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
const computeMinRefills = (dist, tank, stops) => {
const combinedStops = [0, ...stops, dist];
let distanceTravelled = 0;
let currentIdx = 0;
let j;
let numOfRefills = 0;
while(distanceTravelled <= dist) {
j = currentIdx + 1;
if (combinedStops[j] >= dist) {
break;
}
if (combinedStops[j] - combinedStops[currentIdx] > tank) {
return -1;
}
while (combinedStops[j] - combinedStops[currentIdx] <= tank) {
j++;
}
distanceTravelled += combinedStops[j - 1] - combinedStops[currentIdx];
numOfRefills++;
currentIdx = j - 1;
}
return numOfRefills;
}
console.log(computeMinRefills(950, 400, [200,375,550,750]));
console.log(computeMinRefills(10, 3, [1,2,5,9]));
// 950
// 400
// [200 375 550 750]
</script>
<script id="jsbin-source-javascript" type="text/javascript">const computeMinRefills = (dist, tank, stops) => {
const combinedStops = [0, ...stops, dist];
let distanceTravelled = 0;
let currentIdx = 0;
let j;
let numOfRefills = 0;
while(distanceTravelled <= dist) {
j = currentIdx + 1;
if (combinedStops[j] >= dist) {
break;
}
if (combinedStops[j] - combinedStops[currentIdx] > tank) {
return -1;
}
while (combinedStops[j] - combinedStops[currentIdx] <= tank) {
j++;
}
distanceTravelled += combinedStops[j - 1] - combinedStops[currentIdx];
numOfRefills++;
currentIdx = j - 1;
}
return numOfRefills;
}
console.log(computeMinRefills(950, 400, [200,375,550,750]));
console.log(computeMinRefills(10, 3, [1,2,5,9]));
// 950
// 400
// [200 375 550 750]
</script></body>
</html>
const computeMinRefills = (dist, tank, stops) => {
const combinedStops = [0, ...stops, dist];
let distanceTravelled = 0;
let currentIdx = 0;
let j;
let numOfRefills = 0;
while(distanceTravelled <= dist) {
j = currentIdx + 1;
if (combinedStops[j] >= dist) {
break;
}
if (combinedStops[j] - combinedStops[currentIdx] > tank) {
return -1;
}
while (combinedStops[j] - combinedStops[currentIdx] <= tank) {
j++;
}
distanceTravelled += combinedStops[j - 1] - combinedStops[currentIdx];
numOfRefills++;
currentIdx = j - 1;
}
return numOfRefills;
}
console.log(computeMinRefills(950, 400, [200,375,550,750]));
console.log(computeMinRefills(10, 3, [1,2,5,9]));
// 950
// 400
// [200 375 550 750]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment