问题
I have a small problem solving the Car fueling problem using the Greedy Algorithm.
Problem Introduction
You are going to travel to another city that is located 𝑑 miles away from your home city. Your car can travel at most 𝑚 miles on a full tank and you start with a full tank. Along your way, there are gas stations at distances stop1 stop2 . . . ,stopN from your home city. What is the minimum number of refills needed?
Input:
950
400
4
200 375 550 750
Output:
2
What I've tried as of now
def car_fueling(dist,miles,n,gas_stations):
num_refill, curr_refill, last_refill = 0,0,0
while curr_refill <= n:
last_refill = curr_refill
while (curr_refill <= n-1) & (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles):
curr_refill += 1
if curr_refill == last_refill:
return -1
if curr_refill <= n:
num_refill += 1
return num_refill
What is the problem I'm facing
In the statement
while (curr_refill <= n-1) & (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles)
I am getting the error IndexError: list index out of range
. It is because of gas_stations[curr_refill + 1]
. So when I try to separate it as a while
loop and an if
statement as in
while (curr_refill <= n-1):
if (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles):
curr_refill += 1
else:
break
It is entering an infinite loop.
Can you kindly point out the mistake I'm facing?
Thanks in advance.
回答1:
A few issues:
&
is not the boolean and-operator. Useand
curr_refill + 1
can ben
, and hence produce the error you got. Note that the distance after the last gas station can be determined usingdist
- The value of
last_refill
is wrong from the start: you did not refill (yet) at station 0, so it should not be initialised as 0. Instead use another variable that represents how far you can currently drive.
Corrected code:
def car_fueling(dist,miles,n,gas_stations):
num_refill, curr_refill, limit = 0,0,miles
while limit < dist: # While the destination cannot be reached with current fuel
if curr_refill >= n or gas_stations[curr_refill] > limit:
# Cannot reach the destination nor the next gas station
return -1
# Find the furthest gas station we can reach
while curr_refill < n-1 and gas_stations[curr_refill+1] <= limit:
curr_refill += 1
num_refill += 1 # Stop to tank
limit = gas_stations[curr_refill] + miles # Fill up the tank
curr_refill += 1
return num_refill
# Test cases
print(car_fueling(950, 400, 4, [200, 375, 550, 750])) # 2
print(car_fueling(10, 3, 4, [1, 2, 5, 9])) # -1
回答2:
probably this will fix the index error. The logic of your code is correct and that is the same as what I did in the code in the block of else statement. Add the start point and end point(total distance) can avoid index error. First check the total distance to see if it can be arrived in a full tank. If not do the else statement.
def compute_min_refills(distance, tank, stops):
numrefill, currentrefill= 0,0
stops = [0] + stops + [distance] #include the start and end points in the stops list
if distance <= tank:
return 0
else:
while currentrefill < len(stops)-1:
lastrefill = currentrefill
#print(currentrefill, lastrefill, len(stops))
while currentrefill < len(stops)-1 and stops[currentrefill+1] - stops[lastrefill]<=tank:
currentrefill += 1
if currentrefill == lastrefill:
return -1
if currentrefill < len(stops)-1:
numrefill +=1
#print(numrefill)
return numrefill
if __name__ == '__main__':
#print(compute_min_refills(10, 3, [1,2,5,9]))
回答3:
It's in an infinite loop because n is not being incremented.
Increment n where it makes the most sense (for example, at the end of your while statement).
def car_fueling(dist,miles,n,gas_stations):
num_refill, curr_refill, last_refill = 0,0,0
while curr_refill <= n:
last_refill = curr_refill
while (curr_refill <= n-1) & (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles):
curr_refill += 1
if curr_refill == last_refill:
return -1
if curr_refill <= n:
num_refill += 1
n+=1 # Increment
return num_refill
回答4:
def car_refill(dist,cap,n,stops):
stops.insert(0,0)
stops.append(dist)
num_refill,curr_refill = 0,0
while curr_refill <= n:
last_refill = curr_refill
while (curr_refill <= n and stops[curr_refill + 1] - stops[last_refill] <= cap):
curr_refill += 1
if curr_refill == num_refill :
return -1
if curr_refill <= n:
num_refill +=1
return num_refill
try this ....
回答5:
I dont know why but answers seems overly complicated i just imagined myself driving and cameup with this simple solution
function minfill(distance, miles, n, stations) {
//added final distance to last station for simplicity can simply push to array.
stations = [...stations, distance]
let refill = 0,
limit = miles,
dt = 0, //distance travelled
current = 0; //current station
while (current <= n) {
//check if next or first station is unreachable
if ((Math.abs(stations[current] - stations[current + 1]) > limit) || stations[0] > limit) return -1
//check if we need to refuel or pass
if (Math.abs(dt - stations[current]) <= limit) {
current++
}
//if next distance was over limit we set distance tavelled to previous station ,current station was already pointed to next in above block
else {
dt = stations[current - 1]
refill++
}
}
return refill
}
p.s-this code is written in node/javascript, though i have passed all test for this question but i know here there are smarter people who will help to improve/correct this code or provide some pointers.
回答6:
import java.util.; import java.io.;
public class CarFueling {
static int compute_refills(int dist, int tank, int stops[], int n) {
int current_refills=0;
int num_refills=0;
int last_refill=0;
while(current_refills<=n) {
last_refill = current_refills;
while ((current_refills !=stops.length-1) && (stops[current_refills + 1] - stops[last_refill]) <= tank) {
current_refills +=1 ;
}
if (current_refills == last_refill)
return -1;
if (current_refills <= n)
num_refills +=1;
}
return num_refills;
}
public static void main (String[]args){
Scanner scanner = new Scanner(System.in);
int dist = scanner.nextInt();
int tank = scanner.nextInt();
int n = scanner.nextInt();
int stops[] = new int[n * n * n];// to solve array index out of bound exception increase the size of the array
for (int i = 0; i < n; i++) {
stops[i] = scanner.nextInt();
}
System.out.println(compute_refills(dist, tank, stops, n));
}
}
来源:https://stackoverflow.com/questions/61570575/car-fueling-problem-by-greedy-alogorithm-getting-list-index-out-of-range