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

我想编写一个带有 for 循环的函数,该函数在数组中找到数字 1 的索引,并将差值返回到最接近数字 1 的数字 2 的索引(数字 1 只出现一次)。例如:


Input: [1, 0, 0, 0, 2, 2, 2]

Output: 4


Input: [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”。谢谢阅读!


手掌心
浏览 104回答 5
5回答

皈依舞

以 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) {&nbsp; // determine position of 1&nbsp; const indxOf1 = arr.indexOf(1);&nbsp;&nbsp;&nbsp; // create array of distances&nbsp; const distances = [0, 0];&nbsp;&nbsp;&nbsp; // forward search&nbsp; for (let i = indxOf1; i < arr.length; i += 1) {&nbsp; &nbsp; if (arr[i] === 2) {&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; distances[0] += arr[i] !== 2 ? 1 : 0;&nbsp; }&nbsp;&nbsp;&nbsp; // if 1 is @ position 0 backwards search&nbsp; // is not necessary and minimum equals the&nbsp; // already found maximum&nbsp; if (indxOf1 < 1) {&nbsp; &nbsp; distances[1] = distances[0];&nbsp; &nbsp; return Math.min.apply(null, distances);&nbsp; }&nbsp;&nbsp;&nbsp; // backwards search&nbsp; for (let i = indxOf1; i >= 0; i -= 1) {&nbsp; &nbsp; if (arr[i] === 2) {&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; distances[1] += arr[i] !== 2 ? 1 : 0;&nbsp; }&nbsp;&nbsp;&nbsp; return Math.min.apply(null, distances);}

LEATH

像这样的东西可以完成这项工作。您可以使代码更短,但我已尝试说明清楚。一旦我们找到1,从那个索引开始并继续检查相邻的索引。我们还进行边界检查以确保我们不会溢出任何一端。function closest(arr) {&nbsp; &nbsp; const index = arr.findIndex(n => n === 1);&nbsp; &nbsp; const len = arr.length;&nbsp; &nbsp; let offset = 1;&nbsp; &nbsp; while (true) {&nbsp; &nbsp; &nbsp; &nbsp; const before = index - offset;&nbsp; &nbsp; &nbsp; &nbsp; const after = index + offset;&nbsp; &nbsp; &nbsp; &nbsp; const beforeBad = before < 0;&nbsp; &nbsp; &nbsp; &nbsp; const afterBad = after >= len;&nbsp; &nbsp; &nbsp; &nbsp; // It's necessary to check both, we could exceed the bounds on one side but not the other.&nbsp; &nbsp; &nbsp; &nbsp; if (beforeBad && afterBad) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if ((!beforeBad && arr[before] === 2) || (!afterBad && arr[after] === 2)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return offset;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ++offset;&nbsp; &nbsp; }&nbsp; &nbsp; return -1;}

智慧大石

这个怎么样:Output&nbsp;=&nbsp;Input.map((cur,idx,arr)=>cur==2?Math.abs(idx-arr.indexOf(1)):Infinity).sort()[0]

浮云间

您可以在此处避免for循环以支持更实用的样式。该函数minDist将m、n和 和作为参数,并返回数组中第一次出现的和任何出现的array之间的最小距离。mn首先,map用于为每个元素创建一个数组,其中包含到目标m元素的距离和当前元素的值。然后filter用于仅保留表示n元素的对。Thensort用于表示最接近的元素的对位于数组的开头。最后,[0]排序后的数组的pair表示最近的元素[0],这个最近的pair的元素就是最小距离。function minDist(m, n, array) {&nbsp; &nbsp; let index = array.indexOf(m);&nbsp; &nbsp; return array&nbsp; &nbsp; &nbsp; &nbsp; .map((x, i) => [Math.abs(i - index), x])&nbsp; &nbsp; &nbsp; &nbsp; .filter(p => p[1] === n)&nbsp; &nbsp; &nbsp; &nbsp; .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]));

HUH函数

您可以使用entries和reduce来解决这个问题。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 arrayfor (let x of arr.entries()) {&nbsp; if (x[1] === 2) indices.push(x[0]) ;}// Find the index that is closest to your goalconst nearestIndex = indices.reduce((prev, curr) => {&nbsp; return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);}); // 5console.log(Math.abs(goal - nearestIndex));&nbsp; // 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript