tomaszsvd
tomaszsvd

Reputation: 148

Solving the parking lot fees

I have a problem

Parking charge is 3$ per hour for the first 3 hours and for each extra hour you'll be charged 1$ and 24 hrs is 30$ but you can stay more than 24 hours. I don't know how to solve the hours>24 like if car stays there for 37 hours, or more. I think that modulus has to be used for this, unfortunately I cant get this working. any help ??

        if (hours >= 24) {
            price = 30;
            price += (hours - 3) % 1; //should the mod even go here?
        } else if (hours < 24 && hours > 3) {
            price = 9;
            price += (hours - 3) * 1;
        } else {
            price = hours * 3;
        }
        System.out.println("Hours: " + hours + " Price: " + price);

Upvotes: 0

Views: 5349

Answers (4)

bohuss
bohuss

Reputation: 336

based on your specification, it should be as easy as:

    price = Math.min(hours, 3) * 3 + Math.max(hours - 3, 0) * 1;
    System.out.println("Hours: " + hours + " Price: " + price);

update:

    price = (hours / 24) * 30 + Math.min(hours % 24, 3) * 3 + Math.max(hours % 24 - 3, 0) * 1;

Upvotes: 3

ItamarG3
ItamarG3

Reputation: 4122

This works:

if (hours >= 24) {
    price = (hours / 24)*30;
    int h = hours%24;
    int h4 = Math.min(h, 3)*2;
    price += h4 +((hours)%24);

} else if (hours < 24 && hours > 3) {
    price = 9;
    price += (hours - 3) * 1;
} else {
    price = hours * 3;
}
System.out.println("Hours: " + hours + " Price: " + price);

Upvotes: 1

Tanmay Baid
Tanmay Baid

Reputation: 469

Modifying @bohuss's solution to fix the problem for more than 24hours:

private static int calculatePrice(final int hours) {
    // find number of days [where 1 day is 24 hours]
    final int days = hours / 24;
    // calculate price based on 1 day's fixed price as $30
    int price = 30 * days;
    // find remaining hours
    final int remainingHours = hours % 24;
    // calculate price for remaining hours and add to price for entire days.
    price += Math.min(remainingHours, 3) * 3 + Math.max(remainingHours - 3, 0) * 1;
    // return total price
    return price;
}

Example Input/Output

Hours: 0 Price: 0
Hours: 1 Price: 3
Hours: 2 Price: 6
Hours: 3 Price: 9
Hours: 4 Price: 10
Hours: 5 Price: 11
Hours: 6 Price: 12
...
Hours: 22 Price: 28
Hours: 23 Price: 29
Hours: 24 Price: 30
Hours: 25 Price: 33
Hours: 26 Price: 36
Hours: 27 Price: 39
Hours: 28 Price: 40

Upvotes: 1

Brenton
Brenton

Reputation: 274

if(hours > 0) {
  if(hours > 3 && hours < 24) {
    price = 3 + hours;
  }
  if(hours >= 24) {
    price = 30;
  }
}

Note if the person parking still gets charged after 24 hours by $1 per hour then :

if(hours > 0) {
  if(hours > 3 && hours < 24) {
    price = 3 + hours;
  }
  if(hours >= 24) {
    price = 30 + hours - 24;
  }
}

Upvotes: 0

Related Questions