![](/img/trans.png)
[英]Java: algorithm to obtain all combinations of pairs of an array of strings not inverted
[英]Algorithm for all combinations of an Array of doubles with sum equal to 2 in Java
stackoverflow 的好人,我正在嘗試實現一種算法,該算法對於固定的給定雙精度數組(即 [1.0, 0.5, 0.25] 給出所有可能的組合,例如 1.0。在這種情況下,輸出應該看起來喜歡:
1.0
0.5 0.5
0.5 0.25 0.25
0.25 0.25 0.25 0.25
0.25 0.25 0.5
0.25 0.5 0.25
我試圖用兩個嵌套的 for 循環來實現這一點,但無法弄清楚。 任何幫助將不勝感激。
到目前為止,這是我可恥的嘗試:
private double[] a = {1, 0.5, 0.25};
private double max = 1;
private String as;
private double help;
private boolean done;
public void comb()
{
for (var i = 0; i < a.length; i++)
{
for (var j = 0; j < a.length; j++)
{
as ="";
help = 0;
while (help < max)
{
if(help + a[i] <= max)
{
as += a[i] + " ";
help += a[i];
}
/*else if (help + a[j] <= max)
{
ausdruck += a[j] + " ";
help += a[j];
}*/
}
System.out.println(as);
}
}
}
謝謝
您可以使用遞歸解決此問題。 以下是我的方法和一些解釋:
public class Main {
public static void main(String[] args) {
double[] a = {1, 0.5, 0.25};
double max = 1;
//pass the array, target value and an empty list to the method
comb(a, max, new ArrayList<>());
}
public static void comb(double[] a, double max, List<Double> scores) {
//sum the numbers included in the list
double scoresSum = scores.stream().reduce(0.0, Double::sum);
//print the list if the sum of numbers in the list equals target value
if (scoresSum == max) {
System.out.println(scores);
} else if (scoresSum > max) {
//stop the method if the sum of numbers in the list is larger than the target value
} else {
//if the sum of numbers in the list is smaller than the target value, for each value from the array:
//- create copy of the list
//- add the value
//- run the method passing the updated list as an argument
for (double v : a) {
List<Double> scoresPlusOne = new ArrayList<>(scores);
scoresPlusOne.add(v);
comb(a, max, scoresPlusOne);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.