Home > Mobile >  Find the shortest part in array between numbers? [closed]
Find the shortest part in array between numbers? [closed]

Time:10-02

How to create a function to get the shortest part of the array that starts with value 11 and ends with 18 (included)?

var arr = [2, 11, 15, 18, 19, 11, 39, 20, 30, 15, 18, 5, 11, 1, 18];

Here we have 3 options [11, 15, 18], [11, 39, 20, 30, 15, 18] and [11, 1, 18] and I would like the function to always return the last shortest one (in this case [11, 1, 18]). It would be better if the function can be used for any start and end number.

CodePudding user response:

Could something like this work for you?

var arr = [2, 11, 15, 18, 19, 11, 39, 20, 30, 15, 18, 5, 11, 1, 18];


function getShortestPath(arr,startNumber,endNumber){
  let shortesPath = null;
  arr.forEach((val,index)=>{
    if(val === startNumber){
      let endIndex = index   arr.slice(index).findIndex((i)=>i === endNumber);
      if(endIndex >= 0){
        let currentPath = arr.slice(index,endIndex 1);
        if(shortesPath === null || (currentPath.length <= shortesPath.length)){
          shortesPath = currentPath; 
        }
      }
    }
  });
  return shortesPath;
}


console.log(getShortestPath(arr,11,18));

This function basically iterates the whole array and if the number is equal to the starting number it looks for the next occurrence of the end number. Than we create a temporary array from the current index to the index of the current occurrence of the end number. If this array´s length is smaller or equal (or if the shortesPath variable is null because we initialize it with this value) to the length of the shortesPath array we save this array into the shortesPath variable. At the end we simply return the shortesPath variable.

CodePudding user response:

This is my code. Next time please provide part of your code what you tried so far.

const arr = [2, 11, 15, 18, 19, 11, 39, 20, 30, 15, 18, 5, 11, 1, 18];

function getArrayFromRange(array,a, b) {
  const matchRegex = new RegExp(`${a}[\\d,]*${b}`, 'g')
  const val = JSON.stringify(array).replaceAll(`${a}`, `\n${a}`).match(matchRegex);
  return val[val.length-1].split(',').map(Number);
}

console.log(getArrayFromRange(arr,11,18))

  • Related