1. 程式人生 > >阿里2018測評程式設計題——小明購物。。。

阿里2018測評程式設計題——小明購物。。。

以下是小編寫的程式碼,鑑於程式設計技巧笨拙,旨在和大家交流學習!!!

package scan.input;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ScanInput{

//記錄優惠資訊和商品資訊
static Map<Double, Double> map = new HashMap<Double,Double>();
static List<String> li = new ArrayList<String>();
//存放價格資訊
static String[] price =null;
//存放組合商品的價格之和
static List<String> totalValue = new ArrayList<String>();
static //存放最終花費的金額
double allPrice=0;

//遞迴計算所有組合的商品價格之和
private static void combine(){
int start=0;
int end=price.length;
for(int i=start;i<end;i++){
double tmp=Double.valueOf(price[i]).doubleValue();
totalValue.add(Double.toString(tmp));
//System.out.println("#########&&&&&&&"+tmp);
nextLi(++start,end,tmp);
}
}

private static void nextLi(int start, int end, double tmp){
for(int i=start;i<end;i++){
double allValue=tmp;
//System.out.println("&&&&&&&&"+tmp+price[i]);
allValue+=Double.valueOf(price[i]);

totalValue.add(Double.toString(allValue));
int empI=i;
nextLi(++empI,end,allValue);
}

}
//找出所購買商品的最大價值
static void goodsAllValue(){

Map<Double, Double> mapValue = new HashMap<Double,Double>();
/*for(String toVal:totalValue){
System.out.println("tolVal#######+"+toVal);
}*/
//計算出商品優惠後價格總額與參加的最合適的優惠資訊mapValue<所購商品優惠後價格總額,減去的優惠金額>
for(int i=0;i<totalValue.size();i++){

double maxKey=0;
double s=Double.valueOf(totalValue.get(i)).doubleValue();
//System.out.println("s@@@@@@="+totalValue.get(i));
for(Double key:map.keySet()){

//找出優惠資訊中最接近當前價格組合s的優惠資訊的key值
if(s>=key){
//System.out.println("s="+s+",map="+key);
if(key>maxKey){
maxKey=key;
}
}else continue;

}
if(maxKey!=0.0){
//System.out.println("最合適的優惠資訊key:"+maxKey);
double cutP=map.get(maxKey);
mapValue.put(s-cutP, cutP);
//System.out.println("!!!!!"+s+"@@@@@"+cutP);
}else continue;
//System.out.println("@@@@@@@");
//System.out.println("所有商品組合價格和分別為:"+totalValue.get(i));
}
double maxS=0;
//找出在限定花費金額條件下最高的原商品總額
for(Double key:mapValue.keySet()){
if(allPrice>=key){
double lastS=key+mapValue.get(key);
if(lastS>maxS){
maxS=lastS;
}
}else continue;
}
System.out.println("最大的商品價值為:"+maxS);

}



public static void main(String[] args){

Scanner scan=new Scanner(System.in);
System.out.println("請輸入商品總數:");
int goodsNum=scan.nextInt();
System.out.println("請輸入花費的金額總數:");
allPrice=scan.nextDouble();
System.out.println("請輸入優惠方式的總數");
int favNum =scan.nextInt();

//接收控制檯的輸入商品資訊
for(int i=0;i<goodsNum;i++){
int a=i+1;
System.out.println("請輸入商品"+a+"的價格:");
double goodsPrice=scan.nextDouble();
//map1.put(goodsName,goodsPrice);
li.add(Double.toString(goodsPrice));
}

//接收控制檯輸入的優惠資訊
for(int i=0;i<favNum;i++){
int a=i+1;
System.out.println("請輸入優惠方式"+a+"的滿減條件金額:");
double favStart=scan.nextDouble();
System.out.println("請輸入優惠方式"+a+"減去金額:");
double favCut=scan.nextDouble();
map.put(favStart, favCut);
}


//價格資料放到陣列中
price = new String[li.size()];
li.toArray(price);
//商品組合排序計算
combine();
//找出最大價值
goodsAllValue();


}


}