主頁 > 後端開發 > 演算法問題求助

演算法問題求助

2020-09-21 02:02:49 後端開發

有這樣幾個時間段

從       至     收費
00:00~08:00    0元

08:00~10:00    5元

10:00~12:00    10元

12:00~15:00    15元

15:00~00:00    20元

顧客 9點開臺   13點結賬共消費3元 

用Java實作,求演算法!

uj5u.com熱心網友回復:

題目要求不明確?
08:00~10:00    5元 //這里的5元是每小時5元還是一共5元(也就是每小時2.5元)
另外,從你給的客戶消費情況和收費標準來推算,客戶一共玩了4個小時,怎么也算不出才收費3元,所以你的題目是不是還有什么條件沒說清楚?

uj5u.com熱心網友回復:




參考 1 樓 qybao 的回復:
題目要求不明確?
08:00~10:00    5元 //這里的5元是每小時5元還是一共5元(也就是每小時2.5元)
另外,從你給的客戶消費情況和收費標準來推算,客戶一共玩了4個小時,怎么也算不出才收費3元,所以你的題目是不是還有什么條件沒說清楚?

這個是原題 

uj5u.com熱心網友回復:

好吧,這其實涉及不到演算法,就是回圈時間取每個計費區間的費用累加即可,純體力勞動,就給你寫個小例子吧
因為題目的邊界條件不是很明確(具體看代碼中的測驗資料),所以如果邊界條件有出入,請自行修改代碼
整個代碼核心的部分只有幾個地方(代碼注釋中用【重點】標識)
class PriceUnit { //單價類(考慮到單價的單位不同,有按小時的,有按分鐘,所以特別做了個單價類以進行單價換算)
    private double price;
    private int unit; //0:hore, 1:minute
    PriceUnit(double price, int unit) {
        this.price = price;
        this.unit = unit;
    }
    public double getPrice() {return price;}
    public void setPrice(double price) {this.price = price;}
    public int getUnit() {return unit;}
    public void setUnit(int unit) {this.unit = unit;}
    public String toString() {
        return String.format("%.0f/%s", price, (unit==0 ? "小時" : "分鐘"));
    }
    public PriceUnit convertUnit(int toUnit) { //單價換算
        switch(toUnit) {
        case 0:
            switch(this.unit) {
            case 1:
                this.price *= 60;
                break;
            }
            break;
        case 1:
            switch(this.unit) {
            case 0:
                this.price /= 60;
                break;
            }
            break;
        }
        this.unit = toUnit;
        return this;
    }
}

class ParkPrice extends PriceUnit { //停車時間區間單價類
    private int start;
    private int end;
    public ParkPrice(int start, int end, double price) {
        this(start, end, price, 0);
    }
    public ParkPrice(int start, int end, double price, int unit) {
    super(price, unit);
    this.start = start;
    this.end = end;
    }
    public int getStart() {return start;}
    public int getEnd() {return end;}
    public String toString() {
        return String.format("%02d:00~%02d:00 %s", start, end, super.toString());
    }
    public ParkPrice convertUnit(int toUnit) {
        super.convertUnit(toUnit);
        return this;
    }
}

public class ParkFeeSimulator { //模擬停車計費主類
    private static ParkPrice parkPrice[] = { //【重點1】:構造一個時間段的價格表陣列
        new ParkPrice(0, 5, 2),
        new ParkPrice(5, 7, 10),
        new ParkPrice(7, 12, 6),
        new ParkPrice(12, 14, 10),
        new ParkPrice(14, 18, 2),
        new ParkPrice(18, 19, 1, 1).convertUnit(0), //這個需求不明確,題目要求不足1小時按小時收費,所以統一轉成小時單價
        new ParkPrice(19, 21, 20),
        new ParkPrice(21, 24, 6)
    };

    private int freeMinute; //免費時間
    private double maxFeePreDay; //1日最大費用
    public ParkFeeSimulator(int freeMinute, double maxFeePreDay) {
        this.freeMinute = freeMinute;
        this.maxFeePreDay = maxFeePreDay;
    }
    public void setFreeMinute(int freeMinute) { //根據題目要求這個可變
     this.freeMinute = freeMinute;
    }
    public void setMaxFeereDay(double maxFeePreDay) { //根據題目要求這個可變
     this.maxFeePreDay = maxFeePreDay;
    }
    public void listParkPrice() { //列印收費表
        System.out.printf("停車收費價格表\n");
        for (int i=0; i<parkPrice.length; i++) {
            System.out.printf("%d %s\n", i+1, parkPrice[i]);
        }
    }
    protected double getParkPrice(int hour) { //【重點2】:通過時間引數從價格表陣列查找并取得相應的時區價格
        for (ParkPrice pp : parkPrice) {
            if (hour > pp.getStart() && hour <= pp.getEnd()) {
                return pp.getPrice();
            }
        }
        return 0;
    }
    public double caculatePartFee(Calendar start, Calendar end) { //根據開始時間,停止時間計費(核心代碼)
        double fee = 0.0;
        int days = 0, hour = 0;
        start.add(Calendar.MINUTE, freeMinute); //開始時間修正(加上免費時間)
        if (!start.before(end)) { //如果在免費區間
            return fee;
        }
        for (; start.before(end); start.add(Calendar.DATE, 1)) { //【重點3】:算出滿整天的日數
            days++;
        }
        if (start.after(end)) { //【重點4】:如果算出跨天后的時間大于結束時間,則說明最后一次跨天計算不滿一天
            start.add(Calendar.DATE, -1); //所以要回退一天,按小時來計算
            days--;
            hour = start.get(Calendar.HOUR_OF_DAY); //取出開始時間
            if (start.get(Calendar.MINUTE) == 0
                    && start.get(Calendar.SECOND) == 0
                    && start.get(Calendar.MILLISECOND) == 0) { //如果開始時間剛為整點小時數
                hour++; //則修正計費基準為下一小時(因為計時區間是(開始時間,結束時間],不包含整點的開始時間,所以修正為下一小時,確保在計時區間內)
            } else { //否則修正時間為整點小時數
                start.add(Calendar.HOUR, 1); //即把小時進位
                start.set(Calendar.MINUTE, 0); //分鐘以下清0
                start.set(Calendar.SECOND, 0);
                start.set(Calendar.MILLISECOND, 0);
            }
            fee += getParkPrice(hour); //【重點5】:計算第1小時的費用(放在這里計算是為了避免不滿1小時而不進入for回圈的情況)
            start.add(Calendar.HOUR, 1); //計費后時間累加1小時
            for (; !start.after(end); start.add(Calendar.HOUR, 1)) { //【重點6】:回圈時間,累加每小時的費用
                hour = start.get(Calendar.HOUR_OF_DAY);
                fee += getParkPrice(hour); //【重點7】:如果收費編號6按分鐘收費,可以改善這里
            }
        }
        fee += days * maxFeePreDay; //【重點8】:最后加上滿1整天的最大停車費用
        return fee;
    }

    public static void main(String[] args) {
        try {
            ParkFeeSimulator ps = new ParkFeeSimulator(15, 120);
            ps.listParkPrice();
            System.out.printf("模擬停車小例子\n");
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            /*
            // 從控制臺輸入資料的情況
            Scanner sc = new Scanner(System.in);
            System.out.printf("請輸入開始時間(格式: yyyyMMddHHmmss):");
            String str = sc.nextLine();
            c1.setTime(sdf.parse(str));
            System.out.printf("請輸入結束時間(格式: yyyyMMddHHmmss):");
            str = sc.nextLine();
            c2.setTime(sdf.parse(str));
            */
            String[][] testData = { //測驗資料
                    {"20200401100001", "20200403180000"},
                    {"20200401110001", "20200401120000"},
                    {"20200401114501", "20200401120001"},//這個邊界資料,這個算不算免費區間?
                    {"20200401114500", "20200401120001"},//還是這個才算免費區間?根據需求自行修改caculatePartFee方法
                    {"20200331234501", "20200401240000"},//這兩個邊界資料,這個算不算24小時滿1整天?
                    {"20200331234500", "20200401240000"} //還是這個才算24小時滿一整天?根據需求自行修改caculatePartFee方法
            };
            for (int i=0; i<testData.length; i++) {
                c1.setTime(sdf.parse(testData[i][0]));
                c2.setTime(sdf.parse(testData[i][1]));
                System.out.printf("開始時間: %tF %tT\n結束時間: %tF %tT\n", c1.getTime(), c1.getTime(), c2.getTime(), c2.getTime());
                System.out.printf("總停車費: %.0f\n", ps.caculatePartFee(c1, c2));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

uj5u.com熱心網友回復:

三樓的代碼的 3.功能實作類CountCost.java有點BUG,以本樓的代碼為準!
還是按順序來操作吧,注意包名哈!
1.定義一個物體類
package com.paullbm.timingcost.entity;

/**
 * @author paullbm
 */
public class PriceItem {
private int no;
private int start;
private int end;
private int price;

public PriceItem(int no, int start, int end, int price) {
this.no = no;
this.start = start;
this.end = end;
this.price = price;
}

public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append("no=").append(no);
sb.append(",start=").append(start);
sb.append(",end=").append(end);
sb.append(",price=").append(price);
sb.append("]");
return sb.toString();
}

public int getStart() {
return start;
}

public int getEnd() {
return end;
}

public int getPrice() {
return price;
}
}

2.定義一個介面
package com.paullbm.timingcost;


/**
 * @author paullbm
 */
public interface ICountCost {

//獲取總價
public int getTotalPrice();

}

3.定義一個功能實作類
package com.paullbm.timingcost.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.paullbm.timingcost.ICountCost;
import com.paullbm.timingcost.entity.PriceItem;


/**
 * @author paullbm
 */
public class CountCost implements ICountCost {
private int freeTimeSecond = 15 * 60; // 15分鐘免費時間(秒數)
private int oneDayLimitCost = 120; // 1天的封頂費用

private int oneHourSecond = 60 * 60; // 1小時包含的秒數
private long oneDaySecond = 24 * oneHourSecond; // =86400秒
private long east8ZoneSecond = 8 * oneHourSecond; // 東八區附加秒數

private int[][] listPrices = {
{ 1, 0, 5, 2 },
{ 2, 5, 7, 10 },
{ 3, 7, 12, 6 },
{ 4, 12, 14, 10 },
{ 5, 14, 18, 2 },
{ 6, 18, 19, 1 },
{ 7, 19, 21, 20 },
{ 8, 21, 24, 6 }
};
private String fmtDateStr="yyyy-MM-dd HH:mm:ss";
private ArrayList<PriceItem> itemList = new ArrayList<PriceItem>();
private Date startDate;
private Date endDate;

public CountCost(String startTime, String endTime) {
Date startDate = null;
Date endDate = null;
SimpleDateFormat simdate = new SimpleDateFormat(this.fmtDateStr);
try {
startDate = simdate.parse(startTime);
endDate = simdate.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}

this.init(startDate, endDate);
}

public CountCost(Date startDate, Date endDate) {
this.init(startDate, endDate);
}

private void init(Date startDate, Date endDate) {
this.startDate = startDate;
this.endDate = endDate;

for (int i = 0; i < 8; i++) {
PriceItem struct = new PriceItem(
this.listPrices[i][0],
this.listPrices[i][1] * this.oneHourSecond,
this.listPrices[i][2] * this.oneHourSecond,
this.listPrices[i][3]);
this.itemList.add(i, struct);
}
}

@Override
public int getTotalPrice() {
long startTimeSecond = this.startDate.getTime() / 1000;
long endTimeSecond = this.endDate.getTime() / 1000;

if (isFreeTime(startTimeSecond, endTimeSecond)) // 如果是免費時間內
return 0;

int totalPrice = 0;
int limitCost=getLimitCost(startTimeSecond, endTimeSecond);
int normalCost = getWithin1DayCost(startTimeSecond, endTimeSecond);
totalPrice += (limitCost+normalCost);
System.out.println("封頂消費="+limitCost + "元");
System.out.println("普通消費="+normalCost + "元");
return totalPrice;
}

// 判斷是否是在免費時間范圍內
private boolean isFreeTime(long startTimeSecond, long endTimeSecond) {
long timeDiff = endTimeSecond - startTimeSecond;
if (timeDiff <= freeTimeSecond)
return true;
return false;
}

// 計算封頂費用
private int getLimitCost(long startTimeSecond, long endTimeSecond) {
int limitPrice = 0;
while (true) {
if (endTimeSecond - startTimeSecond >= oneDaySecond) {
limitPrice += oneDayLimitCost;
startTimeSecond += oneDaySecond;
} else {
break;
}
}
return limitPrice;
}

//計算1天以內的小時數的消費金額(要注意跨天問題)
private int getWithin1DayCost(long startTimeSecond, long endTimeSecond) {
int normalPrice = 0;
long relativeStartTimeSecond = (startTimeSecond + east8ZoneSecond) % oneDaySecond
+ freeTimeSecond;  //東八區調整再累加免費時長
long relativeEndTimeSecond = (endTimeSecond + east8ZoneSecond) % oneDaySecond;
if (relativeEndTimeSecond < relativeStartTimeSecond) {
//考慮跨天問題,相對結束時間則需要累加1天
relativeEndTimeSecond += oneDaySecond;
}

long offsetTimeSecond = oneHourSecond - (relativeStartTimeSecond % oneHourSecond) + 1; // 計算時間偏移量
boolean isFirst = true;

int index = 0;
int size=itemList.size();
while (relativeStartTimeSecond < relativeEndTimeSecond) {
while(index < size) {
if(relativeStartTimeSecond >= relativeEndTimeSecond)
break;
PriceItem item = itemList.get(index);
if (relativeStartTimeSecond > item.getStart()
&& relativeStartTimeSecond < item.getEnd()) {
normalPrice += item.getPrice();
if (isFirst) { // 首次要添加時間偏移量
relativeStartTimeSecond += offsetTimeSecond;
isFirst = false;
} else { // 之后可進行整小時添加
relativeStartTimeSecond += oneHourSecond;
}

System.out.print(item + ", 階段性累計消費=" + normalPrice + "元\n");
// System.out.println(", relativeStartTimeSecond=" + relativeStartTimeSecond
// + ", relativeEndTimeSecond=" + relativeEndTimeSecond);
}else{
if(relativeStartTimeSecond > item.getEnd())
index++;
}
}

if (relativeEndTimeSecond > oneDaySecond) {
//如果按條件迭代完this.itemList還能進入此處
//說明存在跨天情況,則需要進行相關調整
relativeStartTimeSecond = 1;
relativeEndTimeSecond -= oneDaySecond;
index = 0;
}
}

return normalPrice;
}
}

4.測驗類
package com.paullbm.timingcost.test;

import com.paullbm.timingcost.ICountCost;
import com.paullbm.timingcost.impl.CountCost;


/**
 * @author paullbm
 */
public class CountCostTest {
public static void main(String[] args) {
String startTime = "2020-04-01 18:00:01";
String endTime = "2020-04-03 10:00:00";
// String startTime = "2020-04-01 10:15:01";
// String endTime = "2020-04-01 17:00:02";
ICountCost cc = new CountCost(startTime, endTime);
int totalPrice = cc.getTotalPrice();
System.out.println("總消費金額=" + totalPrice+ "元");
}
}

uj5u.com熱心網友回復:

這道題看似不難,其實里面暗藏了很多需要注意的地方。我的程式注釋非常清楚,請看程式吧
FareRule.java 計費規則類及設定計費規則類
package 停車場計費;
//FareRule是計費時段的計費規則的類

public class FareRule {
    private int begin;      //計費段起始小時
    private int end;        //計費段結束小時
    private int unitPrice;  //計費單價
    int minute;//0:按小時計費;1:按分鐘計費;2:表示該計費規則結束且本條規則也無效

    public FareRule() {
    }
    public FareRule(int begin, int end, int unitPrice, int minute) {
        this.begin = begin;
        this.end = end;
        this.unitPrice = unitPrice;
        this.minute = minute;
    }
    public int getBegin() {
        return begin;
    }
    public void setBegin(int begin) {
        this.begin = begin;
    }
    public int getEnd() {
        return end;
    }
    public void setEnd(int end) {
        this.end = end;
    }
    public int getUnitPrice() {
        return unitPrice;
    }
    public void setUnitPrice(int unitPrice) {
        this.unitPrice = unitPrice;
    }
    public int isMinute() {
        return minute;
    }
    public void setMinute(int minute) {
        this.minute = minute;
    }
}

//SetFareRule是設定計費規則的類,根據你的題目要求:“時間段計費規則可能調整”

class SetFareRule {//設定規則
    static FareRule[] rules  = {//題目要求的計費規則
            new FareRule(0, 5, 2, 0),
            new FareRule(5, 7, 10, 0),
            new FareRule(7, 12, 6, 0),
            new FareRule(12, 14, 10, 0),
            new FareRule(14, 18, 2, 0),
            new FareRule(18, 19, 1, 1),
            new FareRule(19, 21, 20, 0),
            new FareRule(21, 24, 6, 0),
            new FareRule(0,0,0,3),
    };

    public static void setRule(FareRule rule,int index) {//用于修改1條規則
        rules[index] = rule;
    }
    //默認設定,一天24小時,每小時一個時段,清零為下面設定規則準備容器。
    public void setRules() {
        rules  = new FareRule[24];
        for(int i=0;i<24;i++) {
            rules[i] = new FareRule();
        }
    }
    //修改多條規則
    public static void setRules(FareRule[] rs,int beginIdex,int num) {
        for(int i=0;i<num;i++) {
            rules[beginIdex+i]=rs[i];
        }
    }
    public static void showPriceList() { //列印收費表
        System.out.printf("停車收費價格表\n");
        for (int i=0; i<rules.length; i++) {
            if(rules[i].minute==1)
                System.out.printf("%d\t%d點——%d點%d元/分鐘\n",
                        i+1, rules[i].getBegin(),rules[i].getEnd(),
                        rules[i].getUnitPrice());
            else System.out.printf("%d\t%d點——%d點%d元/小時\n",
                    i+1, rules[i].getBegin(),rules[i].getEnd(),
                    rules[i].getUnitPrice());
        }
    }
}


Fare.java:計費類

// Fare是計費類
//停車場計費:計費起始時間=(入場時間-免費時間)
//停車超過1年則:計費天數=年數*365;
//(剩余)不滿1年:計費天數+=(剩余)天數;
//(剩余)不滿24小時,則按時段進行計費。

package 停車場計費;

import java.util.Calendar;

public class Fare {
    Calendar enterTime;     //入場時間
    Calendar begin = Calendar.getInstance();//階段起始時間
    Calendar fareBegin;     //計費起始時間
    Calendar now = Calendar.getInstance();//汽車出場時間取當前時間
    private int freeMinute; //免費時間
    private double maxFarePreDay; //1日最大費用
    public Fare(int freeMinute, double maxFarePreDay) {
        this.freeMinute = freeMinute;
        this.maxFarePreDay = maxFarePreDay;
    }
    public Calendar getEnterTime() {
        return enterTime;
    }
    public void setEnterTime(Calendar enterTime) {
        this.enterTime = enterTime;
    }
    public int getFreeMinute() {
        return freeMinute;
    }
    public void setFreeMinute(int freeMinute) { //根據題目要求這個可變
        this.freeMinute = freeMinute;
    }
    public double getMaxFarePreDay() {
        return maxFarePreDay;
    }
    public void setMaxFareDay(double maxFarePreDay) { //根據題目要求這個可變
        this.maxFarePreDay = maxFarePreDay;
    }
    public void listParkPrice() { //列印收費表
        System.out.printf("停車收費價格表\n");
        for (int i=0; i<SetFareRule.rules.length; i++) {
            if(SetFareRule.rules[i].minute==2) break;
            System.out.printf("%d %s\n", i+1, SetFareRule.rules[i]);
        }
    }

    Calendar getBegin() {//獲取計費起始時間=入場時間+免費時間
        fareBegin = Calendar.getInstance();
        fareBegin.setTimeInMillis(enterTime.getTimeInMillis()+freeMinute*60*1000);
        return fareBegin;
    }

    protected double getPrice() {//計費
        int day=0;  //停車天數
        int year=0; //停車年數
        double price=0;
        /*下面是準備作業*/
        getBegin(); //獲取計費起始時間
        fareBegin.set(Calendar.SECOND,0);   //秒不計費,所以計費起始清零
        now.set(Calendar.SECOND,0);     //出場時間秒也清零
        begin.setTimeInMillis(fareBegin.getTimeInMillis()); //初始化階段計費起始時間

        if(begin.getTimeInMillis()>now.getTimeInMillis())
            return price;   //如果在免費時間段內則收費為0
        year=(now.get(Calendar.YEAR) - begin.get(Calendar.YEAR));
        if(year>0) {//如果停車超過1年,則停車天數+=年數*365
            day = year * 365;
            begin.set(Calendar.YEAR,begin.get(Calendar.YEAR)+year);
        }
        //如果停車未超過1年,則停車天數+=天數
        day+=now.get(Calendar.DAY_OF_YEAR)-begin.get(Calendar.DAY_OF_YEAR);
        price+=day*maxFarePreDay;   //計算按天收費的收費值
        //下面是通過查詢計費時段規則表(陣列)按時段計算收費值
        for (FareRule rule : SetFareRule.rules) {
            switch (rule.minute) {
                case 0: //按小時計費
                    if (begin.get(Calendar.HOUR_OF_DAY) >= rule.getBegin() &&
                        begin.get(Calendar.HOUR_OF_DAY) <= rule.getEnd()) {
                        if(now.get(Calendar.HOUR_OF_DAY)>=rule.getEnd())
                            price += (rule.getEnd()-begin.get(Calendar.HOUR_OF_DAY)) * rule.getUnitPrice();
                        else if(begin.get(Calendar.MINUTE)==now.get(Calendar.MINUTE))
                            price+= (now.get(Calendar.HOUR_OF_DAY)-begin.get(Calendar.HOUR_OF_DAY))*rule.getUnitPrice();
                        else
                            price+= (now.get(Calendar.HOUR_OF_DAY)-begin.get(Calendar.HOUR_OF_DAY)+1)*rule.getUnitPrice();
                        begin.set(Calendar.HOUR_OF_DAY,rule.getEnd());
                    }
                    break;
                case 1: //按分鐘計費
                    if (begin.get(Calendar.HOUR_OF_DAY) >= rule.getBegin() &&
                            begin.get(Calendar.HOUR_OF_DAY) <= rule.getEnd()) {
                        if (begin.getTimeInMillis() != fareBegin.getTimeInMillis())
                            begin.set(Calendar.MINUTE, 0);   //將begin分鐘清零
                        if (now.get(Calendar.HOUR_OF_DAY) >= rule.getEnd())
                            price += rule.getUnitPrice() * (rule.getEnd() - rule.getBegin()) * 60;
                        else price += (now.get(Calendar.MINUTE) - begin.get(Calendar.MINUTE)) * rule.getUnitPrice();
                        begin.set(Calendar.HOUR_OF_DAY, rule.getEnd()); //更新階段計費起始時間
                        begin.set(Calendar.MINUTE, 0);   //已經按分鐘計費了,則分鐘數清零
                    }
                    break;
            }
            if(begin.getTimeInMillis()>=now.getTimeInMillis()) break;//計費完成
        }
        return price;
    }
}


ParkFare.java 應用源檔案

package 停車場計費;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class ParkFare {//模擬停車計費主類
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //新進場了一輛車
        Fare car = new Fare(15,120.0);
        SetFareRule.showPriceList();    //輸出停車場收費價目表
        try {
            System.out.printf("模擬停車\n");
            Calendar c1 = Calendar.getInstance();
            String[] testData = { //測驗資料,汽車入場時間
                    "20200411184501", "20200411180000",
                    "20200412151501", "20200412190000",
                    "20200411114501", "20200411100001",
                    "20200411114500", "20200411120001",
                    "20200410234501", "20200411240000",
                    "20200411214500", "20200411220000"};
            for (int i=0; i<testData.length; i++) {
                c1.setTime(sdf.parse(testData[i]));
                car.setEnterTime(c1);   //設定汽車入場時間
                System.out.printf("開始時間: %tF %tT\n結束時間: %tF %tT\n",
                        c1.getTime(), c1.getTime(), car.now.getTime(), car.now.getTime());
                System.out.printf("總停車費: %.0f\n", car.getPrice());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

uj5u.com熱心網友回復:

運行結果:

停車收費價格表
1 0點——5點2元/小時
2 5點——7點10元/小時
3 7點——12點6元/小時
4 12點——14點10元/小時
5 14點——18點2元/小時
6 18點——19點1元/分鐘
7 19點——21點20元/小時
8 21點——24點6元/小時
9 0點——0點0元/小時
模擬停車
開始時間: 2020-04-11 18:45:01
結束時間: 2020-04-12 00:23:58
總停車費: -337
開始時間: 2020-04-11 18:00:00
結束時間: 2020-04-12 00:23:00
總停車費: -386
開始時間: 2020-04-12 15:15:01
結束時間: 2020-04-12 00:23:00
總停車費: 0
開始時間: 2020-04-12 19:00:00
結束時間: 2020-04-12 00:23:00
總停車費: 0
開始時間: 2020-04-11 11:45:01
結束時間: 2020-04-12 00:23:00
總停車費: -539
開始時間: 2020-04-11 10:00:01
結束時間: 2020-04-12 00:23:00
總停車費: -527
開始時間: 2020-04-11 11:45:00
結束時間: 2020-04-12 00:23:00
總停車費: -539
開始時間: 2020-04-11 12:00:01
結束時間: 2020-04-12 00:23:00
總停車費: -539
開始時間: 2020-04-10 23:45:01
結束時間: 2020-04-12 00:23:00
總停車費: -547
開始時間: 2020-04-12 00:00:00
結束時間: 2020-04-12 00:23:00
總停車費: 2
開始時間: 2020-04-11 21:45:00
結束時間: 2020-04-12 00:23:00
總停車費: -6
開始時間: 2020-04-11 22:00:00
結束時間: 2020-04-12 00:23:00
總停車費: -6

Process finished with exit code 0

uj5u.com熱心網友回復:

昨天發的貼子程式有問題,沒有考慮到跨0點的情況,后來想到一個解題方法:把24小時內計費規則細化為24個時段,每小時一個計費時段。然后計費從入場的小時為起點:回圈根據計費規則進行計費,一直到出場為止。利用[i%rules.length解決了回環(跨0點)問題
for (int i=fareBegin.get(Calendar.HOUR_OF_DAY);i<(rules.length+fareBegin.get(Calendar.HOUR_OF_DAY));i++) {
       rules[i%rules.length]    //這樣解決了回環(跨0點)問題
}
這樣終于對于很多測驗用例得結果都正確了。
FareRule.java包括:FareRule類:計費規則類;SetFareRule類:設定計費規則類

import exception.IndexException;

// FareRule是計費時段的計費規則的類

public class FareRule {
    public static final int MINUTE=1;
    private int begin;      //計費段起始小時
    private int end;        //計費段結束小時
    private int unitPrice;  //計費單價
    int minute;//0:按小時計費;1:按分鐘計費。

    public FareRule() {
    }
    public FareRule(int begin, int end, int unitPrice, int minute) {
        this.begin = begin;
        this.end = end;
        this.unitPrice = unitPrice;
        this.minute = minute;
    }
    public int getBegin() {
        return begin;
    }
    public void setBegin(int begin) {
        this.begin = begin;
    }
    public int getEnd() {
        return end;
    }
    public void setEnd(int end) {
        this.end = end;
    }
    public int getUnitPrice() {
        return unitPrice;
    }
    public void setUnitPrice(int unitPrice) {
        this.unitPrice = unitPrice;
    }
    public boolean isMinute() {
        if(minute==MINUTE) return true;
        return false;
    }
    public void setMinute(int minute) {
        this.minute = minute;
    }
}

// SetFareRule是設定計費規則的類,根據你的題目要求:“時間段計費規則可能調整”
class SetFareRule {//設定規則
    public static final int INIRULE=0;
    public static final int RULE=1;
    //題目要求的計費規則,為初始規則表,為了程式便于處理,將被轉換為按每小時分段規則:rules[]
    static FareRule[] iniRules  = {
            new FareRule(0, 5, 2, 0),
            new FareRule(5, 7, 10, 0),
            new FareRule(7, 12, 6, 0),
            new FareRule(12, 14, 10, 0),
            new FareRule(14, 18, 2, 0),
            new FareRule(18, 19, 1, 1),
            new FareRule(19, 21, 20, 0),
            new FareRule(21, 24, 6, 0),
    };
    //每小時分段計費規則表
    static FareRule[] rules;

    public static void setRule(FareRule rule,int index) {//用于修改1條規則
        rules[index] = rule;
    }
    //默認設定,一天24小時,每小時一個時段,清零為下面設定規則準備容器。
    public static void setRules(int num) {
        rules  = new FareRule[num];
        for(int i=0;i<num;i++) {
            rules[i] = new FareRule();
        }
    }
    //初始化規則表rules[]
    public static void iniRules(){
        setRules(24);
        for(FareRule rule: iniRules) {
            for(int i=rule.getBegin();i<rule.getEnd();i++) {
                rules[i].setBegin(i);
                rules[i].setEnd(i+1);
                rules[i].setUnitPrice(rule.getUnitPrice());
                rules[i].minute = rule.minute;
            }
        }
    }
    //修改多條規則
    public static void setRules(FareRule[] rs,int beginIdex,int num,int rsType) throws IndexException{
        if(beginIdex<0) throw new IndexException(beginIdex);
        if (rsType==INIRULE) {
            for (int i = 0; i < num; i++) {
                iniRules[beginIdex + i] = rs[i];
            }
        } else {
            for (int i = 0; i < num; i++) {
                rules[beginIdex + i] = rs[i];
            }
        }
    }
    public static void showPriceList() { //列印收費表
        System.out.printf("停車收費價格表\n");
        for (int i=0; i<rules.length; i++) {
            if(rules[i].minute==1)
                System.out.printf("%d\t%d點——%d點%d元/分鐘\n",
                        i+1, rules[i].getBegin(),rules[i].getEnd(),
                        rules[i].getUnitPrice());
            else System.out.printf("%d\t%d點——%d點%d元/小時\n",
                    i+1, rules[i].getBegin(),rules[i].getEnd(),
                    rules[i].getUnitPrice());
        }
    }
}

Fare.java是Fare類:計費類的源檔案

//Fare是計費類
//停車場計費:計費起始時間=(入場時間-免費時間)
//停車超過1年則:計費天數=年數*365;
//(剩余)不滿1年:計費天數+=(剩余)天數;
//(剩余)不滿24小時,則按時段進行計費。

import java.util.Calendar;

public class Fare {
    Calendar enterTime;     //入場時間
    Calendar begin = Calendar.getInstance();//時段起始時間
    Calendar fareBegin;     //計費起始時間
    Calendar now = Calendar.getInstance();//汽車出場時間取當前時間
    private int freeMinute; //免費時間
    private double maxFarePreDay; //1日最大費用
    public Fare(int freeMinute, double maxFarePreDay) {
        this.freeMinute = freeMinute;
        this.maxFarePreDay = maxFarePreDay;
    }
    public Calendar getEnterTime() {
        return enterTime;
    }
    public void setEnterTime(Calendar enterTime) {
        this.enterTime = enterTime;
    }
    public int getFreeMinute() {
        return freeMinute;
    }
    public void setFreeMinute(int freeMinute) { //根據題目要求這個可變
        this.freeMinute = freeMinute;
    }
    public double getMaxFarePreDay() {
        return maxFarePreDay;
    }
    public void setMaxFareDay(double maxFarePreDay) { //根據題目要求這個可變
        this.maxFarePreDay = maxFarePreDay;
    }
    public void listParkPrice() { //列印收費表
        System.out.printf("停車收費價格表\n");
        for (int i=0; i<SetFareRule.rules.length; i++) {
            if(SetFareRule.rules[i].minute==2) break;
            System.out.printf("%d %s\n", i+1, SetFareRule.rules[i]);
        }
    }

    Calendar getBegin() {//獲取計費起始時間=入場時間+免費時間
        fareBegin = Calendar.getInstance();
        fareBegin.setTimeInMillis(enterTime.getTimeInMillis()+freeMinute*60*1000);
        return fareBegin;
    }

    protected double getPrice() {//計費
        int day=0;  //停車天數
        int year=0; //停車年數
        double price=0; //總停車費
        double price24=0;   //(剩余)不滿24小時停車費,如果該費用超過日封頂停車費,則計封頂停車費
        /*下面是準備作業*/
        getBegin(); //獲取計費起始時間
        now.set(Calendar.SECOND,0);     //出場時間秒也清零

        if(fareBegin.getTimeInMillis()>now.getTimeInMillis())
            return price;   //如果在免費時間段內則收費為0
        year=(now.get(Calendar.YEAR) - fareBegin.get(Calendar.YEAR));
        if(year>0) {//如果停車超過1年,則停車天數+=年數*365
            day = year * 365;
            fareBegin.set(Calendar.YEAR,fareBegin.get(Calendar.YEAR)+year);
        }
        //如果停車未超過1年,則停車天數+=天數
        day+=now.get(Calendar.DAY_OF_YEAR)-fareBegin.get(Calendar.DAY_OF_YEAR);
        //時間需要考慮跨0點的情況
        if(fareBegin.get(Calendar.HOUR_OF_DAY)>now.get(Calendar.HOUR_OF_DAY)) day--;
        price+=day*maxFarePreDay;   //計算按天收費的收費值
        //下面是通過查詢計費時段規則表(陣列)按時段計算收費值
        FareRule[] rules = SetFareRule.rules;   //宣告一個區域變數指向計費規則表
        begin.setTimeInMillis(fareBegin.getTimeInMillis()); //初始化時段計費起始時間
        for (int i=fareBegin.get(Calendar.HOUR_OF_DAY);i<(rules.length+fareBegin.get(Calendar.HOUR_OF_DAY));i++) {
            //利用i%rules.length解決了回環(跨0點)問題
            switch (rules[i%rules.length].minute) {
                case 0: //按小時計費
                    price24 += rules[i%rules.length].getUnitPrice();
                    //跟新計費起始時段
                    begin.set(Calendar.HOUR_OF_DAY, begin.get(Calendar.HOUR_OF_DAY) + 1);
                    break;
                case 1: //按分鐘計費
                    if (begin.get(Calendar.HOUR_OF_DAY) == rules[i%rules.length].getBegin()) {
                        if (now.get(Calendar.HOUR_OF_DAY) >= rules[i%rules.length].getEnd()) {
                            price24 += rules[i%rules.length].getUnitPrice() * 60;
                            //跟新計費起始時段
                            begin.set(Calendar.HOUR_OF_DAY,begin.get(Calendar.HOUR_OF_DAY)+1);
                        }
                        else {
                            price24 += now.get(Calendar.MINUTE) * rules[i%rules.length].getUnitPrice();
                            begin.setTimeInMillis(now.getTimeInMillis());
                        }
                    }
                    break;
            }
            if(begin.getTimeInMillis()>=now.getTimeInMillis()) break;//計費完成
        }
        if(price24>maxFarePreDay) price+=maxFarePreDay;
        else price+=price24;
        return price;
    }
}

ParkFare.java檔案包括:ParkFare類,這個是計費應用(測驗)類

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class ParkFare {//模擬停車計費主類
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //新進場了一輛車
        Fare car = new Fare(15,120.0);
        SetFareRule.iniRules();         //初始化規則表
        //SetFareRule.showPriceList();    //輸出停車場收費價目表
        try {
            System.out.printf("模擬停車\n");
            Calendar c1 = Calendar.getInstance();
            String[] testData = { //測驗資料,汽車入場時間
                    "20200412124501", "2020041220000",
                    "20200412151501", "20200412190000",
                    "20200412114501", "20200412100001",
                    "20200412164500", "20200412120001",
                    "20200410234501", "20200412240000",
                    "20200412211500", "20200412203000"};
            for (int i=0; i<testData.length; i++) {
                c1.setTime(sdf.parse(testData[i]));
                car.setEnterTime(c1);   //設定汽車入場時間
                System.out.printf("開始時間: %tF %tT\t結束時間: %tF %tT\t",
                        c1.getTime(), c1.getTime(), car.now.getTime(), car.now.getTime());
                System.out.printf("總停車費: %.0f\n", car.getPrice());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/93187.html

標籤:Java SE

上一篇:通配符捕獲究竟是干什么用的?既然有個swapHelper為什么還要用swap去呼叫swapHelper?

下一篇:JAVA JFrame和Frame在使用CardLayout的next()方法時出現的疑問

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more