Skip to content

Instantly share code, notes, and snippets.

@samnatale3
Last active June 4, 2020 22:05
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 samnatale3/0bfbb270912664b538092528edcb12ca to your computer and use it in GitHub Desktop.
Save samnatale3/0bfbb270912664b538092528edcb12ca to your computer and use it in GitHub Desktop.
Codecademy Challenge - Program calculates the cheapest fare option for public transport depending on number of days you are going to use it and number of rides going to be taken
public class TransitCalculator{
//Defining the variables
int numOfDays = 3;
int numOfRides = 34;
// Defining the lists
public static
double[] priceList = {2.75, 33.00, 127.00};
String[] fareOptions = {"Pay-per-ride", "7-day Unlimited Rides", "30-day Unlimited Rides"};
// Calculating the total price of the passes required and dividing it by the amount of Rides
public double calculate(int passLength, double priceOption){
int days = numOfDays;
double price = 0;
while (days > passLength){
price = price + priceOption;
days = days - passLength;
}
if (days != passLength){
price = price + priceOption;
}
return price;
}
// Passes through 30 day passes and the corresponding price so that calculate() can work out the price
public double unlimited30Price(){
double price = calculate(30, priceList[2]);
return price / numOfRides;
}
// Passes through 7 day passes and the corresponding price so that calculate() can work out the price
public double unlimited7Price(){
double price = calculate(7, priceList[1]);
return price / numOfRides;
}
public void getBestFare(double a, double b, double c){
double[] listOfPrices = {a, b, c};
double cheapestPrice = a; int cheapestFareOption = 0;
for (int i=1; i!=3; i++){
if (listOfPrices[i] < cheapestPrice){
cheapestPrice = listOfPrices[i];
cheapestFareOption = i;
}
}
cheapestPrice = ((double)(int)(cheapestPrice*100))/100.0;
System.out.println("You should get the " + fareOptions[cheapestFareOption] + " option at $" + cheapestPrice + " per ride.");
}
public static void main(String[] args){
TransitCalculator results = new TransitCalculator();
results.getBestFare(priceList[0], results.unlimited7Price(), results.unlimited30Price());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment