为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript中的函数,返回两个给定数组索引的最近距离

Javascript中的函数,返回两个给定数组索引的最近距离

手掌心 2022-10-27 15:12:51
我想编写一个带有 for 循环的函数,该函数在数组中找到数字 1 的索引,并将差值返回到最接近数字 1 的数字 2 的索引(数字 1 只出现一次)。例如:Input: [1, 0, 0, 0, 2, 2, 2]Output: 4Input: [2, 0, 0, 0, 2, 2, 1, 0, 0 ,2]Output: 1我的尝试function closest (array) {  let elem=array.findIndex(index=>index === 1)  let numberplus=0;  let numberminus=0;  for (let i=elem; i<array.length; i++){    if (array[elem+1] === 2)    {numberplus+=array[elem+1]-elem;}    break;        }  for (let i=elem; i>=0; i--) {    if (array[elem-1] ===2)    {numberminus+=array[elem-1]-elem;}    break;    }   if (numberplus < numberminus) {      return numberplus   } else {   return numberminus}   }调用时,该函数仅返回“0”。谢谢阅读!
查看完整描述

5 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

以 1 的位置为起点,向上和向下循环(如有必要)数组:


const log = (arr, d) => console.log(`mimimal distance [${arr.join()}]: ${d}`);


const arr = [2, 0, 0, 0, 2, 2, 1, 0, 0, 2];

const arr2 = [1, 0, 0, 0, 2, 2, 2];

const arr3 = [2, 0, 1, 0, 2, 2, 2];

const arr4 = [2, 1, 0, 0, 2, 2, 2];


log(arr, clostes(arr));

log(arr2, clostes(arr2));

log(arr3, clostes(arr3));

log(arr4, clostes(arr4));


function clostes(arr) {

  // determine position of 1

  const indxOf1 = arr.indexOf(1);

  

  // create array of distances

  const distances = [0, 0];

  

  // forward search

  for (let i = indxOf1; i < arr.length; i += 1) {

    if (arr[i] === 2) {

      break;

    }

    distances[0] += arr[i] !== 2 ? 1 : 0;

  }

  

  // if 1 is @ position 0 backwards search

  // is not necessary and minimum equals the

  // already found maximum

  if (indxOf1 < 1) {

    distances[1] = distances[0];

    return Math.min.apply(null, distances);

  }

  

  // backwards search

  for (let i = indxOf1; i >= 0; i -= 1) {

    if (arr[i] === 2) {

      break;

    }

    distances[1] += arr[i] !== 2 ? 1 : 0;

  }

  

  return Math.min.apply(null, distances);

}


查看完整回答
反对 回复 2022-10-27
?
LEATH

TA贡献1936条经验 获得超6个赞

像这样的东西可以完成这项工作。您可以使代码更短,但我已尝试说明清楚。一旦我们找到1,从那个索引开始并继续检查相邻的索引。我们还进行边界检查以确保我们不会溢出任何一端。


function closest(arr) {

    const index = arr.findIndex(n => n === 1);

    const len = arr.length;


    let offset = 1;

    while (true) {

        const before = index - offset;

        const after = index + offset;

        const beforeBad = before < 0;

        const afterBad = after >= len;


        // It's necessary to check both, we could exceed the bounds on one side but not the other.

        if (beforeBad && afterBad) {

            break;

        }


        if ((!beforeBad && arr[before] === 2) || (!afterBad && arr[after] === 2)) {

            return offset;

        }

        ++offset;

    }


    return -1;

}


查看完整回答
反对 回复 2022-10-27
?
智慧大石

TA贡献1946条经验 获得超3个赞

这个怎么样:

Output = Input.map((cur,idx,arr)=>cur==2?Math.abs(idx-arr.indexOf(1)):Infinity).sort()[0]



查看完整回答
反对 回复 2022-10-27
?
浮云间

TA贡献1829条经验 获得超4个赞

您可以在此处避免for循环以支持更实用的样式。该函数minDist将m、n和 和作为参数,并返回数组中第一次出现的和任何出现的array之间的最小距离。mn


首先,map用于为每个元素创建一个数组,其中包含到目标m元素的距离和当前元素的值。然后filter用于仅保留表示n元素的对。Thensort用于表示最接近的元素的对位于数组的开头。最后,[0]排序后的数组的pair表示最近的元素[0],这个最近的pair的元素就是最小距离。


function minDist(m, n, array) {

    let index = array.indexOf(m);

    return array

        .map((x, i) => [Math.abs(i - index), x])

        .filter(p => p[1] === n)

        .sort()[0][0];

}


console.log(minDist(1, 2, [1, 0, 0, 0, 2, 2, 2]));

console.log(minDist(1, 2, [2, 0, 0, 0, 2, 2, 1, 0, 0, 2]));


查看完整回答
反对 回复 2022-10-27
?
HUH函数

TA贡献1836条经验 获得超4个赞

您可以使用entriesreduce来解决这个问题。

const arr = [2, 0, 0, 0, 2, 2, 1, 0, 0 ,2];

const goal = arr.indexOf(1);

const indices = [];


// Find all the indices of 2 in the array

for (let x of arr.entries()) {

  if (x[1] === 2) indices.push(x[0]) ;

}


// Find the index that is closest to your goal

const nearestIndex = indices.reduce((prev, curr) => {

  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);

}); // 5


console.log(Math.abs(goal - nearestIndex));  // 1


查看完整回答
反对 回复 2022-10-27
  • 5 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信