我有一個滑塊,讓用戶在 0 和 20000 之間選擇如何計算最終價格,每 100 點的價格如下:
from 0 to 1200 -> 2.10$/100pts
from 1200 to 2400 ->2.20$/100pts
from 2400 to 4800 ->2.5$/100pts
from 4800 to 7200 ->3.75$/100pts
from 7200 to 10000 ->5.4$/100pts
from 10000 to 20000 ->10$/100pts
示例: 用戶從 3000 到 12000 價格為 45$ 90$ 151.2 $ 200 $ => 最終價格為 = 486.2 $
如果你們可以用javascript給出解決方案,或者我可以用演算法解決方案,謝謝
uj5u.com熱心網友回復:
創建一個帶有閾值的表,然后在 JS 中對其進行迭代以累積價格。
這是一個可運行的片段:
const table = [
[10000, 10.00],
[ 7200, 5.40],
[ 4800, 3.75],
[ 2400, 2.50],
[ 1200, 2.20],
[ 0, 2.10],
];
function convert(points) {
let total = 0;
for (let [limit, price] of table) {
if (points > limit) {
total = Math.floor((points - limit) / 100) * price;
points = limit;
}
}
return total;
}
// IO handling
let [rngStart, rngEnd] = document.querySelectorAll("input");
let output = document.querySelector("span");
rngStart.addEventListener("input", refresh);
rngEnd.addEventListener("input", refresh);
function refresh() {
let start = rngStart.value;
let end = rngEnd.value
output.textContent = (convert(end) - convert(start)).toFixed(2);
}
refresh();
input[type=range] { width: 80% }
From: <input type="number" min="0" max="20000" step="100" value="3000">
To: <input type="number" min="0" max="20000" step="100" value="12000">
Price: <span></span>
uj5u.com熱心網友回復:
這是一個可以轉換為代碼的演算法:
- 讓我們有一個嵌套陣列,或者一個價格物件陣列(可索引和升序排序很重要),對于稱為
prices升序排序的價格,如下所示:
[[1200, 2400, 2.2],...]
lower讓我們在變數和中設定用戶輸入的下限和上限upper。- 讓我們將一個變數
finalPrice初始化為0. - 查找價格中第一個元素的索引,其上限為 >
lower。我們稱之為索引i。 - 現在運行
while lower < upper:
// calc the cost of this range
finalPrice = (min(prices[i][1], upper) - lower)/100 * prices[i]
// sets `lower` to the upper bound of the previous price,
// since we already calculated that.
lower = min(prices[i][1], upper)
// increment i to calc with the next price range
i = 1
由于滑塊在上側被限制為 20000,因此您可以確保i永遠不會超出范圍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/417534.html
標籤:
