更好的做法:始终从阵列中取出6件物品

时间:2019-07-17 06:56:24

标签: javascript arrays algorithm

我需要一点算法帮助。

我想从数组中提取6个项目的范围。起点是给定索引,如果可能的话,我想让项目在给定索引之前和之后平均分配。

我已经做到了,但是我寻找的不仅仅是改变范围。我该如何改善我的代码?

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
const area = 7;
const currentIndex = 5;
const arrayLength = array.length;


let rangeBegin = currentIndex - Math.floor((area - 1) / 2);
let rangeEnd = currentIndex + Math.ceil((area - 1) / 2);

if (rangeBegin < 0) {
  const offset = -rangeBegin;
  rangeBegin += offset;
  rangeEnd += offset;
}

if (rangeEnd >= arrayLength) {
  const offset = rangeEnd - arrayLength;
  rangeBegin -= offset;
  rangeEnd -= offset;
}
slicedArray = array.slice(rangeBegin, rangeEnd);

console.log(slicedArray)

https://playcode.io/377252?tabs=script.js,preview,console

2 个答案:

答案 0 :(得分:2)

您可以通过减去一半大小来移动索引,并为负索引取最大值,对于大于数组长度减去所需子数组大小的索引取最小值。

 value  array                           index  adj  max  min
 -----  ------------------------------  -----  ---  ---  ---
            v                              
    2    1, 2, 3, 4, 5, 6, 7, 8, 9, 10     1    -1    0    0
        [             ]

                     v        
    5    1, 2, 3, 4, 5, 6, 7, 8, 9, 10     4     2    2    2
              [             ]

                                    vv        
   10    1, 2, 3, 4, 5, 6, 7, 8, 9, 10     9     7    7    5
                       [              ]

function getSub(array, index, size) {
    if (size >= array.length) return array;
    var pivot = Math.floor(index - (size - 1) / 2),
        max = Math.max(pivot, 0),
        min = Math.min(max, array.length - size);
    return array.slice(min, min + size);
}

console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1, 5));
console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4, 5));
console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9, 5));

console.log(...getSub([1, 2, 3, 4], 1, 5));
console.log(...getSub([1, 2, 3, 4], 4, 5));
console.log(...getSub([1, 2, 3, 4], 9, 5));

答案 1 :(得分:0)

const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
const area = 7;
const currentIndex = 5;
const arrayLength = array.length;


let rangeBegin = currentIndex - Math.floor((area - 1 ) /2);
if(rangeBegin < 0) {
  rangeBegin = 0;
}
let rangeEnd = rangeBegin + area - 1;
if(rangeEnd >= arrayLength) {
  rangeEnd = arrayLength;
  rangeBegin = arrayLength - area;
}

slicedArray = array.slice(rangeBegin, rangeEnd);

!!!这段代码不会检查数组的长度是否小于我们所需的面积。