【问题标题】:Given an array index, how to get the n neighbors before and after index while wrapping?给定一个数组索引,如何在包装时获取索引前后的 n 个邻居?
【发布时间】:2021-04-23 15:44:06
【问题描述】:

给定一个数组和一个索引,我想返回围绕索引值的 n 个值。

例如: 数组:[0,1,2,3,4,5,6]

索引:1

值:2

结果: [6,0,1,2,3]

slice 派上用场,但我无法让包装要求工作。连接数组并从中工作的最简单的解决方案是什么? ([...数组, ...数组])

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您可以使用双精度数组和一个偏移量来调整切片。

    const
        getValues = (array, index, values) => {
            let offset = index - values;
            if (offset < 0) offset += array.length;
            return [...array, ...array].slice(offset, offset + 2 * values + 1);
        },
        array = [0, 1, 2, 3, 4, 5, 6],
        result = getValues(array, 1, 2);
        
    console.log(...result);

    【讨论】:

      【解决方案2】:

      我不确定这是否已经对这里的答案增加了很多,除非它可能需要覆盖大于数组长度的大小:

      const circle_number_for_size = (circle_size) => (number) => {
        const rem = number % circle_size;
        return rem + (rem < 0 ? circle_size : 0);
      };
      
      const circle_slice = (array, start, end) => {
        const circle_number = circle_number_for_size(array.length);
        let new_array = [];
        
        for(let i = start; i <= end; i++)
          new_array.push(array[circle_number(i)]);
        
        return new_array;
      };
      
      const neighbours = (array, centre_index, offset) =>
        circle_slice(array, centre_index - offset, centre_index + offset);
      
      console.log( ...neighbours([0,1,2,3,4,5,6], 1, 2) );
      console.log( ...neighbours([0,1,2,3,4,5,6,7,8,9], 0, 21) );

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-16
        • 1970-01-01
        • 2019-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多