查找以给定项为中心的数组子集

时间:2017-11-30 04:25:09

标签: javascript algorithm pseudocode

我试图找到一种更好的方法从现有数组中返回一系列数组值。

对于列表/数组,请说:

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

我想选择以给定数字x为中心的5个数字范围。

(Psuedocode,因为我猜我真的在这里引用数组索引..值与位置无关)

因此,如果x为4,我们可以返回一个以此为中心的范围:

[2,3,4,5,6]

但如果x为2,我们就无法将范围居中,所以我们必须尽力而为:

[1,2,3,4,5]

...没有居中,但至少我们已经返回了5个数字。

同样,如果x为10:

[5,6,7,8,9,10]

... 10是限制,所以不能居中,所以5个数字被推倒。

我已经在一些JS代码中使用了这个,但感觉太多的条件有太多的代码。

想知道是否有任何可以帮助的已知方法或算法?

2 个答案:

答案 0 :(得分:4)

你可以这样做。



var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


function findSubset(arr, item) {
  // check index
  var index = arr.indexOf(item);
  // if element not found then return
  if (index == -1) return;

  // if element is at starting position 
  // then return first 5 element
  if (index < 3)
    return arr.slice(0, 5);

  // if elements at ending position
  // then return last 5 elements
  if (index > arr.length - 4)
    return arr.slice(-5);

  // otherwisse return elements based on the index
  // within the required range
  return arr.slice(index - 2, index + 3);
}

console.log(
  findSubset(arr, 1),
  findSubset(arr, 10),
  findSubset(arr, 5),
  findSubset(arr, 9),
  findSubset(arr, 3)
)
&#13;
&#13;
&#13;

具有不同计数的通用解决方案。

&#13;
&#13;
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


function findSubset(arr, item, count = 5) {
  var index = arr.indexOf(item),
    // calculate floor and ceil value for comparison 
    // and getting subset array
    f = Math.floor(count / 2),
    c = Math.ceil(count / 2);
  
  if (index == -1) return;
  
  if (index < c)
    return arr.slice(0, count);

  if (index > arr.length - c - 1)
    return arr.slice(-count);

  return arr.slice(index - 2, index + c);
}

console.log(
  findSubset(arr, 1, 3),
  findSubset(arr, 10, 7),
  findSubset(arr, 5, 1),
  findSubset(arr, 9, 4),
  findSubset(arr, 8, 1),
  findSubset(arr, 7, 3),
  findSubset(arr, 3, 9)
)
&#13;
&#13;
&#13;

答案 1 :(得分: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
                       [              ]

&#13;
&#13;
function getSub(array, value, size) {
    var index = array.indexOf(value) - (size - 1) / 2,
        max = Math.max(index, 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], 2, 5));
console.log(getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5, 5));
console.log(getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10, 5));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;