如何使用滑块计算价格[算法问题]

how to calculate price using slider [algorithmic problem]

我有一个滑块让用户在 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 中给出解决方案,或者我可以使用算法解决方案,谢谢

这是一个可以转换为代码的算法:

  1. 让我们有一个嵌套数组,或价格对象数组(重要的是可索引和升序排序),对于称为 prices 的价格按如下升序排序:
[[1200, 2400, 2.2],...]
  1. 让我们在变量 lowerupper 中设置用户输入的下限和上限。
  2. 让我们将变量 finalPrice 初始化为 0
  3. 找到 prices 中第一个元素的索引,其上限 > lower。我们称此索引为 i.
  4. 现在运行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 永远不会超出范围。

使用阈值创建一个 table,然后在 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>