第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

計(jì)算平均所需的整數(shù)序列,等于定義的雙精度

計(jì)算平均所需的整數(shù)序列,等于定義的雙精度

回首憶惘然 2022-09-14 17:37:28
你好!我正在嘗試制作一個(gè)Java程序來從給定的數(shù)組生成一系列整數(shù),使得所選整數(shù)的平均值等于用戶定義的雙精度值?,F(xiàn)在,假設(shè)用戶將目標(biāo)定義為 46.00。ArrayList<Integer> usableItems = new ArrayList<>();在這里,用戶指定數(shù)組的大小和每個(gè)整數(shù)。喜歡這個(gè)。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;     }}比方說,這是指定的數(shù)組:[20,25,30,35,50]所以,它現(xiàn)在應(yīng)該處理,以便我得到這個(gè)輸出:Specified target = 46.00Series = 50,50,50,50,30由于上述輸出序列的平均值等于 46。序列中的整數(shù)數(shù)(即 5)不必等于可用項(xiàng)的大小。我試圖找到一個(gè)準(zhǔn)確的算法,但我不明白它是如何做到的。任何幫助/建議都值得贊賞!
查看完整描述

1 回答

?
滄海一幻覺

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊

暴力遞歸實(shí)現(xiàn)返回最短的可能序列:


public List<Integer> matchAverage(double target, List<Integer> items) {

    for (int i = 1; i <= 50; i++) { // arbitrary limit of 50

        List<Integer> match = matchAverage(target, items, new ArrayList<>(), 0, i);

        if (match != null) return match;

    }

    throw new RuntimeException("Average not found.");

}


private List<Integer> matchAverage(double target, List<Integer> items, List<Integer> selected, int sum, int left) {

    for (int i = 0; i < items.size(); i++) {

        Integer item = items.get(i);

        selected.add(item);

        sum += item;

        if (left == 1) {

            if (sum / (double) selected.size() == target) {

                return selected;

            }

        } else {

            List<Integer> match = matchAverage(target, items.subList(i, items.size()), selected, sum, left - 1);

            if (match != null) return match;

        }

        sum -= item;

        selected.remove(selected.size() - 1);

    }

    return null;

}

通過僅檢查使您更接近目標(biāo)的項(xiàng)目,您可以更快地做到這一點(diǎn)。


查看完整回答
反對(duì) 回復(fù) 2022-09-14
  • 1 回答
  • 0 關(guān)注
  • 120 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)