gpt4 book ai didi

javascript - 如何在两个数字之间的范围内动态创建不同的步长

转载 作者:行者123 更新时间:2023-12-02 20:58:16 26 4
gpt4 key购买 nike

我需要在具有不同给定步骤的两个数字之间创建动态范围,例如在 raneg1 中范围在 -9.00+4.00 之间,并且包含 3 个不同的步骤

-9.00 -> -6.50 = step is 0.50
-6.00 -> 0.00 = step is 0.25
+0.25 -> +4.00 = step is is0.50

如您所见,数据存储在 raneg1 字符串中,例如 -09.00_-6.50_0.50 作为 beginingof subrange_end of subrange_step

var rane1 = " -09.00_-6.50_0.50,-6.00_0.00_0.25,+0.25_+4.00_0.50";
var rane2 = " -04.00_-9.25_0.25,-09.00_-6.50_0.50,-6.00_0.00_0.25,+0.25_+8.00_0.50";

var ranearr1 = rane1.split(/\,\s*/).reduce(function(arr, item) {
if (item.length) {
arr.push(item.split('_'));
}
return arr;
}, []);

var ranearr2 = rane2.split(/\,\s*/).reduce(function(arr, item) {
if (item.length) {
arr.push(item.split('_'));
}
return arr;
}, []);

var list = [];
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最佳答案

不确定步骤部分。

第一种方法查找范围内有多少个独特的步骤。

第二种方法将检查范围字符串中每个范围所需的步数,并且仅计算唯一的步数。

var rane1 = " -09.00_-6.50_0.50,-6.00_0.00_0.25,+0.25_+4.00_0.50";
var rane2 = " -04.00_-9.25_0.25,-09.00_-6.50_0.50,-6.00_0.00_0.25,+0.25_+8.00_0.50";

const dynamicRange = (ranges) => {
//set to count different step
const counter = new Set();
//reduce to count min max value for each range
const minMax = ranges.split(/\,\s*/).reduce((res, range) => {
const [start, end, step] = range.split('_');
counter.add(step)
return [
res[0]&&parseFloat(res[0])<parseFloat(start) ? res[0] : start,
res[1]&&parseFloat(res[1])>parseFloat(end) ? res[1] : end,
]

}, [])
//return [start, end, different step]
return [...minMax, counter.size]
}


//count different steps need for each range
const dynamicRangeDiffSteps = (ranges) => {
//set to count unique number of steps needs for each range
const counter = new Set();
//reduce to count min max value for each range
const minMax = ranges.split(/\,\s*/).reduce((res, range) => {
const [start, end, step] = range.split('_');
//convert start, end step to float
const sFloat = parseFloat(start), eFloat = parseFloat(end), stepFloat = parseFloat(step)
//add number of steps needed to set
counter.add((eFloat-sFloat)/stepFloat)
return [
res[0]&&parseFloat(res[0])<sFloat ? res[0] : start,
res[1]&&parseFloat(res[1])>eFloat ? res[1] : end,
]

}, [])
//return [start, end, different step]
return [...minMax, counter.size]
}

console.log(dynamicRange(rane1))
console.log(dynamicRange(rane2))

console.log(dynamicRangeDiffSteps(rane1))
console.log(dynamicRangeDiffSteps(rane2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于javascript - 如何在两个数字之间的范围内动态创建不同的步长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61419440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com