[英]Find next highest and next lowest number in a sequence
How to find the lowest and highest value couples in a sequence of number? 如何找到数字序列中的最低和最高价值对? I want to save the low/high values of a line graph.
我想保存折线图的低/高值。
Can you help me with a piece of pseudo code so people can implement the answer in their favorite prog language. 您能帮我提供一段伪代码,以便人们以他们喜欢的编语言来实现答案。
I will be using this to generate a line graph with D3.js. 我将使用它来生成带有D3.js的折线图。 If anybody knows how to do this with D3 I would be more than happy to know about it.
如果有人知道如何使用D3做到这一点,我将非常高兴知道这一点。
Data Sample: [ 20 , 10, 11, 5 , 15, 25 , 10, 5 , 15, 17, 26 , 15, 7 ] 数据样本:[20,10,11,5,15,25,10,5,15,17,26,15,7]
Desired Result:
array[0][high] = 20
array[0][low] = 5
array[1][high] = 25
array[1][low] = 5
array[2][high] = 26
array[2][low] = 7
This is what I have so far (in Javascript). 这就是我到目前为止(用Javascript)所拥有的。 Do you guys see anyway we can optimize this piece of code?
你们是否看到我们可以优化这段代码?
// data sample
var data_sample = Array(5, 15, 20, 15, 6, 11, 21, 14, 9, 4, 15, 20, 15, 1, 10, 20, 4);
// algo
var low = high = k = 0;
var log = [];
for (var i = 0; i < data_sample.length; i++) {
var current = data_sample[i];
var m = i+1;
var next = data_sample[m];
if (typeof next == 'undefined') {
break;
}
if (current < next) {
if (low === 0) {
low = current;
} else if (current < low) {
low = current;
}
} else if (current > next && low !== 0) {
if (high === 0) {
high = current;
} else if (current > high) {
high = current;
}
}
if (low > 0 && high > 0){
log[k] = [];
log[k]['low'] = low;
log[k]['high'] = high;
k++
low = high = 0;
}
};
Thank you in advance 先感谢您
The missing part of your code is how to store as array or object. 代码缺少的部分是如何存储为数组或对象。
In your last if condition
before you end the for loop
you need to initialize log[k]
as an object then add the property low
and high
like this 在结束
for loop
之前的最后一个if condition
,您需要将log[k]
初始化为一个对象,然后像这样添加属性low
和high
if (low > 0 && high > 0){
log[k] = {};
log[k].low = low;
log[k].high = high;
k++
low = high = 0;
}
Doing so will result is 这样做的结果是
array[0]{high: 20, low: 5}
array[1]{high: 25,low: 6}
If you want it to be an multidimensional array you do it like this: Initialize log[k]
as ab empty array. 如果希望它是多维数组,则可以这样操作:将
log[k]
初始化为一个空数组。
if (low > 0 && high > 0){
log[k] = [];
log[k]['low'] = low;
log[k]['high'] = high;
k++
low = high = 0;
}
And the result 结果
array[0]['high'] = 20
array[0]['low'] = 5
array[1]['high'] = 25
array[1]['low'] = 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.