java組合演算法應用:購物滿減(任意數字組合相加在某個範圍內)
阿新 • • 發佈:2018-12-30
任意價格相加在某個範圍內
package com.louisgeek.price;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class CaseTestPrice {
/**
* 用遞迴的思想來求排列跟組合 然後應用到滿減活動
*/
public static void main(String[] args) {
// 一堆書的價格
Object[] tmp = { 44.2, 56.8, 77.6, 88.9, 100.8, 110.6 };
// Object[] tmp = str.split(" ");
int minCount = 200;// 滿200
int maxCount = 220;// 自己認為的最大限制
int num = 0;
ArrayList<Object[]> rs = RandomC(tmp);
// ArrayList<Object[]> rs = cmn(tmp, 3);//3個的組合
// ArrayList<Object[]> rs = cmn(tmp, 4);//4個的組合
for (int i = 0; i < rs.size(); i++)
{
// System.out.print(i+"=");
Double countTemp = 0.0;
String strTemp = "";
for (int j = 0; j < rs.get(i).length; j++) {
countTemp = countTemp + Double.parseDouble(rs.get(i)[j].toString());
// System.out.print(rs.get(i)[j] + ",");
strTemp += rs.get(i)[j] + ",";
}
// System.out.println();
if (minCount < countTemp && countTemp <= maxCount) {
num++;
System.out.println("滿" + minCount + "減,方案" + num + ":" + countTemp + "\n組合是:" + strTemp + "\n");
}
}
}
// 求一個數組的任意組合
static ArrayList<Object[]> RandomC(Object[] source) {
ArrayList<Object[]> result = new ArrayList<Object[]>();
if (source.length == 1) {
result.add(source);
} else {
Object[] psource = new Object[source.length - 1];
for (int i = 0; i < psource.length; i++) {
psource[i] = source[i];
}
result = RandomC(psource);
int len = result.size();// fn組合的長度
result.add((new Object[] { source[source.length - 1] }));
for (int i = 0; i < len; i++) {
Object[] tmp = new Object[result.get(i).length + 1];
for (int j = 0; j < tmp.length - 1; j++) {
tmp[j] = result.get(i)[j];
}
tmp[tmp.length - 1] = source[source.length - 1];
result.add(tmp);
}
}
return result;
}
// 求指定長度的陣列任意組合
static ArrayList<Object[]> cmn(Object[] source, int n) {
ArrayList<Object[]> result = new ArrayList<Object[]>();
if (n == 1) {
for (int i = 0; i < source.length; i++) {
result.add(new Object[] { source[i] });
}
} else if (source.length == n) {
result.add(source);
} else {
Object[] psource = new Object[source.length - 1];
for (int i = 0; i < psource.length; i++) {
psource[i] = source[i];
}
result = cmn(psource, n);
ArrayList<Object[]> tmp = cmn(psource, n - 1);
for (int i = 0; i < tmp.size(); i++) {
Object[] rs = new Object[n];
for (int j = 0; j < n - 1; j++) {
rs[j] = tmp.get(i)[j];
}
rs[n - 1] = source[source.length - 1];
result.add(rs);
}
}
return result;
}
}
輸出:
滿200減,方案1:210.7
組合是:44.2,77.6,88.9,
滿200減,方案2:201.8
組合是:44.2,56.8,100.8,
滿200減,方案3:211.6
組合是:44.2,56.8,110.6,
滿200減,方案4:211.39999999999998
組合是:100.8,110.6,