如何在数字序列中找到最低和最高值的夫妻?我想保存折线图的低/高值。
你能帮助我使用一段伪代码,这样人们就可以用自己喜欢的编程语言来实现答案。
我将使用它来生成D3.js的折线图。如果有人知道如何使用D3,我会非常乐意了解它。
数据样本: [ 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
这是我到目前为止(在Javascript中)。你们有没有看到我们可以优化这段代码?
// 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;
}
};
提前谢谢
答案 0 :(得分:0)
试试这个:
var arr = [20, 10, 11, 5, 15, 25, 10, 6, 15, 17, 26, 15, 7],
sorted = arr.sort(function(a,b){return a-b});
var array = [];
sorted.forEach(function(d,i){
var s = [];
s.push(sorted[i], sorted[(sorted.length-1) - i]);
array.push(s);
});
console.log(array);
工作小提琴here
答案 1 :(得分:0)
代码中缺少的部分是如何存储为数组或对象。
在您结束if condition
之前的for loop
中,您需要将log[k]
初始化为对象,然后像这样添加属性low
和high
< / p>
if (low > 0 && high > 0){
log[k] = {};
log[k].low = low;
log[k].high = high;
k++
low = high = 0;
}
这样做的结果是
array[0]{high: 20, low: 5}
array[1]{high: 25,low: 6}
如果你想要它是一个多维数组,你可以这样做:
将log[k]
初始化为ab空数组。
if (low > 0 && high > 0){
log[k] = [];
log[k]['low'] = low;
log[k]['high'] = high;
k++
low = high = 0;
}
结果
array[0]['high'] = 20
array[0]['low'] = 5
array[1]['high'] = 25
array[1]['low'] = 6