计算平均所需的整数序列,等于定义的双精度

你好!我正在尝试制作一个Java程序来从给定的数组生成一系列整数,使得所选整数的平均值等于用户定义的双精度值。


现在,假设用户将目标定义为 46.00。


ArrayList<Integer> usableItems = new ArrayList<>();

在这里,用户指定数组的大小和每个整数。喜欢这个。


System.out.println("Enter number of elements of usable integers: ");

int siz=0;

siz = Integer.parseInt(in.nextLine());

ArrayList<Integer> usableItems = new ArrayList<>();

for (int i=0 ; i<siz ; i++)

{

     try {

          int j = i+1;

          System.out.println("Enter element "+j+": ");

          usableItems.add(Integer.parseInt(in.nextLine()));

     } catch (Exception e)

     {

          System.out.println(e.getMessage());

          break;

     }

}

比方说,这是指定的数组:


[20,25,30,35,50]

所以,它现在应该处理,以便我得到这个输出:


Specified target = 46.00

Series = 50,50,50,50,30

由于上述输出序列的平均值等于 46。序列中的整数数(即 5)不必等于可用项的大小。


我试图找到一个准确的算法,但我不明白它是如何做到的。


任何帮助/建议都值得赞赏!


回首忆惘然
浏览 96回答 1
1回答

沧海一幻觉

暴力递归实现返回最短的可能序列:public List<Integer> matchAverage(double target, List<Integer> items) {&nbsp; &nbsp; for (int i = 1; i <= 50; i++) { // arbitrary limit of 50&nbsp; &nbsp; &nbsp; &nbsp; List<Integer> match = matchAverage(target, items, new ArrayList<>(), 0, i);&nbsp; &nbsp; &nbsp; &nbsp; if (match != null) return match;&nbsp; &nbsp; }&nbsp; &nbsp; throw new RuntimeException("Average not found.");}private List<Integer> matchAverage(double target, List<Integer> items, List<Integer> selected, int sum, int left) {&nbsp; &nbsp; for (int i = 0; i < items.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; Integer item = items.get(i);&nbsp; &nbsp; &nbsp; &nbsp; selected.add(item);&nbsp; &nbsp; &nbsp; &nbsp; sum += item;&nbsp; &nbsp; &nbsp; &nbsp; if (left == 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (sum / (double) selected.size() == target) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return selected;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<Integer> match = matchAverage(target, items.subList(i, items.size()), selected, sum, left - 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (match != null) return match;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; sum -= item;&nbsp; &nbsp; &nbsp; &nbsp; selected.remove(selected.size() - 1);&nbsp; &nbsp; }&nbsp; &nbsp; return null;}通过仅检查使您更接近目标的项目,您可以更快地做到这一点。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java